text stringlengths 11 4.05M |
|---|
package main
import (
"github.com/kjx98/gobot"
)
func main() {
cfg := gobot.NewConfig("")
rebot, err := gobot.NewWecat(cfg)
if err != nil {
panic(err)
}
rebot.SetRobotName("JacK")
rebot.RegisterTimeCmd()
rebot.Start()
}
|
package handler
import (
"k8s.io/klog/v2"
"private-dns/endpoint"
"private-dns/plan"
)
// Handler interface contains the methods that are required
type Handler interface {
ApplyChanges(changes HashableDNSChanges) error
ObjectCreated(obj interface{}) HashableDNSChanges
ObjectDeleted(obj interface{}) HashableDNSChanges
ObjectUpdated(objOld, objNew interface{}) HashableDNSChanges
}
// DNSEntry yea
type DNSEntry struct {
fqdn string
recordtype string
ttl int
ip string
}
// HashableDNSChanges yea
type HashableDNSChanges struct {
old DNSEntry
new DNSEntry
}
// HashDNSToPlan Plan is not hashable, so not able to add to workqueue
func HashDNSToPlan(changes HashableDNSChanges) (plan.Changes, bool) {
apply := plan.Changes{}
applyIt := false
if changes.old != (DNSEntry{}) && changes.new != (DNSEntry{}) {
klog.Infof("HashDNSToPlan: Update %s %s", changes.new.fqdn, changes.new.ip)
apply = plan.Changes{
UpdateOld: []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL(changes.old.fqdn, changes.old.recordtype , endpoint.TTL(changes.old.ttl), changes.old.ip) },
UpdateNew: []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL(changes.new.fqdn, changes.new.recordtype , endpoint.TTL(changes.old.ttl), changes.new.ip) },
}
applyIt = true
} else if changes.new != (DNSEntry{}) {
klog.Infof("HashDNSToPlan: Add %s %s", changes.new.fqdn, changes.new.ip)
apply = plan.Changes{
Create: []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL(changes.new.fqdn, changes.new.recordtype , endpoint.TTL(changes.old.ttl), changes.new.ip) },
}
applyIt = true
} else if changes.old != (DNSEntry{}) {
klog.Info("HashDNSToPlan: Delete")
apply = plan.Changes{
Delete: []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL(changes.old.fqdn, changes.old.recordtype , endpoint.TTL(changes.old.ttl), changes.old.ip) },
}
applyIt = true
} else {
klog.Info("DNSHandler: Nothing to do")
}
return apply, applyIt
}
|
package handler
import (
"echo/server"
"fmt"
"github.com/labstack/echo"
_ "mysql-master"
"net/http"
)
type menu struct {
Id_menu string
Nama_menu string
Deskripsi string
Jenis string
Harga string
Url_gambar string
Total_order string
}
var data []menu
func BacaData(c echo.Context) error {
menu_makanan()
return c.JSON(http.StatusOK, data)
}
func TambahData(c echo.Context) error {
db, err := server.Koneksi()
defer db.Close()
var nama = c.FormValue("Nama_menu")
var deskripsi = c.FormValue("Deskripsi")
var url_gambar = c.FormValue("Url_gambar")
var jenis = c.FormValue("Jenis")
var harga = c.FormValue("Harga")
_, err = db.Exec("insert into tbl_menu values (?,?,?,?,?,?)", nil, nama, deskripsi, url_gambar, jenis, harga)
if err != nil {
fmt.Println("Menu Gagal Ditambahkan")
return c.JSON(http.StatusOK, "Gagal Menambahkan Menu")
} else {
fmt.Println("Menu Berhasil Ditambahkan")
return c.JSON(http.StatusOK, "Berhasil Menambahkan Menu")
}
}
func UbahData(c echo.Context) error {
db, err := server.Koneksi()
defer db.Close()
var nama = c.FormValue("Nama_menu")
var deskripsi = c.FormValue("Deskripsi")
var url_gambar = c.FormValue("Url_gambar")
var jenis = c.FormValue("Jenis")
var harga = c.FormValue("Harga")
var id = c.FormValue("Id_menu")
_, err = db.Exec("update tbl_menu set nama_menu = ?, deskripsi = ?, harga = ?, jenis = ?,url_gambar = ? where id_menu = ?", nama, deskripsi, harga, jenis, url_gambar, id)
if err != nil {
fmt.Println("Menu Gagal Diubah")
return c.JSON(http.StatusOK, "Gagal Mengubah Menu")
} else {
fmt.Println("Menu Berhasil Diubah")
return c.JSON(http.StatusOK, "Berhasil Mengubah Menu")
}
}
func HapusData(c echo.Context) error {
db, err := server.Koneksi()
defer db.Close()
var id = c.FormValue("Id_menu")
_, err = db.Exec("delete from tbl_menu where id_menu = ?", id)
if err != nil {
fmt.Println("Menu Gagal Dihapus")
return c.JSON(http.StatusOK, "Gagal Menghapus Menu")
} else {
fmt.Println("Menu Berhasil Dihapus")
return c.JSON(http.StatusOK, "Berhasil Menghapus Menu")
}
}
func menu_makanan() {
data = nil
db, err := server.Koneksi()
if err != nil {
fmt.Println(err.Error())
return
}
defer db.Close()
rows, err := db.Query("select * from tbl_menu")
if err != nil {
fmt.Println(err.Error())
return
}
defer rows.Close()
for rows.Next() {
var each = menu{}
var err = rows.Scan(&each.Id_menu, &each.Nama_menu, &each.Deskripsi, &each.Url_gambar, &each.Jenis, &each.Harga)
if err != nil {
fmt.Println(err.Error())
return
}
data = append(data, each)
fmt.Println(data)
}
if err = rows.Err(); err != nil {
fmt.Println(err.Error())
return
}
}
func InputOrder(c echo.Context) error {
db, err := server.Koneksi()
defer db.Close()
var id = c.FormValue("id")
var nama_pemesan = c.FormValue("nama_pemesan")
var nomor_telephone = c.FormValue("nomor_telephone")
var alamat = c.FormValue("alamat")
var jumlah = c.FormValue("jumlah")
_, err = db.Exec("insert into tbl_order values (?,?,?,?,?,?)", nil, id, nama_pemesan, nomor_telephone, alamat, jumlah)
if err != nil {
fmt.Println("Pesanan Gagal Dibuat")
return c.HTML(http.StatusOK, "<strong>Gagal Menambahkan Pesanan</strong>")
} else {
fmt.Println("Pesanan Berhasil Dibuat")
return c.HTML(http.StatusOK, "<script>alert('Berhasil Menambahkan Pesanan, Silahkan menunggu konfirmasi dari kami..Terima Kasih');window.location = 'http://localhost:1323';</script>")
}
return c.Redirect(http.StatusSeeOther, "/")
}
func BacaPopuler(c echo.Context) error {
menu_populer()
return c.JSON(http.StatusOK, data)
}
func menu_populer() {
data = nil
db, err := server.Koneksi()
if err != nil {
fmt.Println(err.Error())
return
}
defer db.Close()
rows, err := db.Query("SELECT * FROM `vw_totalorder` ORDER BY `vw_totalorder`.`total_older` DESC LIMIT 4;")
if err != nil {
fmt.Println(err.Error())
return
}
defer rows.Close()
for rows.Next() {
var each = menu{}
var err = rows.Scan(&each.Id_menu, &each.Nama_menu, &each.Deskripsi, &each.Url_gambar, &each.Jenis, &each.Harga, &each.Total_order)
if err != nil {
fmt.Println(err.Error())
return
}
data = append(data, each)
fmt.Println(data)
}
if err = rows.Err(); err != nil {
fmt.Println(err.Error())
return
}
}
|
// Copyright 2023 PingCAP, Inc.
//
// 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 expression
import (
"fmt"
"testing"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/charset"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/testkit/testutil"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/collate"
"github.com/stretchr/testify/require"
)
func TestIlike(t *testing.T) {
ctx := createContext(t)
tests := []struct {
input string
pattern string
escape int
generalMatch int
unicodeMatch int
}{
{"a", "", 0, 0, 0},
{"a", "a", 0, 1, 1},
{"ü", "Ü", 0, 0, 0},
{"a", "á", 0, 0, 0},
{"a", "b", 0, 0, 0},
{"aA", "Aa", 0, 1, 1},
{"áAb", `Aa%`, 0, 0, 0},
{"áAb", `%ab%`, 0, 1, 1},
{"", "", 0, 1, 1},
{"ß", "s%", 0, 0, 0},
{"ß", "%s", 0, 0, 0},
{"ß", "ss", 0, 0, 0},
{"ß", "s", 0, 0, 0},
{"ss", "%ß%", 0, 0, 0},
{"ß", "_", 0, 1, 1},
{"ß", "__", 0, 0, 0},
{"啊aaa啊啊啊aa", "啊aaa啊啊啊aa", 0, 1, 1},
// escape tests
{"abc", "ABC", int('a'), 1, 1},
{"abc", "ABC", int('A'), 0, 0},
{"aaz", "Aaaz", int('a'), 1, 1},
{"AAz", "AAAAz", int('a'), 0, 0},
{"a", "Aa", int('A'), 1, 1},
{"a", "AA", int('A'), 1, 1},
{"Aa", "AAAA", int('A'), 1, 1},
{"gTp", "AGTAp", int('A'), 1, 1},
{"gTAp", "AGTAap", int('A'), 1, 1},
{"A", "aA", int('a'), 1, 1},
{"a", "aA", int('a'), 1, 1},
{"aaa", "AAaA", int('a'), 1, 1},
{"a啊啊a", "a啊啊A", int('A'), 0, 0},
{"啊aaa啊啊啊aa", "啊aaa啊啊啊aa", int('A'), 1, 1},
{"啊aAa啊啊啊aA", "啊AAA啊啊啊AA", int('a'), 1, 1},
{"啊aaa啊啊啊aa", "啊aaa啊啊啊aa", int('a'), 0, 0},
}
var charsetAndCollationGeneral = [][]string{{"utf8mb4", "utf8mb4_general_ci"}, {"utf8", "utf8_general_ci"}}
for _, charsetAndCollation := range charsetAndCollationGeneral {
for _, tt := range tests {
comment := fmt.Sprintf(`for input = "%s", pattern = "%s", escape = "%s", collation = "%s"`, tt.input, tt.pattern, string(rune(tt.escape)), charsetAndCollation[1])
fc := funcs[ast.Ilike]
inputs := datumsToConstants(types.MakeDatums(tt.input, tt.pattern, tt.escape))
f, err := fc.getFunction(ctx, inputs)
require.NoError(t, err, comment)
f.SetCharsetAndCollation(charsetAndCollation[0], charsetAndCollation[1])
f.setCollator(collate.GetCollator(charsetAndCollation[1]))
r, err := evalBuiltinFunc(f, chunk.Row{})
require.NoError(t, err, comment)
testutil.DatumEqual(t, types.NewDatum(tt.generalMatch), r, comment)
}
}
var charsetAndCollationUnicode = [][]string{
{"utf8mb4", "utf8mb4_bin"},
{"utf8mb4", "utf8mb4_unicode_ci"},
{"utf8", "utf8_bin"},
{"utf8", "utf8_unicode_ci"}}
for _, charsetAndCollation := range charsetAndCollationUnicode {
for _, tt := range tests {
comment := fmt.Sprintf(`for input = "%s", pattern = "%s", escape = "%s", collation = "%s"`, tt.input, tt.pattern, string(rune(tt.escape)), charsetAndCollation[1])
fc := funcs[ast.Ilike]
inputs := datumsToConstants(types.MakeDatums(tt.input, tt.pattern, tt.escape))
f, err := fc.getFunction(ctx, inputs)
require.NoError(t, err, comment)
f.SetCharsetAndCollation(charsetAndCollation[0], charsetAndCollation[1])
f.setCollator(collate.GetCollator(charsetAndCollation[1]))
r, err := evalBuiltinFunc(f, chunk.Row{})
require.NoError(t, err, comment)
testutil.DatumEqual(t, types.NewDatum(tt.unicodeMatch), r, comment)
}
}
}
var vecBuiltinIlikeCases = map[string][]vecExprBenchCase{
ast.Ilike: {
{
retEvalType: types.ETInt,
childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETInt},
geners: []dataGenerator{
&selectStringGener{
candidates: []string{"aaa", "abc", "aAa", "AaA", "a啊啊Aa啊", "啊啊啊啊", "üÜ", "Ü", "a", "A"},
randGen: newDefaultRandGen(),
},
&selectStringGener{
candidates: []string{"aaa", "ABC", "啊啊啊啊", "üÜ", "ü", "a", "A"},
randGen: newDefaultRandGen(),
}},
childrenFieldTypes: []*types.FieldType{types.NewFieldTypeBuilder().SetType(mysql.TypeString).SetFlag(mysql.BinaryFlag).SetCharset(charset.CharsetBin).SetCollate(charset.CollationBin).BuildP()},
},
{
retEvalType: types.ETInt,
childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETInt},
geners: []dataGenerator{
&selectStringGener{
candidates: []string{"aaa", "abc", "aAa", "AaA", "a啊啊Aa啊", "啊啊啊啊", "üÜ", "Ü", "a", "A"},
// candidates: []string{"abc"},
randGen: newDefaultRandGen(),
},
&selectStringGener{
candidates: []string{"aaa", "ABC", "啊啊啊啊", "üÜ", "ü", "a", "A"},
// candidates: []string{"ABC"},
randGen: newDefaultRandGen(),
}},
childrenFieldTypes: []*types.FieldType{types.NewFieldTypeBuilder().SetType(mysql.TypeString).SetFlag(mysql.BinaryFlag).SetCharset(charset.CharsetBin).SetCollate(charset.CollationBin).BuildP()},
},
{
retEvalType: types.ETInt,
childrenTypes: []types.EvalType{types.ETString, types.ETString, types.ETInt},
geners: []dataGenerator{
&selectStringGener{
candidates: []string{"aaa", "abc", "aAa", "AaA", "a啊啊Aa啊", "啊啊啊啊", "üÜ", "Ü", "a", "A"},
randGen: newDefaultRandGen(),
},
&selectStringGener{
candidates: []string{"aaa", "ABC", "啊啊啊啊", "üÜ", "ü", "a", "A"},
randGen: newDefaultRandGen(),
}},
childrenFieldTypes: []*types.FieldType{types.NewFieldTypeBuilder().SetType(mysql.TypeString).SetFlag(mysql.BinaryFlag).SetCharset(charset.CharsetBin).SetCollate(charset.CollationBin).BuildP()},
},
},
}
func TestVectorizedBuiltinIlikeFunc(t *testing.T) {
vecBuiltinIlikeCases[ast.Ilike][0].constants = make([]*Constant, 3)
vecBuiltinIlikeCases[ast.Ilike][1].constants = make([]*Constant, 3)
vecBuiltinIlikeCases[ast.Ilike][2].constants = make([]*Constant, 3)
vecBuiltinIlikeCases[ast.Ilike][0].constants[2] = getIntConstant(int64(byte('A')))
vecBuiltinIlikeCases[ast.Ilike][1].constants[2] = getIntConstant(int64(byte('a')))
vecBuiltinIlikeCases[ast.Ilike][2].constants[2] = getIntConstant(int64(byte('\\')))
testVectorizedBuiltinFunc(t, vecBuiltinIlikeCases)
}
|
package resolvers
import (
"log"
"github.com/graphql-go-example/conf"
"github.com/graphql-go-example/model"
)
//InsertComment -
func InsertComment(comment *model.Comment) error {
strsql := `
INSERT INTO comments(user_id, post_id, title, body)
VALUES (?, ?, ?, ?)`
res, err := conf.DB.Exec(strsql, comment.UserID, comment.PostID, comment.Title, comment.Body)
if err != nil {
log.Printf("[comments] Error INSERT: [%s] \nError: [%s]\n", strsql, err.Error())
return err
}
comment.ID, _ = res.LastInsertId()
return nil
}
//RemoveCommentByID -
func RemoveCommentByID(id int) error {
_, err := conf.DB.Exec("DELETE FROM comments WHERE id=?", id)
return err
}
//GetCommentByIDAndPost -
func GetCommentByIDAndPost(id int64, postID int64) (*model.Comment, error) {
var (
userID int64
title, body string
)
err := conf.DB.QueryRow(`
SELECT user_id, title, body
FROM posts
WHERE id=?
AND post_id=?
`, id, postID).Scan(&userID, &title, &body)
if err != nil {
return nil, err
}
return &model.Comment{
ID: id,
UserID: userID,
PostID: postID,
Title: title,
Body: body,
}, nil
}
//GetCommentsForPost -
func GetCommentsForPost(id int64) ([]*model.Comment, error) {
rows, err := conf.DB.Query(`
SELECT c.id, c.user_id, c.title, c.body
FROM comments AS c
WHERE c.post_id=?
`, id)
if err != nil {
return nil, err
}
defer rows.Close()
var (
comments = []*model.Comment{}
cid, userID int64
title, body string
)
for rows.Next() {
if err = rows.Scan(&cid, &userID, &title, &body); err != nil {
return nil, err
}
comments = append(comments, &model.Comment{
ID: cid,
UserID: userID,
PostID: id,
Title: title,
Body: body,
})
}
return comments, nil
}
|
// Copyright 2021 BoCloud
//
// 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 test
import (
"context"
"flag"
"fmt"
"os"
"time"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
"k8s.io/klog/v2/klogr"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
// WrapReconcile returns a reconcile.Reconcile implementation that delegates to inner and
// writes the request to requests after Reconcile is finished.
func WrapReconcile(inner reconcile.Reconciler) (reconcile.Reconciler, chan reconcile.Request) {
requests := make(chan reconcile.Request)
fn := reconcile.Func(func(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
result, err := inner.Reconcile(ctx, req)
requests <- req
return result, err
})
return fn, requests
}
// WrapReconcileFunc returns a reconcile.Func implementation that delegates to inner and
// writes the request to requests after Reconcile is finished.
func WrapReconcileFunc(inner reconcile.Func) (reconcile.Func, chan reconcile.Request) {
requests := make(chan reconcile.Request)
fn := func(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
result, err := inner.Reconcile(ctx, req)
requests <- req
return result, err
}
return fn, requests
}
// DrainChan drains the request chan time for drainTimeout
func DrainChan(requests <-chan reconcile.Request, timeout time.Duration) {
for {
select {
case <-requests:
continue
case <-time.After(timeout):
return
}
}
}
func SetupLogger() {
level, ok := os.LookupEnv("LOG_LEVEL")
if !ok {
level = "-1"
}
klog.InitFlags(nil)
_ = flag.Set("v", level)
logf.SetLogger(klogr.New().V(5))
}
func StartTestEnv() (env *envtest.Environment, cfg *rest.Config, cli client.Client, err error) {
return StartTestEnvWithCRDAndScheme([]string{}, scheme.Scheme)
}
func StartTestEnvWithCRD(CRDDirectoryPaths []string) (env *envtest.Environment, cfg *rest.Config, cli client.Client, err error) {
return StartTestEnvWithCRDAndScheme(CRDDirectoryPaths, scheme.Scheme)
}
func StartTestEnvWithCRDAndScheme(CRDDirectoryPaths []string, scheme *runtime.Scheme) (env *envtest.Environment, cfg *rest.Config, cli client.Client, err error) {
env = &envtest.Environment{
CRDDirectoryPaths: CRDDirectoryPaths,
}
cfg, err = env.Start()
if err != nil {
return
}
if cfg == nil {
err = fmt.Errorf("no rest config created")
return
}
// +kubebuilder:scaffold:scheme
cli, err = client.New(cfg, client.Options{Scheme: scheme})
if err != nil {
return
}
if cli == nil {
err = fmt.Errorf("no k8s client created")
}
return
}
func GenerateGetNameFunc(namePrefix string) func() string {
var index = 0
return func() string {
for index < 10000 {
name := fmt.Sprintf("%s-%d", namePrefix, index)
index++
index %= 10000
return name
}
return ""
}
}
|
package main
import (
"flag"
"log"
"net/http"
)
//go:generate /bin/sh -c "cd ./root-fs && gopherjs build --minify -v -o app.js"
var (
addrFlag = flag.String("addr", ":5555", "server address:port")
)
func main() {
flag.Parse()
http.Handle("/", http.FileServer(http.Dir("./root-fs")))
err := http.ListenAndServe(*addrFlag, nil)
if err != nil {
log.Fatal(err)
}
}
|
package main
import (
"fmt"
)
func stringp(s string) *string {
return &s
}
func main() {
type person struct {
FirstName string
MiddleName *string
LastName string
}
// s := "Perry"
// p := person{
// FirstName: "Pat",
// MiddleName: &s,
// LastName: "Peterson",
// }
p := person{
FirstName: "Pat",
MiddleName: stringp("Perry"),
LastName: "Peterson",
}
fmt.Println(p)
fmt.Println(*p.MiddleName)
}
|
package controller
var DEMO bool
const DEMO_TRANSACTIONS = `
[
{
"Status":"Confirmed",
"Date":"08 Jun 17 19:45 +0000",
"Amount":"37.80251 C",
"Type":"Transaction",
"Total":"37.80251 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"08 Jun 17 22:34 +0000",
"Amount":"-0.11250 C",
"Type":"Transaction",
"Total":"37.69001 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"09 Jun 17 18:39 +0000",
"Amount":"-0.11250 C",
"Type":"Transaction",
"Total":"37.57751 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"10 Jun 17 17:28 +0000",
"Amount":"-0.11250 C",
"Type":"Transaction",
"Total":"37.46501 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 20:59 +0000",
"Amount":"-36.95404 C",
"Type":"Transaction",
"Total":"0.51096 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 22:20 +0000",
"Amount":"40.00000 C",
"Type":"Transaction",
"Total":"40.51096 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 22:46 +0000",
"Amount":"-11.78796 C",
"Type":"Transaction",
"Total":"28.72300 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 22:46 +0000",
"Amount":"-20.85861 C",
"Type":"Transaction",
"Total":"7.86439 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 22:46 +0000",
"Amount":"-4.79004 C",
"Type":"Transaction",
"Total":"3.07435 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:30 +0000",
"Amount":"290.00000 C",
"Type":"Transaction",
"Total":"293.07435 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:30 +0000",
"Amount":"-9.34383 C",
"Type":"Transaction",
"Total":"283.73052 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:30 +0000",
"Amount":"-16.94657 C",
"Type":"Transaction",
"Total":"266.78394 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:30 +0000",
"Amount":"-3.95982 C",
"Type":"Transaction",
"Total":"262.82412 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:30 +0000",
"Amount":"-14.05395 C",
"Type":"Transaction",
"Total":"248.77017 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-12.53175 C",
"Type":"Transaction",
"Total":"236.23842 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-7.35033 C",
"Type":"Transaction",
"Total":"228.88809 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-8.73603 C",
"Type":"Transaction",
"Total":"220.15206 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-22.81949 C",
"Type":"Transaction",
"Total":"197.33257 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-6.80929 C",
"Type":"Transaction",
"Total":"190.52328 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-18.47789 C",
"Type":"Transaction",
"Total":"172.04539 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-8.83828 C",
"Type":"Transaction",
"Total":"163.20710 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-13.24947 C",
"Type":"Transaction",
"Total":"149.95763 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-14.45968 C",
"Type":"Transaction",
"Total":"135.49795 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-16.32189 C",
"Type":"Transaction",
"Total":"119.17606 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-8.28080 C",
"Type":"Transaction",
"Total":"110.89526 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-11.23600 C",
"Type":"Transaction",
"Total":"99.65926 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-13.57803 C",
"Type":"Transaction",
"Total":"86.08123 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-11.23600 C",
"Type":"Transaction",
"Total":"74.84524 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-10.36200 C",
"Type":"Transaction",
"Total":"64.48324 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-18.18699 C",
"Type":"Transaction",
"Total":"46.29625 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-16.74349 C",
"Type":"Transaction",
"Total":"29.55276 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-11.09116 C",
"Type":"Transaction",
"Total":"18.46160 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-8.94054 C",
"Type":"Transaction",
"Total":"9.52106 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"18 Jul 17 23:42 +0000",
"Amount":"-5.44248 C",
"Type":"Transaction",
"Total":"4.07858 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"23 Jul 17 21:16 +0000",
"Amount":"-0.75000 C",
"Type":"Transaction",
"Total":"3.32858 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"23 Jul 17 21:21 +0000",
"Amount":"-0.75000 C",
"Type":"Transaction",
"Total":"2.57858 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 05:12 +0000",
"Amount":"290.00000 C",
"Type":"Transaction",
"Total":"292.57858 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-5.36465 C",
"Type":"Transaction",
"Total":"287.21394 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-8.60972 C",
"Type":"Transaction",
"Total":"278.60422 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-16.90149 C",
"Type":"Transaction",
"Total":"261.70273 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-16.90149 C",
"Type":"Transaction",
"Total":"244.80124 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-24.85814 C",
"Type":"Transaction",
"Total":"219.94310 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-29.74744 C",
"Type":"Transaction",
"Total":"190.19566 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-21.55973 C",
"Type":"Transaction",
"Total":"168.63594 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-27.57442 C",
"Type":"Transaction",
"Total":"141.06152 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-23.48906 C",
"Type":"Transaction",
"Total":"117.57246 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"27 Jul 17 23:33 +0000",
"Amount":"-17.89618 C",
"Type":"Transaction",
"Total":"99.67628 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 00:05 +0000",
"Amount":"-16.90149 C",
"Type":"Transaction",
"Total":"82.77479 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 00:05 +0000",
"Amount":"-9.91015 C",
"Type":"Transaction",
"Total":"72.86464 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 00:05 +0000",
"Amount":"-24.58488 C",
"Type":"Transaction",
"Total":"48.27976 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 00:05 +0000",
"Amount":"-10.93364 C",
"Type":"Transaction",
"Total":"37.34612 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 00:05 +0000",
"Amount":"-18.66590 C",
"Type":"Transaction",
"Total":"18.68022 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 00:05 +0000",
"Amount":"-10.65518 C",
"Type":"Transaction",
"Total":"8.02504 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 00:05 +0000",
"Amount":"-4.98425 C",
"Type":"Transaction",
"Total":"3.04079 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 18:24 +0000",
"Amount":"58.87511 C",
"Type":"Transaction",
"Total":"61.91590 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 18:59 +0000",
"Amount":"-18.08436 C",
"Type":"Transaction",
"Total":"43.83154 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 18:59 +0000",
"Amount":"-17.37911 C",
"Type":"Transaction",
"Total":"26.45243 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 18:59 +0000",
"Amount":"-16.83380 C",
"Type":"Transaction",
"Total":"9.61863 C",
"ID":""
},
{
"Status":"Confirmed",
"Date":"28 Jul 17 18:59 +0000",
"Amount":"-5.38983 C",
"Type":"Transaction",
"Total":"4.22880 C",
"ID":""
}
]`
|
package Problem0258
func addDigits(n int) int {
return (n-1)%9 + 1
}
|
package server
import (
"fmt"
"time"
)
type QProc struct {
name string
req chan int
}
func (q *QProc) Start(Qname string) int {
c := make(chan int)
quit := make(chan int)
go run(c, quit)
q.req = c
fmt.Print("here")
for i := 0; i < 4; i++ {
c <- 1
fmt.Println("inLoop")
time.Sleep(1 * time.Second)
}
return 0
}
func run(c, quit chan int) {
i := 0
i++
for {
fmt.Println("-XXX--")
select {
case v := <-c:
fmt.Print("inVVVV")
fmt.Print(v)
// default:
// fmt.Println("--C-")
// receiving from c would block
}
//time.Sleep(1*time.Second)
}
}
func (q *QProc) Push() {
q.req <- 1
fmt.Println("-pushed--")
}
|
package logs
import (
"fmt"
"github.com/kalifun/gin-template/config"
"github.com/kalifun/gin-template/global"
"github.com/kalifun/gin-template/utils"
rotates "github.com/lestrrat-go/file-rotatelogs"
oplog "github.com/op/go-logging"
"io"
"os"
"strings"
"time"
)
const (
logDir = "logs"
logSoftLink = "latest_log"
module = "auth"
)
var (
defaultFormatter = `%{time:2006/01/02 - 15:04:05.000} %{longfile} %{color:bold} ▶ [%{level:.6s}] %{message}%{color:reset}`
)
func InitLog() {
c := global.ConfigSvr.Log
if c.Prefix == "" {
_ = fmt.Errorf("logger prefix not found")
}
logger := oplog.MustGetLogger(module)
var backends []oplog.Backend
registerStdout(c, &backends)
if fileWriter := registerFile(c, &backends); fileWriter != nil {
io.MultiWriter(fileWriter, os.Stdout)
}
oplog.SetBackend(backends...)
global.Log = logger
}
func registerStdout(c config.Log, backends *[]oplog.Backend) {
if c.Stdout != "" {
level, err := oplog.LogLevel(c.Stdout)
if err != nil {
fmt.Println(err)
}
*backends = append(*backends, createBackend(os.Stdout, c, level))
}
}
func registerFile(c config.Log, backends *[]oplog.Backend) io.Writer {
if c.File != "" {
if ok, _ := utils.PathExists(logDir); !ok {
// directory not exist
fmt.Println("create log directory")
_ = os.Mkdir(logDir, os.ModePerm)
}
fileWriter, err := rotates.New(
logDir+string(os.PathSeparator)+"%Y-%m-%d-%H-%M.log",
// generate soft link, point to latest log file
rotates.WithLinkName(logSoftLink),
// maximum time to save log files
rotates.WithMaxAge(7*24*time.Hour),
// time period of log file switching
rotates.WithRotationTime(24*time.Hour),
)
if err != nil {
fmt.Println(err)
}
level, err := oplog.LogLevel(c.File)
if err != nil {
fmt.Println(err)
}
*backends = append(*backends, createBackend(fileWriter, c, level))
return fileWriter
}
return nil
}
func createBackend(w io.Writer, c config.Log, level oplog.Level) oplog.Backend {
backend := oplog.NewLogBackend(w, c.Prefix, 0)
stdoutWriter := false
if w == os.Stdout {
stdoutWriter = true
}
format := getLogFormatter(c, stdoutWriter)
backendLeveled := oplog.AddModuleLevel(oplog.NewBackendFormatter(backend, format))
backendLeveled.SetLevel(level, module)
return backendLeveled
}
func getLogFormatter(c config.Log, stdoutWriter bool) oplog.Formatter {
pattern := defaultFormatter
if !stdoutWriter {
// Color is only required for console output
// Other writers don't need %{color} tag
pattern = strings.Replace(pattern, "%{color:bold}", "", -1)
pattern = strings.Replace(pattern, "%{color:reset}", "", -1)
}
if !c.LogFile {
// Remove %{logfile} tag
pattern = strings.Replace(pattern, "%{longfile}", "", -1)
}
return oplog.MustStringFormatter(pattern)
}
/*
写gin的日志文件
*/
//func WriteGinLog() gin.HandlerFunc {
//
//}
|
// Copyright 2023 Google LLC. All Rights Reserved.
//
// 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 alpha
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"strings"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl/operations"
)
func (r *Job) validate() error {
if err := dcl.Required(r, "name"); err != nil {
return err
}
if err := dcl.Required(r, "template"); err != nil {
return err
}
if err := dcl.RequiredParameter(r.Project, "Project"); err != nil {
return err
}
if err := dcl.RequiredParameter(r.Location, "Location"); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(r.BinaryAuthorization) {
if err := r.BinaryAuthorization.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.Template) {
if err := r.Template.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.TerminalCondition) {
if err := r.TerminalCondition.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.LatestSucceededExecution) {
if err := r.LatestSucceededExecution.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.LatestCreatedExecution) {
if err := r.LatestCreatedExecution.validate(); err != nil {
return err
}
}
return nil
}
func (r *JobBinaryAuthorization) validate() error {
return nil
}
func (r *JobTemplate) validate() error {
if err := dcl.Required(r, "template"); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(r.Template) {
if err := r.Template.validate(); err != nil {
return err
}
}
return nil
}
func (r *JobTemplateTemplate) validate() error {
if !dcl.IsEmptyValueIndirect(r.VPCAccess) {
if err := r.VPCAccess.validate(); err != nil {
return err
}
}
return nil
}
func (r *JobTemplateTemplateContainers) validate() error {
if err := dcl.Required(r, "image"); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(r.Resources) {
if err := r.Resources.validate(); err != nil {
return err
}
}
return nil
}
func (r *JobTemplateTemplateContainersEnv) validate() error {
if err := dcl.Required(r, "name"); err != nil {
return err
}
if err := dcl.ValidateAtMostOneOfFieldsSet([]string{"Value", "ValueSource"}, r.Value, r.ValueSource); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(r.ValueSource) {
if err := r.ValueSource.validate(); err != nil {
return err
}
}
return nil
}
func (r *JobTemplateTemplateContainersEnvValueSource) validate() error {
if !dcl.IsEmptyValueIndirect(r.SecretKeyRef) {
if err := r.SecretKeyRef.validate(); err != nil {
return err
}
}
return nil
}
func (r *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef) validate() error {
if err := dcl.Required(r, "secret"); err != nil {
return err
}
return nil
}
func (r *JobTemplateTemplateContainersResources) validate() error {
return nil
}
func (r *JobTemplateTemplateContainersPorts) validate() error {
return nil
}
func (r *JobTemplateTemplateContainersVolumeMounts) validate() error {
if err := dcl.Required(r, "name"); err != nil {
return err
}
if err := dcl.Required(r, "mountPath"); err != nil {
return err
}
return nil
}
func (r *JobTemplateTemplateVolumes) validate() error {
if err := dcl.Required(r, "name"); err != nil {
return err
}
if err := dcl.ValidateAtMostOneOfFieldsSet([]string{"Secret", "CloudSqlInstance"}, r.Secret, r.CloudSqlInstance); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(r.Secret) {
if err := r.Secret.validate(); err != nil {
return err
}
}
if !dcl.IsEmptyValueIndirect(r.CloudSqlInstance) {
if err := r.CloudSqlInstance.validate(); err != nil {
return err
}
}
return nil
}
func (r *JobTemplateTemplateVolumesSecret) validate() error {
if err := dcl.Required(r, "secret"); err != nil {
return err
}
return nil
}
func (r *JobTemplateTemplateVolumesSecretItems) validate() error {
if err := dcl.Required(r, "path"); err != nil {
return err
}
return nil
}
func (r *JobTemplateTemplateVolumesCloudSqlInstance) validate() error {
return nil
}
func (r *JobTemplateTemplateVPCAccess) validate() error {
return nil
}
func (r *JobTerminalCondition) validate() error {
if err := dcl.ValidateAtMostOneOfFieldsSet([]string{"Reason", "InternalReason", "DomainMappingReason", "RevisionReason", "ExecutionReason"}, r.Reason, r.InternalReason, r.DomainMappingReason, r.RevisionReason, r.ExecutionReason); err != nil {
return err
}
return nil
}
func (r *JobConditions) validate() error {
if err := dcl.ValidateAtMostOneOfFieldsSet([]string{"Reason", "RevisionReason", "ExecutionReason"}, r.Reason, r.RevisionReason, r.ExecutionReason); err != nil {
return err
}
return nil
}
func (r *JobLatestSucceededExecution) validate() error {
return nil
}
func (r *JobLatestCreatedExecution) validate() error {
return nil
}
func (r *Job) basePath() string {
params := map[string]interface{}{}
return dcl.Nprintf("https://run.googleapis.com/v2/", params)
}
func (r *Job) getURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := map[string]interface{}{
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
"name": dcl.ValueOrEmptyString(nr.Name),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/jobs/{{name}}", nr.basePath(), userBasePath, params), nil
}
func (r *Job) listURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := map[string]interface{}{
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/jobs", nr.basePath(), userBasePath, params), nil
}
func (r *Job) createURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := map[string]interface{}{
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
"name": dcl.ValueOrEmptyString(nr.Name),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/jobs?jobId={{name}}", nr.basePath(), userBasePath, params), nil
}
func (r *Job) deleteURL(userBasePath string) (string, error) {
nr := r.urlNormalized()
params := map[string]interface{}{
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
"name": dcl.ValueOrEmptyString(nr.Name),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/jobs/{{name}}", nr.basePath(), userBasePath, params), nil
}
func (r *Job) SetPolicyURL(userBasePath string) string {
nr := r.urlNormalized()
fields := map[string]interface{}{
"project": *nr.Project,
"location": *nr.Location,
"name": *nr.Name,
}
return dcl.URL("projects/{{project}}/locations/{{location}}/jobs/{{name}}", nr.basePath(), userBasePath, fields)
}
func (r *Job) SetPolicyVerb() string {
return "POST"
}
func (r *Job) getPolicyURL(userBasePath string) string {
nr := r.urlNormalized()
fields := map[string]interface{}{
"project": *nr.Project,
"location": *nr.Location,
"name": *nr.Name,
}
return dcl.URL("projects/{{project}}/locations/{{location}}/jobs/{{name}}", nr.basePath(), userBasePath, fields)
}
func (r *Job) IAMPolicyVersion() int {
return 3
}
// jobApiOperation represents a mutable operation in the underlying REST
// API such as Create, Update, or Delete.
type jobApiOperation interface {
do(context.Context, *Job, *Client) error
}
// newUpdateJobUpdateJobRequest creates a request for an
// Job resource's UpdateJob update type by filling in the update
// fields based on the intended state of the resource.
func newUpdateJobUpdateJobRequest(ctx context.Context, f *Job, c *Client) (map[string]interface{}, error) {
req := map[string]interface{}{}
res := f
_ = res
if v, err := dcl.DeriveField("projects/%s/locations/%s/jobs/%s", f.Name, dcl.SelfLinkToName(f.Project), dcl.SelfLinkToName(f.Location), dcl.SelfLinkToName(f.Name)); err != nil {
return nil, fmt.Errorf("error expanding Name into name: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
req["name"] = v
}
if v := f.Annotations; !dcl.IsEmptyValueIndirect(v) {
req["annotations"] = v
}
if v := f.Client; !dcl.IsEmptyValueIndirect(v) {
req["client"] = v
}
if v := f.ClientVersion; !dcl.IsEmptyValueIndirect(v) {
req["clientVersion"] = v
}
if v := f.LaunchStage; !dcl.IsEmptyValueIndirect(v) {
req["launchStage"] = v
}
if v, err := expandJobBinaryAuthorization(c, f.BinaryAuthorization, res); err != nil {
return nil, fmt.Errorf("error expanding BinaryAuthorization into binaryAuthorization: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
req["binaryAuthorization"] = v
}
if v, err := expandJobTemplate(c, f.Template, res); err != nil {
return nil, fmt.Errorf("error expanding Template into template: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
req["template"] = v
}
if v, err := expandJobTerminalCondition(c, f.TerminalCondition, res); err != nil {
return nil, fmt.Errorf("error expanding TerminalCondition into terminalCondition: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
req["terminalCondition"] = v
}
if v, err := expandJobLatestSucceededExecution(c, f.LatestSucceededExecution, res); err != nil {
return nil, fmt.Errorf("error expanding LatestSucceededExecution into latestSucceededExecution: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
req["latestSucceededExecution"] = v
}
if v, err := expandJobLatestCreatedExecution(c, f.LatestCreatedExecution, res); err != nil {
return nil, fmt.Errorf("error expanding LatestCreatedExecution into latestCreatedExecution: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
req["latestCreatedExecution"] = v
}
b, err := c.getJobRaw(ctx, f)
if err != nil {
return nil, err
}
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
rawEtag, err := dcl.GetMapEntry(
m,
[]string{"etag"},
)
if err != nil {
c.Config.Logger.WarningWithContextf(ctx, "Failed to fetch from JSON Path: %v", err)
} else {
req["etag"] = rawEtag.(string)
}
return req, nil
}
// marshalUpdateJobUpdateJobRequest converts the update into
// the final JSON request body.
func marshalUpdateJobUpdateJobRequest(c *Client, m map[string]interface{}) ([]byte, error) {
return json.Marshal(m)
}
type updateJobUpdateJobOperation struct {
// If the update operation has the REQUIRES_APPLY_OPTIONS trait, this will be populated.
// Usually it will be nil - this is to prevent us from accidentally depending on apply
// options, which should usually be unnecessary.
ApplyOptions []dcl.ApplyOption
FieldDiffs []*dcl.FieldDiff
}
// do creates a request and sends it to the appropriate URL. In most operations,
// do will transcribe a subset of the resource into a request object and send a
// PUT request to a single URL.
func (op *updateJobUpdateJobOperation) do(ctx context.Context, r *Job, c *Client) error {
_, err := c.GetJob(ctx, r)
if err != nil {
return err
}
u, err := r.updateURL(c.Config.BasePath, "UpdateJob")
if err != nil {
return err
}
req, err := newUpdateJobUpdateJobRequest(ctx, r, c)
if err != nil {
return err
}
c.Config.Logger.InfoWithContextf(ctx, "Created update: %#v", req)
body, err := marshalUpdateJobUpdateJobRequest(c, req)
if err != nil {
return err
}
resp, err := dcl.SendRequest(ctx, c.Config, "PATCH", u, bytes.NewBuffer(body), c.Config.RetryProvider)
if err != nil {
return err
}
var o operations.StandardGCPOperation
if err := dcl.ParseResponse(resp.Response, &o); err != nil {
return err
}
err = o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET")
if err != nil {
return err
}
return nil
}
func (c *Client) listJobRaw(ctx context.Context, r *Job, pageToken string, pageSize int32) ([]byte, error) {
u, err := r.urlNormalized().listURL(c.Config.BasePath)
if err != nil {
return nil, err
}
m := make(map[string]string)
if pageToken != "" {
m["pageToken"] = pageToken
}
if pageSize != JobMaxPage {
m["pageSize"] = fmt.Sprintf("%v", pageSize)
}
u, err = dcl.AddQueryParams(u, m)
if err != nil {
return nil, err
}
resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider)
if err != nil {
return nil, err
}
defer resp.Response.Body.Close()
return ioutil.ReadAll(resp.Response.Body)
}
type listJobOperation struct {
Jobs []map[string]interface{} `json:"jobs"`
Token string `json:"nextPageToken"`
}
func (c *Client) listJob(ctx context.Context, r *Job, pageToken string, pageSize int32) ([]*Job, string, error) {
b, err := c.listJobRaw(ctx, r, pageToken, pageSize)
if err != nil {
return nil, "", err
}
var m listJobOperation
if err := json.Unmarshal(b, &m); err != nil {
return nil, "", err
}
var l []*Job
for _, v := range m.Jobs {
res, err := unmarshalMapJob(v, c, r)
if err != nil {
return nil, m.Token, err
}
res.Project = r.Project
res.Location = r.Location
l = append(l, res)
}
return l, m.Token, nil
}
func (c *Client) deleteAllJob(ctx context.Context, f func(*Job) bool, resources []*Job) error {
var errors []string
for _, res := range resources {
if f(res) {
// We do not want deleteAll to fail on a deletion or else it will stop deleting other resources.
err := c.DeleteJob(ctx, res)
if err != nil {
errors = append(errors, err.Error())
}
}
}
if len(errors) > 0 {
return fmt.Errorf("%v", strings.Join(errors, "\n"))
} else {
return nil
}
}
type deleteJobOperation struct{}
func (op *deleteJobOperation) do(ctx context.Context, r *Job, c *Client) error {
r, err := c.GetJob(ctx, r)
if err != nil {
if dcl.IsNotFound(err) {
c.Config.Logger.InfoWithContextf(ctx, "Job not found, returning. Original error: %v", err)
return nil
}
c.Config.Logger.WarningWithContextf(ctx, "GetJob checking for existence. error: %v", err)
return err
}
u, err := r.deleteURL(c.Config.BasePath)
if err != nil {
return err
}
u, err = dcl.AddQueryParams(u, map[string]string{"force": "true"})
if err != nil {
return err
}
// Delete should never have a body
body := &bytes.Buffer{}
_, err = dcl.SendRequest(ctx, c.Config, "DELETE", u, body, c.Config.RetryProvider)
if err != nil {
return fmt.Errorf("failed to delete Job: %w", err)
}
return nil
}
// Create operations are similar to Update operations, although they do not have
// specific request objects. The Create request object is the json encoding of
// the resource, which is modified by res.marshal to form the base request body.
type createJobOperation struct {
response map[string]interface{}
}
func (op *createJobOperation) FirstResponse() (map[string]interface{}, bool) {
return op.response, len(op.response) > 0
}
func (op *createJobOperation) do(ctx context.Context, r *Job, c *Client) error {
c.Config.Logger.InfoWithContextf(ctx, "Attempting to create %v", r)
u, err := r.createURL(c.Config.BasePath)
if err != nil {
return err
}
req, err := r.marshal(c)
if err != nil {
return err
}
resp, err := dcl.SendRequest(ctx, c.Config, "POST", u, bytes.NewBuffer(req), c.Config.RetryProvider)
if err != nil {
return err
}
// wait for object to be created.
var o operations.StandardGCPOperation
if err := dcl.ParseResponse(resp.Response, &o); err != nil {
return err
}
if err := o.Wait(context.WithValue(ctx, dcl.DoNotLogRequestsKey, true), c.Config, r.basePath(), "GET"); err != nil {
c.Config.Logger.Warningf("Creation failed after waiting for operation: %v", err)
return err
}
c.Config.Logger.InfoWithContextf(ctx, "Successfully waited for operation")
op.response, _ = o.FirstResponse()
if _, err := c.GetJob(ctx, r); err != nil {
c.Config.Logger.WarningWithContextf(ctx, "get returned error: %v", err)
return err
}
return nil
}
func (c *Client) getJobRaw(ctx context.Context, r *Job) ([]byte, error) {
u, err := r.getURL(c.Config.BasePath)
if err != nil {
return nil, err
}
resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider)
if err != nil {
return nil, err
}
defer resp.Response.Body.Close()
b, err := ioutil.ReadAll(resp.Response.Body)
if err != nil {
return nil, err
}
return b, nil
}
func (c *Client) jobDiffsForRawDesired(ctx context.Context, rawDesired *Job, opts ...dcl.ApplyOption) (initial, desired *Job, diffs []*dcl.FieldDiff, err error) {
c.Config.Logger.InfoWithContext(ctx, "Fetching initial state...")
// First, let us see if the user provided a state hint. If they did, we will start fetching based on that.
var fetchState *Job
if sh := dcl.FetchStateHint(opts); sh != nil {
if r, ok := sh.(*Job); !ok {
c.Config.Logger.WarningWithContextf(ctx, "Initial state hint was of the wrong type; expected Job, got %T", sh)
} else {
fetchState = r
}
}
if fetchState == nil {
fetchState = rawDesired
}
// 1.2: Retrieval of raw initial state from API
rawInitial, err := c.GetJob(ctx, fetchState)
if rawInitial == nil {
if !dcl.IsNotFound(err) {
c.Config.Logger.WarningWithContextf(ctx, "Failed to retrieve whether a Job resource already exists: %s", err)
return nil, nil, nil, fmt.Errorf("failed to retrieve Job resource: %v", err)
}
c.Config.Logger.InfoWithContext(ctx, "Found that Job resource did not exist.")
// Perform canonicalization to pick up defaults.
desired, err = canonicalizeJobDesiredState(rawDesired, rawInitial)
return nil, desired, nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Found initial state for Job: %v", rawInitial)
c.Config.Logger.InfoWithContextf(ctx, "Initial desired state for Job: %v", rawDesired)
// The Get call applies postReadExtract and so the result may contain fields that are not part of API version.
if err := extractJobFields(rawInitial); err != nil {
return nil, nil, nil, err
}
// 1.3: Canonicalize raw initial state into initial state.
initial, err = canonicalizeJobInitialState(rawInitial, rawDesired)
if err != nil {
return nil, nil, nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Canonicalized initial state for Job: %v", initial)
// 1.4: Canonicalize raw desired state into desired state.
desired, err = canonicalizeJobDesiredState(rawDesired, rawInitial, opts...)
if err != nil {
return nil, nil, nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Canonicalized desired state for Job: %v", desired)
// 2.1: Comparison of initial and desired state.
diffs, err = diffJob(c, desired, initial, opts...)
return initial, desired, diffs, err
}
func canonicalizeJobInitialState(rawInitial, rawDesired *Job) (*Job, error) {
// TODO(magic-modules-eng): write canonicalizer once relevant traits are added.
return rawInitial, nil
}
/*
* Canonicalizers
*
* These are responsible for converting either a user-specified config or a
* GCP API response to a standard format that can be used for difference checking.
* */
func canonicalizeJobDesiredState(rawDesired, rawInitial *Job, opts ...dcl.ApplyOption) (*Job, error) {
if rawInitial == nil {
// Since the initial state is empty, the desired state is all we have.
// We canonicalize the remaining nested objects with nil to pick up defaults.
rawDesired.BinaryAuthorization = canonicalizeJobBinaryAuthorization(rawDesired.BinaryAuthorization, nil, opts...)
rawDesired.Template = canonicalizeJobTemplate(rawDesired.Template, nil, opts...)
rawDesired.TerminalCondition = canonicalizeJobTerminalCondition(rawDesired.TerminalCondition, nil, opts...)
rawDesired.LatestSucceededExecution = canonicalizeJobLatestSucceededExecution(rawDesired.LatestSucceededExecution, nil, opts...)
rawDesired.LatestCreatedExecution = canonicalizeJobLatestCreatedExecution(rawDesired.LatestCreatedExecution, nil, opts...)
return rawDesired, nil
}
canonicalDesired := &Job{}
if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawInitial.Name) {
canonicalDesired.Name = rawInitial.Name
} else {
canonicalDesired.Name = rawDesired.Name
}
if dcl.IsZeroValue(rawDesired.Annotations) || (dcl.IsEmptyValueIndirect(rawDesired.Annotations) && dcl.IsEmptyValueIndirect(rawInitial.Annotations)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
canonicalDesired.Annotations = rawInitial.Annotations
} else {
canonicalDesired.Annotations = rawDesired.Annotations
}
if dcl.StringCanonicalize(rawDesired.Client, rawInitial.Client) {
canonicalDesired.Client = rawInitial.Client
} else {
canonicalDesired.Client = rawDesired.Client
}
if dcl.StringCanonicalize(rawDesired.ClientVersion, rawInitial.ClientVersion) {
canonicalDesired.ClientVersion = rawInitial.ClientVersion
} else {
canonicalDesired.ClientVersion = rawDesired.ClientVersion
}
if dcl.IsZeroValue(rawDesired.LaunchStage) || (dcl.IsEmptyValueIndirect(rawDesired.LaunchStage) && dcl.IsEmptyValueIndirect(rawInitial.LaunchStage)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
canonicalDesired.LaunchStage = rawInitial.LaunchStage
} else {
canonicalDesired.LaunchStage = rawDesired.LaunchStage
}
canonicalDesired.BinaryAuthorization = canonicalizeJobBinaryAuthorization(rawDesired.BinaryAuthorization, rawInitial.BinaryAuthorization, opts...)
canonicalDesired.Template = canonicalizeJobTemplate(rawDesired.Template, rawInitial.Template, opts...)
if dcl.NameToSelfLink(rawDesired.Project, rawInitial.Project) {
canonicalDesired.Project = rawInitial.Project
} else {
canonicalDesired.Project = rawDesired.Project
}
if dcl.NameToSelfLink(rawDesired.Location, rawInitial.Location) {
canonicalDesired.Location = rawInitial.Location
} else {
canonicalDesired.Location = rawDesired.Location
}
return canonicalDesired, nil
}
func canonicalizeJobNewState(c *Client, rawNew, rawDesired *Job) (*Job, error) {
if dcl.IsEmptyValueIndirect(rawNew.Name) && dcl.IsEmptyValueIndirect(rawDesired.Name) {
rawNew.Name = rawDesired.Name
} else {
if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawNew.Name) {
rawNew.Name = rawDesired.Name
}
}
if dcl.IsEmptyValueIndirect(rawNew.Uid) && dcl.IsEmptyValueIndirect(rawDesired.Uid) {
rawNew.Uid = rawDesired.Uid
} else {
if dcl.StringCanonicalize(rawDesired.Uid, rawNew.Uid) {
rawNew.Uid = rawDesired.Uid
}
}
if dcl.IsEmptyValueIndirect(rawNew.Generation) && dcl.IsEmptyValueIndirect(rawDesired.Generation) {
rawNew.Generation = rawDesired.Generation
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.Labels) && dcl.IsEmptyValueIndirect(rawDesired.Labels) {
rawNew.Labels = rawDesired.Labels
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.Annotations) && dcl.IsEmptyValueIndirect(rawDesired.Annotations) {
rawNew.Annotations = rawDesired.Annotations
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.CreateTime) && dcl.IsEmptyValueIndirect(rawDesired.CreateTime) {
rawNew.CreateTime = rawDesired.CreateTime
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.UpdateTime) && dcl.IsEmptyValueIndirect(rawDesired.UpdateTime) {
rawNew.UpdateTime = rawDesired.UpdateTime
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.DeleteTime) && dcl.IsEmptyValueIndirect(rawDesired.DeleteTime) {
rawNew.DeleteTime = rawDesired.DeleteTime
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.ExpireTime) && dcl.IsEmptyValueIndirect(rawDesired.ExpireTime) {
rawNew.ExpireTime = rawDesired.ExpireTime
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.Creator) && dcl.IsEmptyValueIndirect(rawDesired.Creator) {
rawNew.Creator = rawDesired.Creator
} else {
if dcl.StringCanonicalize(rawDesired.Creator, rawNew.Creator) {
rawNew.Creator = rawDesired.Creator
}
}
if dcl.IsEmptyValueIndirect(rawNew.LastModifier) && dcl.IsEmptyValueIndirect(rawDesired.LastModifier) {
rawNew.LastModifier = rawDesired.LastModifier
} else {
if dcl.StringCanonicalize(rawDesired.LastModifier, rawNew.LastModifier) {
rawNew.LastModifier = rawDesired.LastModifier
}
}
if dcl.IsEmptyValueIndirect(rawNew.Client) && dcl.IsEmptyValueIndirect(rawDesired.Client) {
rawNew.Client = rawDesired.Client
} else {
if dcl.StringCanonicalize(rawDesired.Client, rawNew.Client) {
rawNew.Client = rawDesired.Client
}
}
if dcl.IsEmptyValueIndirect(rawNew.ClientVersion) && dcl.IsEmptyValueIndirect(rawDesired.ClientVersion) {
rawNew.ClientVersion = rawDesired.ClientVersion
} else {
if dcl.StringCanonicalize(rawDesired.ClientVersion, rawNew.ClientVersion) {
rawNew.ClientVersion = rawDesired.ClientVersion
}
}
if dcl.IsEmptyValueIndirect(rawNew.LaunchStage) && dcl.IsEmptyValueIndirect(rawDesired.LaunchStage) {
rawNew.LaunchStage = rawDesired.LaunchStage
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.BinaryAuthorization) && dcl.IsEmptyValueIndirect(rawDesired.BinaryAuthorization) {
rawNew.BinaryAuthorization = rawDesired.BinaryAuthorization
} else {
rawNew.BinaryAuthorization = canonicalizeNewJobBinaryAuthorization(c, rawDesired.BinaryAuthorization, rawNew.BinaryAuthorization)
}
if dcl.IsEmptyValueIndirect(rawNew.Template) && dcl.IsEmptyValueIndirect(rawDesired.Template) {
rawNew.Template = rawDesired.Template
} else {
rawNew.Template = canonicalizeNewJobTemplate(c, rawDesired.Template, rawNew.Template)
}
if dcl.IsEmptyValueIndirect(rawNew.ObservedGeneration) && dcl.IsEmptyValueIndirect(rawDesired.ObservedGeneration) {
rawNew.ObservedGeneration = rawDesired.ObservedGeneration
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.TerminalCondition) && dcl.IsEmptyValueIndirect(rawDesired.TerminalCondition) {
rawNew.TerminalCondition = rawDesired.TerminalCondition
} else {
rawNew.TerminalCondition = canonicalizeNewJobTerminalCondition(c, rawDesired.TerminalCondition, rawNew.TerminalCondition)
}
if dcl.IsEmptyValueIndirect(rawNew.Conditions) && dcl.IsEmptyValueIndirect(rawDesired.Conditions) {
rawNew.Conditions = rawDesired.Conditions
} else {
rawNew.Conditions = canonicalizeNewJobConditionsSlice(c, rawDesired.Conditions, rawNew.Conditions)
}
if dcl.IsEmptyValueIndirect(rawNew.ExecutionCount) && dcl.IsEmptyValueIndirect(rawDesired.ExecutionCount) {
rawNew.ExecutionCount = rawDesired.ExecutionCount
} else {
}
if dcl.IsEmptyValueIndirect(rawNew.LatestSucceededExecution) && dcl.IsEmptyValueIndirect(rawDesired.LatestSucceededExecution) {
rawNew.LatestSucceededExecution = rawDesired.LatestSucceededExecution
} else {
rawNew.LatestSucceededExecution = canonicalizeNewJobLatestSucceededExecution(c, rawDesired.LatestSucceededExecution, rawNew.LatestSucceededExecution)
}
if dcl.IsEmptyValueIndirect(rawNew.LatestCreatedExecution) && dcl.IsEmptyValueIndirect(rawDesired.LatestCreatedExecution) {
rawNew.LatestCreatedExecution = rawDesired.LatestCreatedExecution
} else {
rawNew.LatestCreatedExecution = canonicalizeNewJobLatestCreatedExecution(c, rawDesired.LatestCreatedExecution, rawNew.LatestCreatedExecution)
}
if dcl.IsEmptyValueIndirect(rawNew.Reconciling) && dcl.IsEmptyValueIndirect(rawDesired.Reconciling) {
rawNew.Reconciling = rawDesired.Reconciling
} else {
if dcl.BoolCanonicalize(rawDesired.Reconciling, rawNew.Reconciling) {
rawNew.Reconciling = rawDesired.Reconciling
}
}
if dcl.IsEmptyValueIndirect(rawNew.Etag) && dcl.IsEmptyValueIndirect(rawDesired.Etag) {
rawNew.Etag = rawDesired.Etag
} else {
if dcl.StringCanonicalize(rawDesired.Etag, rawNew.Etag) {
rawNew.Etag = rawDesired.Etag
}
}
rawNew.Project = rawDesired.Project
rawNew.Location = rawDesired.Location
return rawNew, nil
}
func canonicalizeJobBinaryAuthorization(des, initial *JobBinaryAuthorization, opts ...dcl.ApplyOption) *JobBinaryAuthorization {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobBinaryAuthorization{}
if dcl.BoolCanonicalize(des.UseDefault, initial.UseDefault) || dcl.IsZeroValue(des.UseDefault) {
cDes.UseDefault = initial.UseDefault
} else {
cDes.UseDefault = des.UseDefault
}
if dcl.StringCanonicalize(des.BreakglassJustification, initial.BreakglassJustification) || dcl.IsZeroValue(des.BreakglassJustification) {
cDes.BreakglassJustification = initial.BreakglassJustification
} else {
cDes.BreakglassJustification = des.BreakglassJustification
}
return cDes
}
func canonicalizeJobBinaryAuthorizationSlice(des, initial []JobBinaryAuthorization, opts ...dcl.ApplyOption) []JobBinaryAuthorization {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobBinaryAuthorization, 0, len(des))
for _, d := range des {
cd := canonicalizeJobBinaryAuthorization(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobBinaryAuthorization, 0, len(des))
for i, d := range des {
cd := canonicalizeJobBinaryAuthorization(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobBinaryAuthorization(c *Client, des, nw *JobBinaryAuthorization) *JobBinaryAuthorization {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobBinaryAuthorization while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.BoolCanonicalize(des.UseDefault, nw.UseDefault) {
nw.UseDefault = des.UseDefault
}
if dcl.StringCanonicalize(des.BreakglassJustification, nw.BreakglassJustification) {
nw.BreakglassJustification = des.BreakglassJustification
}
return nw
}
func canonicalizeNewJobBinaryAuthorizationSet(c *Client, des, nw []JobBinaryAuthorization) []JobBinaryAuthorization {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobBinaryAuthorization
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobBinaryAuthorizationNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobBinaryAuthorization(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobBinaryAuthorizationSlice(c *Client, des, nw []JobBinaryAuthorization) []JobBinaryAuthorization {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobBinaryAuthorization
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobBinaryAuthorization(c, &d, &n))
}
return items
}
func canonicalizeJobTemplate(des, initial *JobTemplate, opts ...dcl.ApplyOption) *JobTemplate {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplate{}
if dcl.IsZeroValue(des.Labels) || (dcl.IsEmptyValueIndirect(des.Labels) && dcl.IsEmptyValueIndirect(initial.Labels)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Labels = initial.Labels
} else {
cDes.Labels = des.Labels
}
if dcl.IsZeroValue(des.Annotations) || (dcl.IsEmptyValueIndirect(des.Annotations) && dcl.IsEmptyValueIndirect(initial.Annotations)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Annotations = initial.Annotations
} else {
cDes.Annotations = des.Annotations
}
if dcl.IsZeroValue(des.Parallelism) || (dcl.IsEmptyValueIndirect(des.Parallelism) && dcl.IsEmptyValueIndirect(initial.Parallelism)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Parallelism = initial.Parallelism
} else {
cDes.Parallelism = des.Parallelism
}
if dcl.IsZeroValue(des.TaskCount) || (dcl.IsEmptyValueIndirect(des.TaskCount) && dcl.IsEmptyValueIndirect(initial.TaskCount)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.TaskCount = initial.TaskCount
} else {
cDes.TaskCount = des.TaskCount
}
cDes.Template = canonicalizeJobTemplateTemplate(des.Template, initial.Template, opts...)
return cDes
}
func canonicalizeJobTemplateSlice(des, initial []JobTemplate, opts ...dcl.ApplyOption) []JobTemplate {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplate, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplate(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplate, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplate(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplate(c *Client, des, nw *JobTemplate) *JobTemplate {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplate while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.Template = canonicalizeNewJobTemplateTemplate(c, des.Template, nw.Template)
return nw
}
func canonicalizeNewJobTemplateSet(c *Client, des, nw []JobTemplate) []JobTemplate {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplate
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplate(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateSlice(c *Client, des, nw []JobTemplate) []JobTemplate {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplate
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplate(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplate(des, initial *JobTemplateTemplate, opts ...dcl.ApplyOption) *JobTemplateTemplate {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplate{}
cDes.Containers = canonicalizeJobTemplateTemplateContainersSlice(des.Containers, initial.Containers, opts...)
cDes.Volumes = canonicalizeJobTemplateTemplateVolumesSlice(des.Volumes, initial.Volumes, opts...)
if dcl.IsZeroValue(des.MaxRetries) || (dcl.IsEmptyValueIndirect(des.MaxRetries) && dcl.IsEmptyValueIndirect(initial.MaxRetries)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.MaxRetries = initial.MaxRetries
} else {
cDes.MaxRetries = des.MaxRetries
}
if dcl.StringCanonicalize(des.Timeout, initial.Timeout) || dcl.IsZeroValue(des.Timeout) {
cDes.Timeout = initial.Timeout
} else {
cDes.Timeout = des.Timeout
}
if dcl.StringCanonicalize(des.ServiceAccount, initial.ServiceAccount) || dcl.IsZeroValue(des.ServiceAccount) {
cDes.ServiceAccount = initial.ServiceAccount
} else {
cDes.ServiceAccount = des.ServiceAccount
}
if dcl.IsZeroValue(des.ExecutionEnvironment) || (dcl.IsEmptyValueIndirect(des.ExecutionEnvironment) && dcl.IsEmptyValueIndirect(initial.ExecutionEnvironment)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.ExecutionEnvironment = initial.ExecutionEnvironment
} else {
cDes.ExecutionEnvironment = des.ExecutionEnvironment
}
if dcl.IsZeroValue(des.EncryptionKey) || (dcl.IsEmptyValueIndirect(des.EncryptionKey) && dcl.IsEmptyValueIndirect(initial.EncryptionKey)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.EncryptionKey = initial.EncryptionKey
} else {
cDes.EncryptionKey = des.EncryptionKey
}
cDes.VPCAccess = canonicalizeJobTemplateTemplateVPCAccess(des.VPCAccess, initial.VPCAccess, opts...)
return cDes
}
func canonicalizeJobTemplateTemplateSlice(des, initial []JobTemplateTemplate, opts ...dcl.ApplyOption) []JobTemplateTemplate {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplate, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplate(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplate, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplate(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplate(c *Client, des, nw *JobTemplateTemplate) *JobTemplateTemplate {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplate while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.Containers = canonicalizeNewJobTemplateTemplateContainersSlice(c, des.Containers, nw.Containers)
nw.Volumes = canonicalizeNewJobTemplateTemplateVolumesSlice(c, des.Volumes, nw.Volumes)
if dcl.StringCanonicalize(des.Timeout, nw.Timeout) {
nw.Timeout = des.Timeout
}
if dcl.StringCanonicalize(des.ServiceAccount, nw.ServiceAccount) {
nw.ServiceAccount = des.ServiceAccount
}
nw.VPCAccess = canonicalizeNewJobTemplateTemplateVPCAccess(c, des.VPCAccess, nw.VPCAccess)
return nw
}
func canonicalizeNewJobTemplateTemplateSet(c *Client, des, nw []JobTemplateTemplate) []JobTemplateTemplate {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplate
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplate(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateSlice(c *Client, des, nw []JobTemplateTemplate) []JobTemplateTemplate {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplate
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplate(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateContainers(des, initial *JobTemplateTemplateContainers, opts ...dcl.ApplyOption) *JobTemplateTemplateContainers {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateContainers{}
if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) {
cDes.Name = initial.Name
} else {
cDes.Name = des.Name
}
if dcl.StringCanonicalize(des.Image, initial.Image) || dcl.IsZeroValue(des.Image) {
cDes.Image = initial.Image
} else {
cDes.Image = des.Image
}
if dcl.StringArrayCanonicalize(des.Command, initial.Command) {
cDes.Command = initial.Command
} else {
cDes.Command = des.Command
}
if dcl.StringArrayCanonicalize(des.Args, initial.Args) {
cDes.Args = initial.Args
} else {
cDes.Args = des.Args
}
cDes.Env = canonicalizeJobTemplateTemplateContainersEnvSlice(des.Env, initial.Env, opts...)
cDes.Resources = canonicalizeJobTemplateTemplateContainersResources(des.Resources, initial.Resources, opts...)
cDes.Ports = canonicalizeJobTemplateTemplateContainersPortsSlice(des.Ports, initial.Ports, opts...)
cDes.VolumeMounts = canonicalizeJobTemplateTemplateContainersVolumeMountsSlice(des.VolumeMounts, initial.VolumeMounts, opts...)
return cDes
}
func canonicalizeJobTemplateTemplateContainersSlice(des, initial []JobTemplateTemplateContainers, opts ...dcl.ApplyOption) []JobTemplateTemplateContainers {
if des == nil {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateContainers, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateContainers(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateContainers, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateContainers(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateContainers(c *Client, des, nw *JobTemplateTemplateContainers) *JobTemplateTemplateContainers {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateContainers while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Name, nw.Name) {
nw.Name = des.Name
}
if dcl.StringCanonicalize(des.Image, nw.Image) {
nw.Image = des.Image
}
if dcl.StringArrayCanonicalize(des.Command, nw.Command) {
nw.Command = des.Command
}
if dcl.StringArrayCanonicalize(des.Args, nw.Args) {
nw.Args = des.Args
}
nw.Env = canonicalizeNewJobTemplateTemplateContainersEnvSlice(c, des.Env, nw.Env)
nw.Resources = canonicalizeNewJobTemplateTemplateContainersResources(c, des.Resources, nw.Resources)
nw.Ports = canonicalizeNewJobTemplateTemplateContainersPortsSlice(c, des.Ports, nw.Ports)
nw.VolumeMounts = canonicalizeNewJobTemplateTemplateContainersVolumeMountsSlice(c, des.VolumeMounts, nw.VolumeMounts)
return nw
}
func canonicalizeNewJobTemplateTemplateContainersSet(c *Client, des, nw []JobTemplateTemplateContainers) []JobTemplateTemplateContainers {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateContainers
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateContainersNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateContainers(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateContainersSlice(c *Client, des, nw []JobTemplateTemplateContainers) []JobTemplateTemplateContainers {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateContainers
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateContainers(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateContainersEnv(des, initial *JobTemplateTemplateContainersEnv, opts ...dcl.ApplyOption) *JobTemplateTemplateContainersEnv {
if des == nil {
return initial
}
if des.empty {
return des
}
if des.Value != nil || (initial != nil && initial.Value != nil) {
// Check if anything else is set.
if dcl.AnySet(des.ValueSource) {
des.Value = nil
if initial != nil {
initial.Value = nil
}
}
}
if des.ValueSource != nil || (initial != nil && initial.ValueSource != nil) {
// Check if anything else is set.
if dcl.AnySet(des.Value) {
des.ValueSource = nil
if initial != nil {
initial.ValueSource = nil
}
}
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateContainersEnv{}
if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) {
cDes.Name = initial.Name
} else {
cDes.Name = des.Name
}
if dcl.StringCanonicalize(des.Value, initial.Value) || dcl.IsZeroValue(des.Value) {
cDes.Value = initial.Value
} else {
cDes.Value = des.Value
}
cDes.ValueSource = canonicalizeJobTemplateTemplateContainersEnvValueSource(des.ValueSource, initial.ValueSource, opts...)
return cDes
}
func canonicalizeJobTemplateTemplateContainersEnvSlice(des, initial []JobTemplateTemplateContainersEnv, opts ...dcl.ApplyOption) []JobTemplateTemplateContainersEnv {
if des == nil {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateContainersEnv, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateContainersEnv(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateContainersEnv, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateContainersEnv(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateContainersEnv(c *Client, des, nw *JobTemplateTemplateContainersEnv) *JobTemplateTemplateContainersEnv {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateContainersEnv while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Name, nw.Name) {
nw.Name = des.Name
}
if dcl.StringCanonicalize(des.Value, nw.Value) {
nw.Value = des.Value
}
nw.ValueSource = canonicalizeNewJobTemplateTemplateContainersEnvValueSource(c, des.ValueSource, nw.ValueSource)
return nw
}
func canonicalizeNewJobTemplateTemplateContainersEnvSet(c *Client, des, nw []JobTemplateTemplateContainersEnv) []JobTemplateTemplateContainersEnv {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateContainersEnv
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateContainersEnvNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateContainersEnv(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateContainersEnvSlice(c *Client, des, nw []JobTemplateTemplateContainersEnv) []JobTemplateTemplateContainersEnv {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateContainersEnv
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateContainersEnv(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateContainersEnvValueSource(des, initial *JobTemplateTemplateContainersEnvValueSource, opts ...dcl.ApplyOption) *JobTemplateTemplateContainersEnvValueSource {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateContainersEnvValueSource{}
cDes.SecretKeyRef = canonicalizeJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(des.SecretKeyRef, initial.SecretKeyRef, opts...)
return cDes
}
func canonicalizeJobTemplateTemplateContainersEnvValueSourceSlice(des, initial []JobTemplateTemplateContainersEnvValueSource, opts ...dcl.ApplyOption) []JobTemplateTemplateContainersEnvValueSource {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateContainersEnvValueSource, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateContainersEnvValueSource(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateContainersEnvValueSource, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateContainersEnvValueSource(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateContainersEnvValueSource(c *Client, des, nw *JobTemplateTemplateContainersEnvValueSource) *JobTemplateTemplateContainersEnvValueSource {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateContainersEnvValueSource while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
nw.SecretKeyRef = canonicalizeNewJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c, des.SecretKeyRef, nw.SecretKeyRef)
return nw
}
func canonicalizeNewJobTemplateTemplateContainersEnvValueSourceSet(c *Client, des, nw []JobTemplateTemplateContainersEnvValueSource) []JobTemplateTemplateContainersEnvValueSource {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateContainersEnvValueSource
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateContainersEnvValueSourceNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateContainersEnvValueSource(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateContainersEnvValueSourceSlice(c *Client, des, nw []JobTemplateTemplateContainersEnvValueSource) []JobTemplateTemplateContainersEnvValueSource {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateContainersEnvValueSource
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateContainersEnvValueSource(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(des, initial *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef, opts ...dcl.ApplyOption) *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateContainersEnvValueSourceSecretKeyRef{}
if dcl.IsZeroValue(des.Secret) || (dcl.IsEmptyValueIndirect(des.Secret) && dcl.IsEmptyValueIndirect(initial.Secret)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Secret = initial.Secret
} else {
cDes.Secret = des.Secret
}
if dcl.IsZeroValue(des.Version) || (dcl.IsEmptyValueIndirect(des.Version) && dcl.IsEmptyValueIndirect(initial.Version)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Version = initial.Version
} else {
cDes.Version = des.Version
}
return cDes
}
func canonicalizeJobTemplateTemplateContainersEnvValueSourceSecretKeyRefSlice(des, initial []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef, opts ...dcl.ApplyOption) []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateContainersEnvValueSourceSecretKeyRef, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateContainersEnvValueSourceSecretKeyRef, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c *Client, des, nw *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef) *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateContainersEnvValueSourceSecretKeyRef while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
return nw
}
func canonicalizeNewJobTemplateTemplateContainersEnvValueSourceSecretKeyRefSet(c *Client, des, nw []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef) []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateContainersEnvValueSourceSecretKeyRefNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateContainersEnvValueSourceSecretKeyRefSlice(c *Client, des, nw []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef) []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateContainersResources(des, initial *JobTemplateTemplateContainersResources, opts ...dcl.ApplyOption) *JobTemplateTemplateContainersResources {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateContainersResources{}
if dcl.IsZeroValue(des.Limits) || (dcl.IsEmptyValueIndirect(des.Limits) && dcl.IsEmptyValueIndirect(initial.Limits)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Limits = initial.Limits
} else {
cDes.Limits = des.Limits
}
if dcl.BoolCanonicalize(des.CpuIdle, initial.CpuIdle) || dcl.IsZeroValue(des.CpuIdle) {
cDes.CpuIdle = initial.CpuIdle
} else {
cDes.CpuIdle = des.CpuIdle
}
return cDes
}
func canonicalizeJobTemplateTemplateContainersResourcesSlice(des, initial []JobTemplateTemplateContainersResources, opts ...dcl.ApplyOption) []JobTemplateTemplateContainersResources {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateContainersResources, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateContainersResources(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateContainersResources, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateContainersResources(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateContainersResources(c *Client, des, nw *JobTemplateTemplateContainersResources) *JobTemplateTemplateContainersResources {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateContainersResources while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.BoolCanonicalize(des.CpuIdle, nw.CpuIdle) {
nw.CpuIdle = des.CpuIdle
}
return nw
}
func canonicalizeNewJobTemplateTemplateContainersResourcesSet(c *Client, des, nw []JobTemplateTemplateContainersResources) []JobTemplateTemplateContainersResources {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateContainersResources
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateContainersResourcesNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateContainersResources(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateContainersResourcesSlice(c *Client, des, nw []JobTemplateTemplateContainersResources) []JobTemplateTemplateContainersResources {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateContainersResources
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateContainersResources(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateContainersPorts(des, initial *JobTemplateTemplateContainersPorts, opts ...dcl.ApplyOption) *JobTemplateTemplateContainersPorts {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateContainersPorts{}
if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) {
cDes.Name = initial.Name
} else {
cDes.Name = des.Name
}
if dcl.IsZeroValue(des.ContainerPort) || (dcl.IsEmptyValueIndirect(des.ContainerPort) && dcl.IsEmptyValueIndirect(initial.ContainerPort)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.ContainerPort = initial.ContainerPort
} else {
cDes.ContainerPort = des.ContainerPort
}
return cDes
}
func canonicalizeJobTemplateTemplateContainersPortsSlice(des, initial []JobTemplateTemplateContainersPorts, opts ...dcl.ApplyOption) []JobTemplateTemplateContainersPorts {
if des == nil {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateContainersPorts, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateContainersPorts(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateContainersPorts, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateContainersPorts(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateContainersPorts(c *Client, des, nw *JobTemplateTemplateContainersPorts) *JobTemplateTemplateContainersPorts {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateContainersPorts while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Name, nw.Name) {
nw.Name = des.Name
}
return nw
}
func canonicalizeNewJobTemplateTemplateContainersPortsSet(c *Client, des, nw []JobTemplateTemplateContainersPorts) []JobTemplateTemplateContainersPorts {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateContainersPorts
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateContainersPortsNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateContainersPorts(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateContainersPortsSlice(c *Client, des, nw []JobTemplateTemplateContainersPorts) []JobTemplateTemplateContainersPorts {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateContainersPorts
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateContainersPorts(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateContainersVolumeMounts(des, initial *JobTemplateTemplateContainersVolumeMounts, opts ...dcl.ApplyOption) *JobTemplateTemplateContainersVolumeMounts {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateContainersVolumeMounts{}
if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) {
cDes.Name = initial.Name
} else {
cDes.Name = des.Name
}
if dcl.StringCanonicalize(des.MountPath, initial.MountPath) || dcl.IsZeroValue(des.MountPath) {
cDes.MountPath = initial.MountPath
} else {
cDes.MountPath = des.MountPath
}
return cDes
}
func canonicalizeJobTemplateTemplateContainersVolumeMountsSlice(des, initial []JobTemplateTemplateContainersVolumeMounts, opts ...dcl.ApplyOption) []JobTemplateTemplateContainersVolumeMounts {
if des == nil {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateContainersVolumeMounts, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateContainersVolumeMounts(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateContainersVolumeMounts, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateContainersVolumeMounts(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateContainersVolumeMounts(c *Client, des, nw *JobTemplateTemplateContainersVolumeMounts) *JobTemplateTemplateContainersVolumeMounts {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateContainersVolumeMounts while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Name, nw.Name) {
nw.Name = des.Name
}
if dcl.StringCanonicalize(des.MountPath, nw.MountPath) {
nw.MountPath = des.MountPath
}
return nw
}
func canonicalizeNewJobTemplateTemplateContainersVolumeMountsSet(c *Client, des, nw []JobTemplateTemplateContainersVolumeMounts) []JobTemplateTemplateContainersVolumeMounts {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateContainersVolumeMounts
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateContainersVolumeMountsNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateContainersVolumeMounts(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateContainersVolumeMountsSlice(c *Client, des, nw []JobTemplateTemplateContainersVolumeMounts) []JobTemplateTemplateContainersVolumeMounts {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateContainersVolumeMounts
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateContainersVolumeMounts(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateVolumes(des, initial *JobTemplateTemplateVolumes, opts ...dcl.ApplyOption) *JobTemplateTemplateVolumes {
if des == nil {
return initial
}
if des.empty {
return des
}
if des.Secret != nil || (initial != nil && initial.Secret != nil) {
// Check if anything else is set.
if dcl.AnySet(des.CloudSqlInstance) {
des.Secret = nil
if initial != nil {
initial.Secret = nil
}
}
}
if des.CloudSqlInstance != nil || (initial != nil && initial.CloudSqlInstance != nil) {
// Check if anything else is set.
if dcl.AnySet(des.Secret) {
des.CloudSqlInstance = nil
if initial != nil {
initial.CloudSqlInstance = nil
}
}
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateVolumes{}
if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) {
cDes.Name = initial.Name
} else {
cDes.Name = des.Name
}
cDes.Secret = canonicalizeJobTemplateTemplateVolumesSecret(des.Secret, initial.Secret, opts...)
cDes.CloudSqlInstance = canonicalizeJobTemplateTemplateVolumesCloudSqlInstance(des.CloudSqlInstance, initial.CloudSqlInstance, opts...)
return cDes
}
func canonicalizeJobTemplateTemplateVolumesSlice(des, initial []JobTemplateTemplateVolumes, opts ...dcl.ApplyOption) []JobTemplateTemplateVolumes {
if des == nil {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateVolumes, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateVolumes(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateVolumes, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateVolumes(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateVolumes(c *Client, des, nw *JobTemplateTemplateVolumes) *JobTemplateTemplateVolumes {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateVolumes while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Name, nw.Name) {
nw.Name = des.Name
}
nw.Secret = canonicalizeNewJobTemplateTemplateVolumesSecret(c, des.Secret, nw.Secret)
nw.CloudSqlInstance = canonicalizeNewJobTemplateTemplateVolumesCloudSqlInstance(c, des.CloudSqlInstance, nw.CloudSqlInstance)
return nw
}
func canonicalizeNewJobTemplateTemplateVolumesSet(c *Client, des, nw []JobTemplateTemplateVolumes) []JobTemplateTemplateVolumes {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateVolumes
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateVolumesNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateVolumes(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateVolumesSlice(c *Client, des, nw []JobTemplateTemplateVolumes) []JobTemplateTemplateVolumes {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateVolumes
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateVolumes(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateVolumesSecret(des, initial *JobTemplateTemplateVolumesSecret, opts ...dcl.ApplyOption) *JobTemplateTemplateVolumesSecret {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateVolumesSecret{}
if dcl.StringCanonicalize(des.Secret, initial.Secret) || dcl.IsZeroValue(des.Secret) {
cDes.Secret = initial.Secret
} else {
cDes.Secret = des.Secret
}
cDes.Items = canonicalizeJobTemplateTemplateVolumesSecretItemsSlice(des.Items, initial.Items, opts...)
if dcl.IsZeroValue(des.DefaultMode) || (dcl.IsEmptyValueIndirect(des.DefaultMode) && dcl.IsEmptyValueIndirect(initial.DefaultMode)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.DefaultMode = initial.DefaultMode
} else {
cDes.DefaultMode = des.DefaultMode
}
return cDes
}
func canonicalizeJobTemplateTemplateVolumesSecretSlice(des, initial []JobTemplateTemplateVolumesSecret, opts ...dcl.ApplyOption) []JobTemplateTemplateVolumesSecret {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateVolumesSecret, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateVolumesSecret(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateVolumesSecret, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateVolumesSecret(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateVolumesSecret(c *Client, des, nw *JobTemplateTemplateVolumesSecret) *JobTemplateTemplateVolumesSecret {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateVolumesSecret while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Secret, nw.Secret) {
nw.Secret = des.Secret
}
nw.Items = canonicalizeNewJobTemplateTemplateVolumesSecretItemsSlice(c, des.Items, nw.Items)
return nw
}
func canonicalizeNewJobTemplateTemplateVolumesSecretSet(c *Client, des, nw []JobTemplateTemplateVolumesSecret) []JobTemplateTemplateVolumesSecret {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateVolumesSecret
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateVolumesSecretNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateVolumesSecret(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateVolumesSecretSlice(c *Client, des, nw []JobTemplateTemplateVolumesSecret) []JobTemplateTemplateVolumesSecret {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateVolumesSecret
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateVolumesSecret(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateVolumesSecretItems(des, initial *JobTemplateTemplateVolumesSecretItems, opts ...dcl.ApplyOption) *JobTemplateTemplateVolumesSecretItems {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateVolumesSecretItems{}
if dcl.StringCanonicalize(des.Path, initial.Path) || dcl.IsZeroValue(des.Path) {
cDes.Path = initial.Path
} else {
cDes.Path = des.Path
}
if dcl.StringCanonicalize(des.Version, initial.Version) || dcl.IsZeroValue(des.Version) {
cDes.Version = initial.Version
} else {
cDes.Version = des.Version
}
if dcl.IsZeroValue(des.Mode) || (dcl.IsEmptyValueIndirect(des.Mode) && dcl.IsEmptyValueIndirect(initial.Mode)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Mode = initial.Mode
} else {
cDes.Mode = des.Mode
}
return cDes
}
func canonicalizeJobTemplateTemplateVolumesSecretItemsSlice(des, initial []JobTemplateTemplateVolumesSecretItems, opts ...dcl.ApplyOption) []JobTemplateTemplateVolumesSecretItems {
if des == nil {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateVolumesSecretItems, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateVolumesSecretItems(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateVolumesSecretItems, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateVolumesSecretItems(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateVolumesSecretItems(c *Client, des, nw *JobTemplateTemplateVolumesSecretItems) *JobTemplateTemplateVolumesSecretItems {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateVolumesSecretItems while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Path, nw.Path) {
nw.Path = des.Path
}
if dcl.StringCanonicalize(des.Version, nw.Version) {
nw.Version = des.Version
}
return nw
}
func canonicalizeNewJobTemplateTemplateVolumesSecretItemsSet(c *Client, des, nw []JobTemplateTemplateVolumesSecretItems) []JobTemplateTemplateVolumesSecretItems {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateVolumesSecretItems
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateVolumesSecretItemsNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateVolumesSecretItems(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateVolumesSecretItemsSlice(c *Client, des, nw []JobTemplateTemplateVolumesSecretItems) []JobTemplateTemplateVolumesSecretItems {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateVolumesSecretItems
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateVolumesSecretItems(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateVolumesCloudSqlInstance(des, initial *JobTemplateTemplateVolumesCloudSqlInstance, opts ...dcl.ApplyOption) *JobTemplateTemplateVolumesCloudSqlInstance {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateVolumesCloudSqlInstance{}
if dcl.StringArrayCanonicalize(des.Instances, initial.Instances) {
cDes.Instances = initial.Instances
} else {
cDes.Instances = des.Instances
}
return cDes
}
func canonicalizeJobTemplateTemplateVolumesCloudSqlInstanceSlice(des, initial []JobTemplateTemplateVolumesCloudSqlInstance, opts ...dcl.ApplyOption) []JobTemplateTemplateVolumesCloudSqlInstance {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateVolumesCloudSqlInstance, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateVolumesCloudSqlInstance(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateVolumesCloudSqlInstance, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateVolumesCloudSqlInstance(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateVolumesCloudSqlInstance(c *Client, des, nw *JobTemplateTemplateVolumesCloudSqlInstance) *JobTemplateTemplateVolumesCloudSqlInstance {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateVolumesCloudSqlInstance while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringArrayCanonicalize(des.Instances, nw.Instances) {
nw.Instances = des.Instances
}
return nw
}
func canonicalizeNewJobTemplateTemplateVolumesCloudSqlInstanceSet(c *Client, des, nw []JobTemplateTemplateVolumesCloudSqlInstance) []JobTemplateTemplateVolumesCloudSqlInstance {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateVolumesCloudSqlInstance
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateVolumesCloudSqlInstanceNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateVolumesCloudSqlInstance(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateVolumesCloudSqlInstanceSlice(c *Client, des, nw []JobTemplateTemplateVolumesCloudSqlInstance) []JobTemplateTemplateVolumesCloudSqlInstance {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateVolumesCloudSqlInstance
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateVolumesCloudSqlInstance(c, &d, &n))
}
return items
}
func canonicalizeJobTemplateTemplateVPCAccess(des, initial *JobTemplateTemplateVPCAccess, opts ...dcl.ApplyOption) *JobTemplateTemplateVPCAccess {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobTemplateTemplateVPCAccess{}
if dcl.IsZeroValue(des.Connector) || (dcl.IsEmptyValueIndirect(des.Connector) && dcl.IsEmptyValueIndirect(initial.Connector)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Connector = initial.Connector
} else {
cDes.Connector = des.Connector
}
if dcl.IsZeroValue(des.Egress) || (dcl.IsEmptyValueIndirect(des.Egress) && dcl.IsEmptyValueIndirect(initial.Egress)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Egress = initial.Egress
} else {
cDes.Egress = des.Egress
}
return cDes
}
func canonicalizeJobTemplateTemplateVPCAccessSlice(des, initial []JobTemplateTemplateVPCAccess, opts ...dcl.ApplyOption) []JobTemplateTemplateVPCAccess {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobTemplateTemplateVPCAccess, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTemplateTemplateVPCAccess(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTemplateTemplateVPCAccess, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTemplateTemplateVPCAccess(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTemplateTemplateVPCAccess(c *Client, des, nw *JobTemplateTemplateVPCAccess) *JobTemplateTemplateVPCAccess {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTemplateTemplateVPCAccess while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
return nw
}
func canonicalizeNewJobTemplateTemplateVPCAccessSet(c *Client, des, nw []JobTemplateTemplateVPCAccess) []JobTemplateTemplateVPCAccess {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTemplateTemplateVPCAccess
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTemplateTemplateVPCAccessNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTemplateTemplateVPCAccess(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTemplateTemplateVPCAccessSlice(c *Client, des, nw []JobTemplateTemplateVPCAccess) []JobTemplateTemplateVPCAccess {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTemplateTemplateVPCAccess
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTemplateTemplateVPCAccess(c, &d, &n))
}
return items
}
func canonicalizeJobTerminalCondition(des, initial *JobTerminalCondition, opts ...dcl.ApplyOption) *JobTerminalCondition {
if des == nil {
return initial
}
if des.empty {
return des
}
if des.Reason != nil || (initial != nil && initial.Reason != nil) {
// Check if anything else is set.
if dcl.AnySet(des.InternalReason, des.DomainMappingReason, des.RevisionReason, des.ExecutionReason) {
des.Reason = nil
if initial != nil {
initial.Reason = nil
}
}
}
if des.InternalReason != nil || (initial != nil && initial.InternalReason != nil) {
// Check if anything else is set.
if dcl.AnySet(des.Reason, des.DomainMappingReason, des.RevisionReason, des.ExecutionReason) {
des.InternalReason = nil
if initial != nil {
initial.InternalReason = nil
}
}
}
if des.DomainMappingReason != nil || (initial != nil && initial.DomainMappingReason != nil) {
// Check if anything else is set.
if dcl.AnySet(des.Reason, des.InternalReason, des.RevisionReason, des.ExecutionReason) {
des.DomainMappingReason = nil
if initial != nil {
initial.DomainMappingReason = nil
}
}
}
if des.RevisionReason != nil || (initial != nil && initial.RevisionReason != nil) {
// Check if anything else is set.
if dcl.AnySet(des.Reason, des.InternalReason, des.DomainMappingReason, des.ExecutionReason) {
des.RevisionReason = nil
if initial != nil {
initial.RevisionReason = nil
}
}
}
if des.ExecutionReason != nil || (initial != nil && initial.ExecutionReason != nil) {
// Check if anything else is set.
if dcl.AnySet(des.Reason, des.InternalReason, des.DomainMappingReason, des.RevisionReason) {
des.ExecutionReason = nil
if initial != nil {
initial.ExecutionReason = nil
}
}
}
if initial == nil {
return des
}
cDes := &JobTerminalCondition{}
if dcl.StringCanonicalize(des.Type, initial.Type) || dcl.IsZeroValue(des.Type) {
cDes.Type = initial.Type
} else {
cDes.Type = des.Type
}
if dcl.IsZeroValue(des.State) || (dcl.IsEmptyValueIndirect(des.State) && dcl.IsEmptyValueIndirect(initial.State)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.State = initial.State
} else {
cDes.State = des.State
}
if dcl.StringCanonicalize(des.Message, initial.Message) || dcl.IsZeroValue(des.Message) {
cDes.Message = initial.Message
} else {
cDes.Message = des.Message
}
if dcl.IsZeroValue(des.LastTransitionTime) || (dcl.IsEmptyValueIndirect(des.LastTransitionTime) && dcl.IsEmptyValueIndirect(initial.LastTransitionTime)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.LastTransitionTime = initial.LastTransitionTime
} else {
cDes.LastTransitionTime = des.LastTransitionTime
}
if dcl.IsZeroValue(des.Severity) || (dcl.IsEmptyValueIndirect(des.Severity) && dcl.IsEmptyValueIndirect(initial.Severity)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Severity = initial.Severity
} else {
cDes.Severity = des.Severity
}
if dcl.IsZeroValue(des.Reason) || (dcl.IsEmptyValueIndirect(des.Reason) && dcl.IsEmptyValueIndirect(initial.Reason)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Reason = initial.Reason
} else {
cDes.Reason = des.Reason
}
if dcl.IsZeroValue(des.InternalReason) || (dcl.IsEmptyValueIndirect(des.InternalReason) && dcl.IsEmptyValueIndirect(initial.InternalReason)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.InternalReason = initial.InternalReason
} else {
cDes.InternalReason = des.InternalReason
}
if dcl.IsZeroValue(des.DomainMappingReason) || (dcl.IsEmptyValueIndirect(des.DomainMappingReason) && dcl.IsEmptyValueIndirect(initial.DomainMappingReason)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.DomainMappingReason = initial.DomainMappingReason
} else {
cDes.DomainMappingReason = des.DomainMappingReason
}
if dcl.IsZeroValue(des.RevisionReason) || (dcl.IsEmptyValueIndirect(des.RevisionReason) && dcl.IsEmptyValueIndirect(initial.RevisionReason)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.RevisionReason = initial.RevisionReason
} else {
cDes.RevisionReason = des.RevisionReason
}
if dcl.IsZeroValue(des.ExecutionReason) || (dcl.IsEmptyValueIndirect(des.ExecutionReason) && dcl.IsEmptyValueIndirect(initial.ExecutionReason)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.ExecutionReason = initial.ExecutionReason
} else {
cDes.ExecutionReason = des.ExecutionReason
}
return cDes
}
func canonicalizeJobTerminalConditionSlice(des, initial []JobTerminalCondition, opts ...dcl.ApplyOption) []JobTerminalCondition {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobTerminalCondition, 0, len(des))
for _, d := range des {
cd := canonicalizeJobTerminalCondition(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobTerminalCondition, 0, len(des))
for i, d := range des {
cd := canonicalizeJobTerminalCondition(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobTerminalCondition(c *Client, des, nw *JobTerminalCondition) *JobTerminalCondition {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobTerminalCondition while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Type, nw.Type) {
nw.Type = des.Type
}
if dcl.StringCanonicalize(des.Message, nw.Message) {
nw.Message = des.Message
}
return nw
}
func canonicalizeNewJobTerminalConditionSet(c *Client, des, nw []JobTerminalCondition) []JobTerminalCondition {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobTerminalCondition
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobTerminalConditionNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobTerminalCondition(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobTerminalConditionSlice(c *Client, des, nw []JobTerminalCondition) []JobTerminalCondition {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobTerminalCondition
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobTerminalCondition(c, &d, &n))
}
return items
}
func canonicalizeJobConditions(des, initial *JobConditions, opts ...dcl.ApplyOption) *JobConditions {
if des == nil {
return initial
}
if des.empty {
return des
}
if des.Reason != nil || (initial != nil && initial.Reason != nil) {
// Check if anything else is set.
if dcl.AnySet(des.RevisionReason, des.ExecutionReason) {
des.Reason = nil
if initial != nil {
initial.Reason = nil
}
}
}
if des.RevisionReason != nil || (initial != nil && initial.RevisionReason != nil) {
// Check if anything else is set.
if dcl.AnySet(des.Reason, des.ExecutionReason) {
des.RevisionReason = nil
if initial != nil {
initial.RevisionReason = nil
}
}
}
if des.ExecutionReason != nil || (initial != nil && initial.ExecutionReason != nil) {
// Check if anything else is set.
if dcl.AnySet(des.Reason, des.RevisionReason) {
des.ExecutionReason = nil
if initial != nil {
initial.ExecutionReason = nil
}
}
}
if initial == nil {
return des
}
cDes := &JobConditions{}
if dcl.StringCanonicalize(des.Type, initial.Type) || dcl.IsZeroValue(des.Type) {
cDes.Type = initial.Type
} else {
cDes.Type = des.Type
}
if dcl.IsZeroValue(des.State) || (dcl.IsEmptyValueIndirect(des.State) && dcl.IsEmptyValueIndirect(initial.State)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.State = initial.State
} else {
cDes.State = des.State
}
if dcl.StringCanonicalize(des.Message, initial.Message) || dcl.IsZeroValue(des.Message) {
cDes.Message = initial.Message
} else {
cDes.Message = des.Message
}
if dcl.IsZeroValue(des.LastTransitionTime) || (dcl.IsEmptyValueIndirect(des.LastTransitionTime) && dcl.IsEmptyValueIndirect(initial.LastTransitionTime)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.LastTransitionTime = initial.LastTransitionTime
} else {
cDes.LastTransitionTime = des.LastTransitionTime
}
if dcl.IsZeroValue(des.Severity) || (dcl.IsEmptyValueIndirect(des.Severity) && dcl.IsEmptyValueIndirect(initial.Severity)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Severity = initial.Severity
} else {
cDes.Severity = des.Severity
}
if dcl.IsZeroValue(des.Reason) || (dcl.IsEmptyValueIndirect(des.Reason) && dcl.IsEmptyValueIndirect(initial.Reason)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Reason = initial.Reason
} else {
cDes.Reason = des.Reason
}
if dcl.IsZeroValue(des.RevisionReason) || (dcl.IsEmptyValueIndirect(des.RevisionReason) && dcl.IsEmptyValueIndirect(initial.RevisionReason)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.RevisionReason = initial.RevisionReason
} else {
cDes.RevisionReason = des.RevisionReason
}
if dcl.IsZeroValue(des.ExecutionReason) || (dcl.IsEmptyValueIndirect(des.ExecutionReason) && dcl.IsEmptyValueIndirect(initial.ExecutionReason)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.ExecutionReason = initial.ExecutionReason
} else {
cDes.ExecutionReason = des.ExecutionReason
}
return cDes
}
func canonicalizeJobConditionsSlice(des, initial []JobConditions, opts ...dcl.ApplyOption) []JobConditions {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobConditions, 0, len(des))
for _, d := range des {
cd := canonicalizeJobConditions(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobConditions, 0, len(des))
for i, d := range des {
cd := canonicalizeJobConditions(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobConditions(c *Client, des, nw *JobConditions) *JobConditions {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobConditions while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
if dcl.StringCanonicalize(des.Type, nw.Type) {
nw.Type = des.Type
}
if dcl.StringCanonicalize(des.Message, nw.Message) {
nw.Message = des.Message
}
return nw
}
func canonicalizeNewJobConditionsSet(c *Client, des, nw []JobConditions) []JobConditions {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobConditions
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobConditionsNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobConditions(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobConditionsSlice(c *Client, des, nw []JobConditions) []JobConditions {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobConditions
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobConditions(c, &d, &n))
}
return items
}
func canonicalizeJobLatestSucceededExecution(des, initial *JobLatestSucceededExecution, opts ...dcl.ApplyOption) *JobLatestSucceededExecution {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobLatestSucceededExecution{}
if dcl.IsZeroValue(des.Name) || (dcl.IsEmptyValueIndirect(des.Name) && dcl.IsEmptyValueIndirect(initial.Name)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Name = initial.Name
} else {
cDes.Name = des.Name
}
if dcl.IsZeroValue(des.CreateTime) || (dcl.IsEmptyValueIndirect(des.CreateTime) && dcl.IsEmptyValueIndirect(initial.CreateTime)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.CreateTime = initial.CreateTime
} else {
cDes.CreateTime = des.CreateTime
}
return cDes
}
func canonicalizeJobLatestSucceededExecutionSlice(des, initial []JobLatestSucceededExecution, opts ...dcl.ApplyOption) []JobLatestSucceededExecution {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobLatestSucceededExecution, 0, len(des))
for _, d := range des {
cd := canonicalizeJobLatestSucceededExecution(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobLatestSucceededExecution, 0, len(des))
for i, d := range des {
cd := canonicalizeJobLatestSucceededExecution(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobLatestSucceededExecution(c *Client, des, nw *JobLatestSucceededExecution) *JobLatestSucceededExecution {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobLatestSucceededExecution while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
return nw
}
func canonicalizeNewJobLatestSucceededExecutionSet(c *Client, des, nw []JobLatestSucceededExecution) []JobLatestSucceededExecution {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobLatestSucceededExecution
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobLatestSucceededExecutionNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobLatestSucceededExecution(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobLatestSucceededExecutionSlice(c *Client, des, nw []JobLatestSucceededExecution) []JobLatestSucceededExecution {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobLatestSucceededExecution
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobLatestSucceededExecution(c, &d, &n))
}
return items
}
func canonicalizeJobLatestCreatedExecution(des, initial *JobLatestCreatedExecution, opts ...dcl.ApplyOption) *JobLatestCreatedExecution {
if des == nil {
return initial
}
if des.empty {
return des
}
if initial == nil {
return des
}
cDes := &JobLatestCreatedExecution{}
if dcl.IsZeroValue(des.Name) || (dcl.IsEmptyValueIndirect(des.Name) && dcl.IsEmptyValueIndirect(initial.Name)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.Name = initial.Name
} else {
cDes.Name = des.Name
}
if dcl.IsZeroValue(des.CreateTime) || (dcl.IsEmptyValueIndirect(des.CreateTime) && dcl.IsEmptyValueIndirect(initial.CreateTime)) {
// Desired and initial values are equivalent, so set canonical desired value to initial value.
cDes.CreateTime = initial.CreateTime
} else {
cDes.CreateTime = des.CreateTime
}
return cDes
}
func canonicalizeJobLatestCreatedExecutionSlice(des, initial []JobLatestCreatedExecution, opts ...dcl.ApplyOption) []JobLatestCreatedExecution {
if dcl.IsEmptyValueIndirect(des) {
return initial
}
if len(des) != len(initial) {
items := make([]JobLatestCreatedExecution, 0, len(des))
for _, d := range des {
cd := canonicalizeJobLatestCreatedExecution(&d, nil, opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
items := make([]JobLatestCreatedExecution, 0, len(des))
for i, d := range des {
cd := canonicalizeJobLatestCreatedExecution(&d, &initial[i], opts...)
if cd != nil {
items = append(items, *cd)
}
}
return items
}
func canonicalizeNewJobLatestCreatedExecution(c *Client, des, nw *JobLatestCreatedExecution) *JobLatestCreatedExecution {
if des == nil {
return nw
}
if nw == nil {
if dcl.IsEmptyValueIndirect(des) {
c.Config.Logger.Info("Found explicitly empty value for JobLatestCreatedExecution while comparing non-nil desired to nil actual. Returning desired object.")
return des
}
return nil
}
return nw
}
func canonicalizeNewJobLatestCreatedExecutionSet(c *Client, des, nw []JobLatestCreatedExecution) []JobLatestCreatedExecution {
if des == nil {
return nw
}
// Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw.
var items []JobLatestCreatedExecution
for _, d := range des {
matchedIndex := -1
for i, n := range nw {
if diffs, _ := compareJobLatestCreatedExecutionNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 {
matchedIndex = i
break
}
}
if matchedIndex != -1 {
items = append(items, *canonicalizeNewJobLatestCreatedExecution(c, &d, &nw[matchedIndex]))
nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...)
}
}
// Also include elements in nw that are not matched in des.
items = append(items, nw...)
return items
}
func canonicalizeNewJobLatestCreatedExecutionSlice(c *Client, des, nw []JobLatestCreatedExecution) []JobLatestCreatedExecution {
if des == nil {
return nw
}
// Lengths are unequal. A diff will occur later, so we shouldn't canonicalize.
// Return the original array.
if len(des) != len(nw) {
return nw
}
var items []JobLatestCreatedExecution
for i, d := range des {
n := nw[i]
items = append(items, *canonicalizeNewJobLatestCreatedExecution(c, &d, &n))
}
return items
}
// The differ returns a list of diffs, along with a list of operations that should be taken
// to remedy them. Right now, it does not attempt to consolidate operations - if several
// fields can be fixed with a patch update, it will perform the patch several times.
// Diffs on some fields will be ignored if the `desired` state has an empty (nil)
// value. This empty value indicates that the user does not care about the state for
// the field. Empty fields on the actual object will cause diffs.
// TODO(magic-modules-eng): for efficiency in some resources, add batching.
func diffJob(c *Client, desired, actual *Job, opts ...dcl.ApplyOption) ([]*dcl.FieldDiff, error) {
if desired == nil || actual == nil {
return nil, fmt.Errorf("nil resource passed to diff - always a programming error: %#v, %#v", desired, actual)
}
c.Config.Logger.Infof("Diff function called with desired state: %v", desired)
c.Config.Logger.Infof("Diff function called with actual state: %v", actual)
var fn dcl.FieldName
var newDiffs []*dcl.FieldDiff
// New style diffs.
if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Uid, actual.Uid, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Uid")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Generation, actual.Generation, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Generation")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Labels, actual.Labels, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Labels")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Annotations, actual.Annotations, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Annotations")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.CreateTime, actual.CreateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("CreateTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.UpdateTime, actual.UpdateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("UpdateTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.DeleteTime, actual.DeleteTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("DeleteTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.ExpireTime, actual.ExpireTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("ExpireTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Creator, actual.Creator, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Creator")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.LastModifier, actual.LastModifier, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("LastModifier")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Client, actual.Client, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Client")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.ClientVersion, actual.ClientVersion, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("ClientVersion")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.LaunchStage, actual.LaunchStage, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("LaunchStage")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.BinaryAuthorization, actual.BinaryAuthorization, dcl.DiffInfo{ObjectFunction: compareJobBinaryAuthorizationNewStyle, EmptyObject: EmptyJobBinaryAuthorization, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("BinaryAuthorization")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Template, actual.Template, dcl.DiffInfo{ObjectFunction: compareJobTemplateNewStyle, EmptyObject: EmptyJobTemplate, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Template")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.ObservedGeneration, actual.ObservedGeneration, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("ObservedGeneration")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.TerminalCondition, actual.TerminalCondition, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareJobTerminalConditionNewStyle, EmptyObject: EmptyJobTerminalCondition, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("TerminalCondition")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Conditions, actual.Conditions, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareJobConditionsNewStyle, EmptyObject: EmptyJobConditions, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Conditions")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.ExecutionCount, actual.ExecutionCount, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("ExecutionCount")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.LatestSucceededExecution, actual.LatestSucceededExecution, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareJobLatestSucceededExecutionNewStyle, EmptyObject: EmptyJobLatestSucceededExecution, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("LatestSucceededExecution")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.LatestCreatedExecution, actual.LatestCreatedExecution, dcl.DiffInfo{OutputOnly: true, ObjectFunction: compareJobLatestCreatedExecutionNewStyle, EmptyObject: EmptyJobLatestCreatedExecution, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("LatestCreatedExecution")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Reconciling, actual.Reconciling, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Reconciling")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Etag, actual.Etag, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Etag")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Project, actual.Project, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Project")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if ds, err := dcl.Diff(desired.Location, actual.Location, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Location")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
newDiffs = append(newDiffs, ds...)
}
if len(newDiffs) > 0 {
c.Config.Logger.Infof("Diff function found diffs: %v", newDiffs)
}
return newDiffs, nil
}
func compareJobBinaryAuthorizationNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobBinaryAuthorization)
if !ok {
desiredNotPointer, ok := d.(JobBinaryAuthorization)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobBinaryAuthorization or *JobBinaryAuthorization", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobBinaryAuthorization)
if !ok {
actualNotPointer, ok := a.(JobBinaryAuthorization)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobBinaryAuthorization", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.UseDefault, actual.UseDefault, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("UseDefault")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.BreakglassJustification, actual.BreakglassJustification, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("BreakglassJustification")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplate)
if !ok {
desiredNotPointer, ok := d.(JobTemplate)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplate or *JobTemplate", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplate)
if !ok {
actualNotPointer, ok := a.(JobTemplate)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplate", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Labels, actual.Labels, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Labels")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Annotations, actual.Annotations, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Annotations")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Parallelism, actual.Parallelism, dcl.DiffInfo{ServerDefault: true, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Parallelism")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.TaskCount, actual.TaskCount, dcl.DiffInfo{ServerDefault: true, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("TaskCount")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Template, actual.Template, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateNewStyle, EmptyObject: EmptyJobTemplateTemplate, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Template")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplate)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplate)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplate or *JobTemplateTemplate", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplate)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplate)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplate", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Containers, actual.Containers, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateContainersNewStyle, EmptyObject: EmptyJobTemplateTemplateContainers, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Containers")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Volumes, actual.Volumes, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateVolumesNewStyle, EmptyObject: EmptyJobTemplateTemplateVolumes, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Volumes")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.MaxRetries, actual.MaxRetries, dcl.DiffInfo{ServerDefault: true, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("MaxRetries")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Timeout, actual.Timeout, dcl.DiffInfo{ServerDefault: true, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Timeout")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.ServiceAccount, actual.ServiceAccount, dcl.DiffInfo{ServerDefault: true, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("ServiceAccount")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.ExecutionEnvironment, actual.ExecutionEnvironment, dcl.DiffInfo{ServerDefault: true, Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("ExecutionEnvironment")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.EncryptionKey, actual.EncryptionKey, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("EncryptionKey")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.VPCAccess, actual.VPCAccess, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateVPCAccessNewStyle, EmptyObject: EmptyJobTemplateTemplateVPCAccess, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("VpcAccess")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateContainersNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateContainers)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateContainers)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainers or *JobTemplateTemplateContainers", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateContainers)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateContainers)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainers", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Image, actual.Image, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Image")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Command, actual.Command, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Command")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Args, actual.Args, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Args")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Env, actual.Env, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateContainersEnvNewStyle, EmptyObject: EmptyJobTemplateTemplateContainersEnv, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Env")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Resources, actual.Resources, dcl.DiffInfo{ServerDefault: true, ObjectFunction: compareJobTemplateTemplateContainersResourcesNewStyle, EmptyObject: EmptyJobTemplateTemplateContainersResources, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Resources")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Ports, actual.Ports, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateContainersPortsNewStyle, EmptyObject: EmptyJobTemplateTemplateContainersPorts, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Ports")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.VolumeMounts, actual.VolumeMounts, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateContainersVolumeMountsNewStyle, EmptyObject: EmptyJobTemplateTemplateContainersVolumeMounts, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("VolumeMounts")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateContainersEnvNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateContainersEnv)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateContainersEnv)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersEnv or *JobTemplateTemplateContainersEnv", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateContainersEnv)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateContainersEnv)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersEnv", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Value, actual.Value, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Value")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.ValueSource, actual.ValueSource, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateContainersEnvValueSourceNewStyle, EmptyObject: EmptyJobTemplateTemplateContainersEnvValueSource, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("ValueSource")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateContainersEnvValueSourceNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateContainersEnvValueSource)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateContainersEnvValueSource)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersEnvValueSource or *JobTemplateTemplateContainersEnvValueSource", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateContainersEnvValueSource)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateContainersEnvValueSource)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersEnvValueSource", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.SecretKeyRef, actual.SecretKeyRef, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateContainersEnvValueSourceSecretKeyRefNewStyle, EmptyObject: EmptyJobTemplateTemplateContainersEnvValueSourceSecretKeyRef, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("SecretKeyRef")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateContainersEnvValueSourceSecretKeyRefNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateContainersEnvValueSourceSecretKeyRef)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateContainersEnvValueSourceSecretKeyRef)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersEnvValueSourceSecretKeyRef or *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateContainersEnvValueSourceSecretKeyRef)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateContainersEnvValueSourceSecretKeyRef)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersEnvValueSourceSecretKeyRef", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Secret, actual.Secret, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Secret")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Version, actual.Version, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Version")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateContainersResourcesNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateContainersResources)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateContainersResources)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersResources or *JobTemplateTemplateContainersResources", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateContainersResources)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateContainersResources)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersResources", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Limits, actual.Limits, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Limits")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.CpuIdle, actual.CpuIdle, dcl.DiffInfo{ServerDefault: true, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("CpuIdle")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateContainersPortsNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateContainersPorts)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateContainersPorts)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersPorts or *JobTemplateTemplateContainersPorts", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateContainersPorts)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateContainersPorts)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersPorts", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.ContainerPort, actual.ContainerPort, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("ContainerPort")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateContainersVolumeMountsNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateContainersVolumeMounts)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateContainersVolumeMounts)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersVolumeMounts or *JobTemplateTemplateContainersVolumeMounts", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateContainersVolumeMounts)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateContainersVolumeMounts)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateContainersVolumeMounts", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.MountPath, actual.MountPath, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("MountPath")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateVolumesNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateVolumes)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateVolumes)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVolumes or *JobTemplateTemplateVolumes", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateVolumes)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateVolumes)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVolumes", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Secret, actual.Secret, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateVolumesSecretNewStyle, EmptyObject: EmptyJobTemplateTemplateVolumesSecret, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Secret")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.CloudSqlInstance, actual.CloudSqlInstance, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateVolumesCloudSqlInstanceNewStyle, EmptyObject: EmptyJobTemplateTemplateVolumesCloudSqlInstance, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("CloudSqlInstance")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateVolumesSecretNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateVolumesSecret)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateVolumesSecret)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVolumesSecret or *JobTemplateTemplateVolumesSecret", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateVolumesSecret)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateVolumesSecret)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVolumesSecret", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Secret, actual.Secret, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Secret")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Items, actual.Items, dcl.DiffInfo{ObjectFunction: compareJobTemplateTemplateVolumesSecretItemsNewStyle, EmptyObject: EmptyJobTemplateTemplateVolumesSecretItems, OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Items")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.DefaultMode, actual.DefaultMode, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("DefaultMode")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateVolumesSecretItemsNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateVolumesSecretItems)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateVolumesSecretItems)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVolumesSecretItems or *JobTemplateTemplateVolumesSecretItems", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateVolumesSecretItems)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateVolumesSecretItems)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVolumesSecretItems", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Path, actual.Path, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Path")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Version, actual.Version, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Version")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Mode, actual.Mode, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Mode")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateVolumesCloudSqlInstanceNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateVolumesCloudSqlInstance)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateVolumesCloudSqlInstance)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVolumesCloudSqlInstance or *JobTemplateTemplateVolumesCloudSqlInstance", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateVolumesCloudSqlInstance)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateVolumesCloudSqlInstance)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVolumesCloudSqlInstance", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Instances, actual.Instances, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Instances")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTemplateTemplateVPCAccessNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTemplateTemplateVPCAccess)
if !ok {
desiredNotPointer, ok := d.(JobTemplateTemplateVPCAccess)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVPCAccess or *JobTemplateTemplateVPCAccess", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTemplateTemplateVPCAccess)
if !ok {
actualNotPointer, ok := a.(JobTemplateTemplateVPCAccess)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTemplateTemplateVPCAccess", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Connector, actual.Connector, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Connector")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Egress, actual.Egress, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Egress")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobTerminalConditionNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobTerminalCondition)
if !ok {
desiredNotPointer, ok := d.(JobTerminalCondition)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTerminalCondition or *JobTerminalCondition", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobTerminalCondition)
if !ok {
actualNotPointer, ok := a.(JobTerminalCondition)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobTerminalCondition", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Type, actual.Type, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Type")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.State, actual.State, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("State")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Message, actual.Message, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Message")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.LastTransitionTime, actual.LastTransitionTime, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("LastTransitionTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Severity, actual.Severity, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Severity")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Reason, actual.Reason, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Reason")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.InternalReason, actual.InternalReason, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("InternalReason")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.DomainMappingReason, actual.DomainMappingReason, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("DomainMappingReason")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.RevisionReason, actual.RevisionReason, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("RevisionReason")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.ExecutionReason, actual.ExecutionReason, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("ExecutionReason")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobConditionsNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobConditions)
if !ok {
desiredNotPointer, ok := d.(JobConditions)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobConditions or *JobConditions", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobConditions)
if !ok {
actualNotPointer, ok := a.(JobConditions)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobConditions", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Type, actual.Type, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Type")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.State, actual.State, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("State")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Message, actual.Message, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Message")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.LastTransitionTime, actual.LastTransitionTime, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("LastTransitionTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Severity, actual.Severity, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Severity")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.Reason, actual.Reason, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Reason")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.RevisionReason, actual.RevisionReason, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("RevisionReason")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.ExecutionReason, actual.ExecutionReason, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("ExecutionReason")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobLatestSucceededExecutionNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobLatestSucceededExecution)
if !ok {
desiredNotPointer, ok := d.(JobLatestSucceededExecution)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobLatestSucceededExecution or *JobLatestSucceededExecution", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobLatestSucceededExecution)
if !ok {
actualNotPointer, ok := a.(JobLatestSucceededExecution)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobLatestSucceededExecution", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.CreateTime, actual.CreateTime, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("CreateTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
func compareJobLatestCreatedExecutionNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) {
var diffs []*dcl.FieldDiff
desired, ok := d.(*JobLatestCreatedExecution)
if !ok {
desiredNotPointer, ok := d.(JobLatestCreatedExecution)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobLatestCreatedExecution or *JobLatestCreatedExecution", d)
}
desired = &desiredNotPointer
}
actual, ok := a.(*JobLatestCreatedExecution)
if !ok {
actualNotPointer, ok := a.(JobLatestCreatedExecution)
if !ok {
return nil, fmt.Errorf("obj %v is not a JobLatestCreatedExecution", a)
}
actual = &actualNotPointer
}
if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
if ds, err := dcl.Diff(desired.CreateTime, actual.CreateTime, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateJobUpdateJobOperation")}, fn.AddNest("CreateTime")); len(ds) != 0 || err != nil {
if err != nil {
return nil, err
}
diffs = append(diffs, ds...)
}
return diffs, nil
}
// urlNormalized returns a copy of the resource struct with values normalized
// for URL substitutions. For instance, it converts long-form self-links to
// short-form so they can be substituted in.
func (r *Job) urlNormalized() *Job {
normalized := dcl.Copy(*r).(Job)
normalized.Name = dcl.SelfLinkToName(r.Name)
normalized.Uid = dcl.SelfLinkToName(r.Uid)
normalized.Creator = dcl.SelfLinkToName(r.Creator)
normalized.LastModifier = dcl.SelfLinkToName(r.LastModifier)
normalized.Client = dcl.SelfLinkToName(r.Client)
normalized.ClientVersion = dcl.SelfLinkToName(r.ClientVersion)
normalized.Etag = dcl.SelfLinkToName(r.Etag)
normalized.Project = dcl.SelfLinkToName(r.Project)
normalized.Location = dcl.SelfLinkToName(r.Location)
return &normalized
}
func (r *Job) updateURL(userBasePath, updateName string) (string, error) {
nr := r.urlNormalized()
if updateName == "UpdateJob" {
fields := map[string]interface{}{
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
"name": dcl.ValueOrEmptyString(nr.Name),
}
return dcl.URL("projects/{{project}}/locations/{{location}}/jobs/{{name}}", nr.basePath(), userBasePath, fields), nil
}
return "", fmt.Errorf("unknown update name: %s", updateName)
}
// marshal encodes the Job resource into JSON for a Create request, and
// performs transformations from the resource schema to the API schema if
// necessary.
func (r *Job) marshal(c *Client) ([]byte, error) {
m, err := expandJob(c, r)
if err != nil {
return nil, fmt.Errorf("error marshalling Job: %w", err)
}
return json.Marshal(m)
}
// unmarshalJob decodes JSON responses into the Job resource schema.
func unmarshalJob(b []byte, c *Client, res *Job) (*Job, error) {
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
return unmarshalMapJob(m, c, res)
}
func unmarshalMapJob(m map[string]interface{}, c *Client, res *Job) (*Job, error) {
flattened := flattenJob(c, m, res)
if flattened == nil {
return nil, fmt.Errorf("attempted to flatten empty json object")
}
return flattened, nil
}
// expandJob expands Job into a JSON request object.
func expandJob(c *Client, f *Job) (map[string]interface{}, error) {
m := make(map[string]interface{})
res := f
_ = res
if v, err := dcl.DeriveField("projects/%s/locations/%s/jobs/%s", f.Name, dcl.SelfLinkToName(f.Project), dcl.SelfLinkToName(f.Location), dcl.SelfLinkToName(f.Name)); err != nil {
return nil, fmt.Errorf("error expanding Name into name: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["name"] = v
}
if v := f.Annotations; dcl.ValueShouldBeSent(v) {
m["annotations"] = v
}
if v := f.Client; dcl.ValueShouldBeSent(v) {
m["client"] = v
}
if v := f.ClientVersion; dcl.ValueShouldBeSent(v) {
m["clientVersion"] = v
}
if v := f.LaunchStage; dcl.ValueShouldBeSent(v) {
m["launchStage"] = v
}
if v, err := expandJobBinaryAuthorization(c, f.BinaryAuthorization, res); err != nil {
return nil, fmt.Errorf("error expanding BinaryAuthorization into binaryAuthorization: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["binaryAuthorization"] = v
}
if v, err := expandJobTemplate(c, f.Template, res); err != nil {
return nil, fmt.Errorf("error expanding Template into template: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["template"] = v
}
if v, err := dcl.EmptyValue(); err != nil {
return nil, fmt.Errorf("error expanding Project into project: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["project"] = v
}
if v, err := dcl.EmptyValue(); err != nil {
return nil, fmt.Errorf("error expanding Location into location: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["location"] = v
}
return m, nil
}
// flattenJob flattens Job from a JSON request object into the
// Job type.
func flattenJob(c *Client, i interface{}, res *Job) *Job {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
if len(m) == 0 {
return nil
}
resultRes := &Job{}
resultRes.Name = dcl.FlattenString(m["name"])
resultRes.Uid = dcl.FlattenString(m["uid"])
resultRes.Generation = dcl.FlattenInteger(m["generation"])
resultRes.Labels = dcl.FlattenKeyValuePairs(m["labels"])
resultRes.Annotations = dcl.FlattenKeyValuePairs(m["annotations"])
resultRes.CreateTime = dcl.FlattenString(m["createTime"])
resultRes.UpdateTime = dcl.FlattenString(m["updateTime"])
resultRes.DeleteTime = dcl.FlattenString(m["deleteTime"])
resultRes.ExpireTime = dcl.FlattenString(m["expireTime"])
resultRes.Creator = dcl.FlattenString(m["creator"])
resultRes.LastModifier = dcl.FlattenString(m["lastModifier"])
resultRes.Client = dcl.FlattenString(m["client"])
resultRes.ClientVersion = dcl.FlattenString(m["clientVersion"])
resultRes.LaunchStage = flattenJobLaunchStageEnum(m["launchStage"])
resultRes.BinaryAuthorization = flattenJobBinaryAuthorization(c, m["binaryAuthorization"], res)
resultRes.Template = flattenJobTemplate(c, m["template"], res)
resultRes.ObservedGeneration = dcl.FlattenInteger(m["observedGeneration"])
resultRes.TerminalCondition = flattenJobTerminalCondition(c, m["terminalCondition"], res)
resultRes.Conditions = flattenJobConditionsSlice(c, m["conditions"], res)
resultRes.ExecutionCount = dcl.FlattenInteger(m["executionCount"])
resultRes.LatestSucceededExecution = flattenJobLatestSucceededExecution(c, m["latestSucceededExecution"], res)
resultRes.LatestCreatedExecution = flattenJobLatestCreatedExecution(c, m["latestCreatedExecution"], res)
resultRes.Reconciling = dcl.FlattenBool(m["reconciling"])
resultRes.Etag = dcl.FlattenString(m["etag"])
resultRes.Project = dcl.FlattenString(m["project"])
resultRes.Location = dcl.FlattenString(m["location"])
return resultRes
}
// expandJobBinaryAuthorizationMap expands the contents of JobBinaryAuthorization into a JSON
// request object.
func expandJobBinaryAuthorizationMap(c *Client, f map[string]JobBinaryAuthorization, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobBinaryAuthorization(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobBinaryAuthorizationSlice expands the contents of JobBinaryAuthorization into a JSON
// request object.
func expandJobBinaryAuthorizationSlice(c *Client, f []JobBinaryAuthorization, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobBinaryAuthorization(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobBinaryAuthorizationMap flattens the contents of JobBinaryAuthorization from a JSON
// response object.
func flattenJobBinaryAuthorizationMap(c *Client, i interface{}, res *Job) map[string]JobBinaryAuthorization {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobBinaryAuthorization{}
}
if len(a) == 0 {
return map[string]JobBinaryAuthorization{}
}
items := make(map[string]JobBinaryAuthorization)
for k, item := range a {
items[k] = *flattenJobBinaryAuthorization(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobBinaryAuthorizationSlice flattens the contents of JobBinaryAuthorization from a JSON
// response object.
func flattenJobBinaryAuthorizationSlice(c *Client, i interface{}, res *Job) []JobBinaryAuthorization {
a, ok := i.([]interface{})
if !ok {
return []JobBinaryAuthorization{}
}
if len(a) == 0 {
return []JobBinaryAuthorization{}
}
items := make([]JobBinaryAuthorization, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobBinaryAuthorization(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobBinaryAuthorization expands an instance of JobBinaryAuthorization into a JSON
// request object.
func expandJobBinaryAuthorization(c *Client, f *JobBinaryAuthorization, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.UseDefault; !dcl.IsEmptyValueIndirect(v) {
m["useDefault"] = v
}
if v := f.BreakglassJustification; !dcl.IsEmptyValueIndirect(v) {
m["breakglassJustification"] = v
}
return m, nil
}
// flattenJobBinaryAuthorization flattens an instance of JobBinaryAuthorization from a JSON
// response object.
func flattenJobBinaryAuthorization(c *Client, i interface{}, res *Job) *JobBinaryAuthorization {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobBinaryAuthorization{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobBinaryAuthorization
}
r.UseDefault = dcl.FlattenBool(m["useDefault"])
r.BreakglassJustification = dcl.FlattenString(m["breakglassJustification"])
return r
}
// expandJobTemplateMap expands the contents of JobTemplate into a JSON
// request object.
func expandJobTemplateMap(c *Client, f map[string]JobTemplate, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplate(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateSlice expands the contents of JobTemplate into a JSON
// request object.
func expandJobTemplateSlice(c *Client, f []JobTemplate, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplate(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateMap flattens the contents of JobTemplate from a JSON
// response object.
func flattenJobTemplateMap(c *Client, i interface{}, res *Job) map[string]JobTemplate {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplate{}
}
if len(a) == 0 {
return map[string]JobTemplate{}
}
items := make(map[string]JobTemplate)
for k, item := range a {
items[k] = *flattenJobTemplate(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateSlice flattens the contents of JobTemplate from a JSON
// response object.
func flattenJobTemplateSlice(c *Client, i interface{}, res *Job) []JobTemplate {
a, ok := i.([]interface{})
if !ok {
return []JobTemplate{}
}
if len(a) == 0 {
return []JobTemplate{}
}
items := make([]JobTemplate, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplate(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplate expands an instance of JobTemplate into a JSON
// request object.
func expandJobTemplate(c *Client, f *JobTemplate, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Labels; !dcl.IsEmptyValueIndirect(v) {
m["labels"] = v
}
if v := f.Annotations; !dcl.IsEmptyValueIndirect(v) {
m["annotations"] = v
}
if v := f.Parallelism; !dcl.IsEmptyValueIndirect(v) {
m["parallelism"] = v
}
if v := f.TaskCount; !dcl.IsEmptyValueIndirect(v) {
m["taskCount"] = v
}
if v, err := expandJobTemplateTemplate(c, f.Template, res); err != nil {
return nil, fmt.Errorf("error expanding Template into template: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["template"] = v
}
return m, nil
}
// flattenJobTemplate flattens an instance of JobTemplate from a JSON
// response object.
func flattenJobTemplate(c *Client, i interface{}, res *Job) *JobTemplate {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplate{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplate
}
r.Labels = dcl.FlattenKeyValuePairs(m["labels"])
r.Annotations = dcl.FlattenKeyValuePairs(m["annotations"])
r.Parallelism = dcl.FlattenInteger(m["parallelism"])
r.TaskCount = dcl.FlattenInteger(m["taskCount"])
r.Template = flattenJobTemplateTemplate(c, m["template"], res)
return r
}
// expandJobTemplateTemplateMap expands the contents of JobTemplateTemplate into a JSON
// request object.
func expandJobTemplateTemplateMap(c *Client, f map[string]JobTemplateTemplate, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplate(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateSlice expands the contents of JobTemplateTemplate into a JSON
// request object.
func expandJobTemplateTemplateSlice(c *Client, f []JobTemplateTemplate, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplate(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateMap flattens the contents of JobTemplateTemplate from a JSON
// response object.
func flattenJobTemplateTemplateMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplate {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplate{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplate{}
}
items := make(map[string]JobTemplateTemplate)
for k, item := range a {
items[k] = *flattenJobTemplateTemplate(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateSlice flattens the contents of JobTemplateTemplate from a JSON
// response object.
func flattenJobTemplateTemplateSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplate {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplate{}
}
if len(a) == 0 {
return []JobTemplateTemplate{}
}
items := make([]JobTemplateTemplate, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplate(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplate expands an instance of JobTemplateTemplate into a JSON
// request object.
func expandJobTemplateTemplate(c *Client, f *JobTemplateTemplate, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v, err := expandJobTemplateTemplateContainersSlice(c, f.Containers, res); err != nil {
return nil, fmt.Errorf("error expanding Containers into containers: %w", err)
} else if v != nil {
m["containers"] = v
}
if v, err := expandJobTemplateTemplateVolumesSlice(c, f.Volumes, res); err != nil {
return nil, fmt.Errorf("error expanding Volumes into volumes: %w", err)
} else if v != nil {
m["volumes"] = v
}
if v := f.MaxRetries; !dcl.IsEmptyValueIndirect(v) {
m["maxRetries"] = v
}
if v := f.Timeout; !dcl.IsEmptyValueIndirect(v) {
m["timeout"] = v
}
if v := f.ServiceAccount; !dcl.IsEmptyValueIndirect(v) {
m["serviceAccount"] = v
}
if v := f.ExecutionEnvironment; !dcl.IsEmptyValueIndirect(v) {
m["executionEnvironment"] = v
}
if v := f.EncryptionKey; !dcl.IsEmptyValueIndirect(v) {
m["encryptionKey"] = v
}
if v, err := expandJobTemplateTemplateVPCAccess(c, f.VPCAccess, res); err != nil {
return nil, fmt.Errorf("error expanding VPCAccess into vpcAccess: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["vpcAccess"] = v
}
return m, nil
}
// flattenJobTemplateTemplate flattens an instance of JobTemplateTemplate from a JSON
// response object.
func flattenJobTemplateTemplate(c *Client, i interface{}, res *Job) *JobTemplateTemplate {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplate{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplate
}
r.Containers = flattenJobTemplateTemplateContainersSlice(c, m["containers"], res)
r.Volumes = flattenJobTemplateTemplateVolumesSlice(c, m["volumes"], res)
r.MaxRetries = dcl.FlattenInteger(m["maxRetries"])
r.Timeout = dcl.FlattenString(m["timeout"])
r.ServiceAccount = dcl.FlattenString(m["serviceAccount"])
r.ExecutionEnvironment = flattenJobTemplateTemplateExecutionEnvironmentEnum(m["executionEnvironment"])
r.EncryptionKey = dcl.FlattenString(m["encryptionKey"])
r.VPCAccess = flattenJobTemplateTemplateVPCAccess(c, m["vpcAccess"], res)
return r
}
// expandJobTemplateTemplateContainersMap expands the contents of JobTemplateTemplateContainers into a JSON
// request object.
func expandJobTemplateTemplateContainersMap(c *Client, f map[string]JobTemplateTemplateContainers, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateContainers(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateContainersSlice expands the contents of JobTemplateTemplateContainers into a JSON
// request object.
func expandJobTemplateTemplateContainersSlice(c *Client, f []JobTemplateTemplateContainers, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateContainers(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateContainersMap flattens the contents of JobTemplateTemplateContainers from a JSON
// response object.
func flattenJobTemplateTemplateContainersMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateContainers {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateContainers{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateContainers{}
}
items := make(map[string]JobTemplateTemplateContainers)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateContainers(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateContainersSlice flattens the contents of JobTemplateTemplateContainers from a JSON
// response object.
func flattenJobTemplateTemplateContainersSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateContainers {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateContainers{}
}
if len(a) == 0 {
return []JobTemplateTemplateContainers{}
}
items := make([]JobTemplateTemplateContainers, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateContainers(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateContainers expands an instance of JobTemplateTemplateContainers into a JSON
// request object.
func expandJobTemplateTemplateContainers(c *Client, f *JobTemplateTemplateContainers, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Name; !dcl.IsEmptyValueIndirect(v) {
m["name"] = v
}
if v := f.Image; !dcl.IsEmptyValueIndirect(v) {
m["image"] = v
}
if v := f.Command; v != nil {
m["command"] = v
}
if v := f.Args; v != nil {
m["args"] = v
}
if v, err := expandJobTemplateTemplateContainersEnvSlice(c, f.Env, res); err != nil {
return nil, fmt.Errorf("error expanding Env into env: %w", err)
} else if v != nil {
m["env"] = v
}
if v, err := expandJobTemplateTemplateContainersResources(c, f.Resources, res); err != nil {
return nil, fmt.Errorf("error expanding Resources into resources: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["resources"] = v
}
if v, err := expandJobTemplateTemplateContainersPortsSlice(c, f.Ports, res); err != nil {
return nil, fmt.Errorf("error expanding Ports into ports: %w", err)
} else if v != nil {
m["ports"] = v
}
if v, err := expandJobTemplateTemplateContainersVolumeMountsSlice(c, f.VolumeMounts, res); err != nil {
return nil, fmt.Errorf("error expanding VolumeMounts into volumeMounts: %w", err)
} else if v != nil {
m["volumeMounts"] = v
}
return m, nil
}
// flattenJobTemplateTemplateContainers flattens an instance of JobTemplateTemplateContainers from a JSON
// response object.
func flattenJobTemplateTemplateContainers(c *Client, i interface{}, res *Job) *JobTemplateTemplateContainers {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateContainers{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateContainers
}
r.Name = dcl.FlattenString(m["name"])
r.Image = dcl.FlattenString(m["image"])
r.Command = dcl.FlattenStringSlice(m["command"])
r.Args = dcl.FlattenStringSlice(m["args"])
r.Env = flattenJobTemplateTemplateContainersEnvSlice(c, m["env"], res)
r.Resources = flattenJobTemplateTemplateContainersResources(c, m["resources"], res)
r.Ports = flattenJobTemplateTemplateContainersPortsSlice(c, m["ports"], res)
r.VolumeMounts = flattenJobTemplateTemplateContainersVolumeMountsSlice(c, m["volumeMounts"], res)
return r
}
// expandJobTemplateTemplateContainersEnvMap expands the contents of JobTemplateTemplateContainersEnv into a JSON
// request object.
func expandJobTemplateTemplateContainersEnvMap(c *Client, f map[string]JobTemplateTemplateContainersEnv, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateContainersEnv(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateContainersEnvSlice expands the contents of JobTemplateTemplateContainersEnv into a JSON
// request object.
func expandJobTemplateTemplateContainersEnvSlice(c *Client, f []JobTemplateTemplateContainersEnv, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateContainersEnv(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateContainersEnvMap flattens the contents of JobTemplateTemplateContainersEnv from a JSON
// response object.
func flattenJobTemplateTemplateContainersEnvMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateContainersEnv {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateContainersEnv{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateContainersEnv{}
}
items := make(map[string]JobTemplateTemplateContainersEnv)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateContainersEnv(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateContainersEnvSlice flattens the contents of JobTemplateTemplateContainersEnv from a JSON
// response object.
func flattenJobTemplateTemplateContainersEnvSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateContainersEnv {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateContainersEnv{}
}
if len(a) == 0 {
return []JobTemplateTemplateContainersEnv{}
}
items := make([]JobTemplateTemplateContainersEnv, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateContainersEnv(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateContainersEnv expands an instance of JobTemplateTemplateContainersEnv into a JSON
// request object.
func expandJobTemplateTemplateContainersEnv(c *Client, f *JobTemplateTemplateContainersEnv, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Name; !dcl.IsEmptyValueIndirect(v) {
m["name"] = v
}
if v := f.Value; !dcl.IsEmptyValueIndirect(v) {
m["value"] = v
}
if v, err := expandJobTemplateTemplateContainersEnvValueSource(c, f.ValueSource, res); err != nil {
return nil, fmt.Errorf("error expanding ValueSource into valueSource: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["valueSource"] = v
}
return m, nil
}
// flattenJobTemplateTemplateContainersEnv flattens an instance of JobTemplateTemplateContainersEnv from a JSON
// response object.
func flattenJobTemplateTemplateContainersEnv(c *Client, i interface{}, res *Job) *JobTemplateTemplateContainersEnv {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateContainersEnv{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateContainersEnv
}
r.Name = dcl.FlattenString(m["name"])
r.Value = dcl.FlattenString(m["value"])
r.ValueSource = flattenJobTemplateTemplateContainersEnvValueSource(c, m["valueSource"], res)
return r
}
// expandJobTemplateTemplateContainersEnvValueSourceMap expands the contents of JobTemplateTemplateContainersEnvValueSource into a JSON
// request object.
func expandJobTemplateTemplateContainersEnvValueSourceMap(c *Client, f map[string]JobTemplateTemplateContainersEnvValueSource, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateContainersEnvValueSource(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateContainersEnvValueSourceSlice expands the contents of JobTemplateTemplateContainersEnvValueSource into a JSON
// request object.
func expandJobTemplateTemplateContainersEnvValueSourceSlice(c *Client, f []JobTemplateTemplateContainersEnvValueSource, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateContainersEnvValueSource(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateContainersEnvValueSourceMap flattens the contents of JobTemplateTemplateContainersEnvValueSource from a JSON
// response object.
func flattenJobTemplateTemplateContainersEnvValueSourceMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateContainersEnvValueSource {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateContainersEnvValueSource{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateContainersEnvValueSource{}
}
items := make(map[string]JobTemplateTemplateContainersEnvValueSource)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateContainersEnvValueSource(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateContainersEnvValueSourceSlice flattens the contents of JobTemplateTemplateContainersEnvValueSource from a JSON
// response object.
func flattenJobTemplateTemplateContainersEnvValueSourceSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateContainersEnvValueSource {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateContainersEnvValueSource{}
}
if len(a) == 0 {
return []JobTemplateTemplateContainersEnvValueSource{}
}
items := make([]JobTemplateTemplateContainersEnvValueSource, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateContainersEnvValueSource(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateContainersEnvValueSource expands an instance of JobTemplateTemplateContainersEnvValueSource into a JSON
// request object.
func expandJobTemplateTemplateContainersEnvValueSource(c *Client, f *JobTemplateTemplateContainersEnvValueSource, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v, err := expandJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c, f.SecretKeyRef, res); err != nil {
return nil, fmt.Errorf("error expanding SecretKeyRef into secretKeyRef: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["secretKeyRef"] = v
}
return m, nil
}
// flattenJobTemplateTemplateContainersEnvValueSource flattens an instance of JobTemplateTemplateContainersEnvValueSource from a JSON
// response object.
func flattenJobTemplateTemplateContainersEnvValueSource(c *Client, i interface{}, res *Job) *JobTemplateTemplateContainersEnvValueSource {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateContainersEnvValueSource{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateContainersEnvValueSource
}
r.SecretKeyRef = flattenJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c, m["secretKeyRef"], res)
return r
}
// expandJobTemplateTemplateContainersEnvValueSourceSecretKeyRefMap expands the contents of JobTemplateTemplateContainersEnvValueSourceSecretKeyRef into a JSON
// request object.
func expandJobTemplateTemplateContainersEnvValueSourceSecretKeyRefMap(c *Client, f map[string]JobTemplateTemplateContainersEnvValueSourceSecretKeyRef, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateContainersEnvValueSourceSecretKeyRefSlice expands the contents of JobTemplateTemplateContainersEnvValueSourceSecretKeyRef into a JSON
// request object.
func expandJobTemplateTemplateContainersEnvValueSourceSecretKeyRefSlice(c *Client, f []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateContainersEnvValueSourceSecretKeyRefMap flattens the contents of JobTemplateTemplateContainersEnvValueSourceSecretKeyRef from a JSON
// response object.
func flattenJobTemplateTemplateContainersEnvValueSourceSecretKeyRefMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateContainersEnvValueSourceSecretKeyRef {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateContainersEnvValueSourceSecretKeyRef{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateContainersEnvValueSourceSecretKeyRef{}
}
items := make(map[string]JobTemplateTemplateContainersEnvValueSourceSecretKeyRef)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateContainersEnvValueSourceSecretKeyRefSlice flattens the contents of JobTemplateTemplateContainersEnvValueSourceSecretKeyRef from a JSON
// response object.
func flattenJobTemplateTemplateContainersEnvValueSourceSecretKeyRefSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef{}
}
if len(a) == 0 {
return []JobTemplateTemplateContainersEnvValueSourceSecretKeyRef{}
}
items := make([]JobTemplateTemplateContainersEnvValueSourceSecretKeyRef, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateContainersEnvValueSourceSecretKeyRef expands an instance of JobTemplateTemplateContainersEnvValueSourceSecretKeyRef into a JSON
// request object.
func expandJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c *Client, f *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Secret; !dcl.IsEmptyValueIndirect(v) {
m["secret"] = v
}
if v := f.Version; !dcl.IsEmptyValueIndirect(v) {
m["version"] = v
}
return m, nil
}
// flattenJobTemplateTemplateContainersEnvValueSourceSecretKeyRef flattens an instance of JobTemplateTemplateContainersEnvValueSourceSecretKeyRef from a JSON
// response object.
func flattenJobTemplateTemplateContainersEnvValueSourceSecretKeyRef(c *Client, i interface{}, res *Job) *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateContainersEnvValueSourceSecretKeyRef{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateContainersEnvValueSourceSecretKeyRef
}
r.Secret = dcl.FlattenString(m["secret"])
r.Version = dcl.FlattenString(m["version"])
return r
}
// expandJobTemplateTemplateContainersResourcesMap expands the contents of JobTemplateTemplateContainersResources into a JSON
// request object.
func expandJobTemplateTemplateContainersResourcesMap(c *Client, f map[string]JobTemplateTemplateContainersResources, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateContainersResources(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateContainersResourcesSlice expands the contents of JobTemplateTemplateContainersResources into a JSON
// request object.
func expandJobTemplateTemplateContainersResourcesSlice(c *Client, f []JobTemplateTemplateContainersResources, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateContainersResources(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateContainersResourcesMap flattens the contents of JobTemplateTemplateContainersResources from a JSON
// response object.
func flattenJobTemplateTemplateContainersResourcesMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateContainersResources {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateContainersResources{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateContainersResources{}
}
items := make(map[string]JobTemplateTemplateContainersResources)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateContainersResources(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateContainersResourcesSlice flattens the contents of JobTemplateTemplateContainersResources from a JSON
// response object.
func flattenJobTemplateTemplateContainersResourcesSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateContainersResources {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateContainersResources{}
}
if len(a) == 0 {
return []JobTemplateTemplateContainersResources{}
}
items := make([]JobTemplateTemplateContainersResources, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateContainersResources(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateContainersResources expands an instance of JobTemplateTemplateContainersResources into a JSON
// request object.
func expandJobTemplateTemplateContainersResources(c *Client, f *JobTemplateTemplateContainersResources, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Limits; !dcl.IsEmptyValueIndirect(v) {
m["limits"] = v
}
if v := f.CpuIdle; !dcl.IsEmptyValueIndirect(v) {
m["cpuIdle"] = v
}
return m, nil
}
// flattenJobTemplateTemplateContainersResources flattens an instance of JobTemplateTemplateContainersResources from a JSON
// response object.
func flattenJobTemplateTemplateContainersResources(c *Client, i interface{}, res *Job) *JobTemplateTemplateContainersResources {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateContainersResources{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateContainersResources
}
r.Limits = dcl.FlattenKeyValuePairs(m["limits"])
r.CpuIdle = dcl.FlattenBool(m["cpuIdle"])
return r
}
// expandJobTemplateTemplateContainersPortsMap expands the contents of JobTemplateTemplateContainersPorts into a JSON
// request object.
func expandJobTemplateTemplateContainersPortsMap(c *Client, f map[string]JobTemplateTemplateContainersPorts, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateContainersPorts(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateContainersPortsSlice expands the contents of JobTemplateTemplateContainersPorts into a JSON
// request object.
func expandJobTemplateTemplateContainersPortsSlice(c *Client, f []JobTemplateTemplateContainersPorts, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateContainersPorts(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateContainersPortsMap flattens the contents of JobTemplateTemplateContainersPorts from a JSON
// response object.
func flattenJobTemplateTemplateContainersPortsMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateContainersPorts {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateContainersPorts{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateContainersPorts{}
}
items := make(map[string]JobTemplateTemplateContainersPorts)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateContainersPorts(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateContainersPortsSlice flattens the contents of JobTemplateTemplateContainersPorts from a JSON
// response object.
func flattenJobTemplateTemplateContainersPortsSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateContainersPorts {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateContainersPorts{}
}
if len(a) == 0 {
return []JobTemplateTemplateContainersPorts{}
}
items := make([]JobTemplateTemplateContainersPorts, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateContainersPorts(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateContainersPorts expands an instance of JobTemplateTemplateContainersPorts into a JSON
// request object.
func expandJobTemplateTemplateContainersPorts(c *Client, f *JobTemplateTemplateContainersPorts, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Name; !dcl.IsEmptyValueIndirect(v) {
m["name"] = v
}
if v := f.ContainerPort; !dcl.IsEmptyValueIndirect(v) {
m["containerPort"] = v
}
return m, nil
}
// flattenJobTemplateTemplateContainersPorts flattens an instance of JobTemplateTemplateContainersPorts from a JSON
// response object.
func flattenJobTemplateTemplateContainersPorts(c *Client, i interface{}, res *Job) *JobTemplateTemplateContainersPorts {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateContainersPorts{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateContainersPorts
}
r.Name = dcl.FlattenString(m["name"])
r.ContainerPort = dcl.FlattenInteger(m["containerPort"])
return r
}
// expandJobTemplateTemplateContainersVolumeMountsMap expands the contents of JobTemplateTemplateContainersVolumeMounts into a JSON
// request object.
func expandJobTemplateTemplateContainersVolumeMountsMap(c *Client, f map[string]JobTemplateTemplateContainersVolumeMounts, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateContainersVolumeMounts(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateContainersVolumeMountsSlice expands the contents of JobTemplateTemplateContainersVolumeMounts into a JSON
// request object.
func expandJobTemplateTemplateContainersVolumeMountsSlice(c *Client, f []JobTemplateTemplateContainersVolumeMounts, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateContainersVolumeMounts(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateContainersVolumeMountsMap flattens the contents of JobTemplateTemplateContainersVolumeMounts from a JSON
// response object.
func flattenJobTemplateTemplateContainersVolumeMountsMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateContainersVolumeMounts {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateContainersVolumeMounts{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateContainersVolumeMounts{}
}
items := make(map[string]JobTemplateTemplateContainersVolumeMounts)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateContainersVolumeMounts(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateContainersVolumeMountsSlice flattens the contents of JobTemplateTemplateContainersVolumeMounts from a JSON
// response object.
func flattenJobTemplateTemplateContainersVolumeMountsSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateContainersVolumeMounts {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateContainersVolumeMounts{}
}
if len(a) == 0 {
return []JobTemplateTemplateContainersVolumeMounts{}
}
items := make([]JobTemplateTemplateContainersVolumeMounts, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateContainersVolumeMounts(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateContainersVolumeMounts expands an instance of JobTemplateTemplateContainersVolumeMounts into a JSON
// request object.
func expandJobTemplateTemplateContainersVolumeMounts(c *Client, f *JobTemplateTemplateContainersVolumeMounts, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Name; !dcl.IsEmptyValueIndirect(v) {
m["name"] = v
}
if v := f.MountPath; !dcl.IsEmptyValueIndirect(v) {
m["mountPath"] = v
}
return m, nil
}
// flattenJobTemplateTemplateContainersVolumeMounts flattens an instance of JobTemplateTemplateContainersVolumeMounts from a JSON
// response object.
func flattenJobTemplateTemplateContainersVolumeMounts(c *Client, i interface{}, res *Job) *JobTemplateTemplateContainersVolumeMounts {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateContainersVolumeMounts{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateContainersVolumeMounts
}
r.Name = dcl.FlattenString(m["name"])
r.MountPath = dcl.FlattenString(m["mountPath"])
return r
}
// expandJobTemplateTemplateVolumesMap expands the contents of JobTemplateTemplateVolumes into a JSON
// request object.
func expandJobTemplateTemplateVolumesMap(c *Client, f map[string]JobTemplateTemplateVolumes, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateVolumes(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateVolumesSlice expands the contents of JobTemplateTemplateVolumes into a JSON
// request object.
func expandJobTemplateTemplateVolumesSlice(c *Client, f []JobTemplateTemplateVolumes, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateVolumes(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateVolumesMap flattens the contents of JobTemplateTemplateVolumes from a JSON
// response object.
func flattenJobTemplateTemplateVolumesMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateVolumes {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateVolumes{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateVolumes{}
}
items := make(map[string]JobTemplateTemplateVolumes)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateVolumes(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateVolumesSlice flattens the contents of JobTemplateTemplateVolumes from a JSON
// response object.
func flattenJobTemplateTemplateVolumesSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateVolumes {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateVolumes{}
}
if len(a) == 0 {
return []JobTemplateTemplateVolumes{}
}
items := make([]JobTemplateTemplateVolumes, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateVolumes(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateVolumes expands an instance of JobTemplateTemplateVolumes into a JSON
// request object.
func expandJobTemplateTemplateVolumes(c *Client, f *JobTemplateTemplateVolumes, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Name; !dcl.IsEmptyValueIndirect(v) {
m["name"] = v
}
if v, err := expandJobTemplateTemplateVolumesSecret(c, f.Secret, res); err != nil {
return nil, fmt.Errorf("error expanding Secret into secret: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["secret"] = v
}
if v, err := expandJobTemplateTemplateVolumesCloudSqlInstance(c, f.CloudSqlInstance, res); err != nil {
return nil, fmt.Errorf("error expanding CloudSqlInstance into cloudSqlInstance: %w", err)
} else if !dcl.IsEmptyValueIndirect(v) {
m["cloudSqlInstance"] = v
}
return m, nil
}
// flattenJobTemplateTemplateVolumes flattens an instance of JobTemplateTemplateVolumes from a JSON
// response object.
func flattenJobTemplateTemplateVolumes(c *Client, i interface{}, res *Job) *JobTemplateTemplateVolumes {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateVolumes{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateVolumes
}
r.Name = dcl.FlattenString(m["name"])
r.Secret = flattenJobTemplateTemplateVolumesSecret(c, m["secret"], res)
r.CloudSqlInstance = flattenJobTemplateTemplateVolumesCloudSqlInstance(c, m["cloudSqlInstance"], res)
return r
}
// expandJobTemplateTemplateVolumesSecretMap expands the contents of JobTemplateTemplateVolumesSecret into a JSON
// request object.
func expandJobTemplateTemplateVolumesSecretMap(c *Client, f map[string]JobTemplateTemplateVolumesSecret, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateVolumesSecret(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateVolumesSecretSlice expands the contents of JobTemplateTemplateVolumesSecret into a JSON
// request object.
func expandJobTemplateTemplateVolumesSecretSlice(c *Client, f []JobTemplateTemplateVolumesSecret, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateVolumesSecret(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateVolumesSecretMap flattens the contents of JobTemplateTemplateVolumesSecret from a JSON
// response object.
func flattenJobTemplateTemplateVolumesSecretMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateVolumesSecret {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateVolumesSecret{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateVolumesSecret{}
}
items := make(map[string]JobTemplateTemplateVolumesSecret)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateVolumesSecret(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateVolumesSecretSlice flattens the contents of JobTemplateTemplateVolumesSecret from a JSON
// response object.
func flattenJobTemplateTemplateVolumesSecretSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateVolumesSecret {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateVolumesSecret{}
}
if len(a) == 0 {
return []JobTemplateTemplateVolumesSecret{}
}
items := make([]JobTemplateTemplateVolumesSecret, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateVolumesSecret(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateVolumesSecret expands an instance of JobTemplateTemplateVolumesSecret into a JSON
// request object.
func expandJobTemplateTemplateVolumesSecret(c *Client, f *JobTemplateTemplateVolumesSecret, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Secret; !dcl.IsEmptyValueIndirect(v) {
m["secret"] = v
}
if v, err := expandJobTemplateTemplateVolumesSecretItemsSlice(c, f.Items, res); err != nil {
return nil, fmt.Errorf("error expanding Items into items: %w", err)
} else if v != nil {
m["items"] = v
}
if v := f.DefaultMode; !dcl.IsEmptyValueIndirect(v) {
m["defaultMode"] = v
}
return m, nil
}
// flattenJobTemplateTemplateVolumesSecret flattens an instance of JobTemplateTemplateVolumesSecret from a JSON
// response object.
func flattenJobTemplateTemplateVolumesSecret(c *Client, i interface{}, res *Job) *JobTemplateTemplateVolumesSecret {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateVolumesSecret{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateVolumesSecret
}
r.Secret = dcl.FlattenString(m["secret"])
r.Items = flattenJobTemplateTemplateVolumesSecretItemsSlice(c, m["items"], res)
r.DefaultMode = dcl.FlattenInteger(m["defaultMode"])
return r
}
// expandJobTemplateTemplateVolumesSecretItemsMap expands the contents of JobTemplateTemplateVolumesSecretItems into a JSON
// request object.
func expandJobTemplateTemplateVolumesSecretItemsMap(c *Client, f map[string]JobTemplateTemplateVolumesSecretItems, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateVolumesSecretItems(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateVolumesSecretItemsSlice expands the contents of JobTemplateTemplateVolumesSecretItems into a JSON
// request object.
func expandJobTemplateTemplateVolumesSecretItemsSlice(c *Client, f []JobTemplateTemplateVolumesSecretItems, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateVolumesSecretItems(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateVolumesSecretItemsMap flattens the contents of JobTemplateTemplateVolumesSecretItems from a JSON
// response object.
func flattenJobTemplateTemplateVolumesSecretItemsMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateVolumesSecretItems {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateVolumesSecretItems{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateVolumesSecretItems{}
}
items := make(map[string]JobTemplateTemplateVolumesSecretItems)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateVolumesSecretItems(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateVolumesSecretItemsSlice flattens the contents of JobTemplateTemplateVolumesSecretItems from a JSON
// response object.
func flattenJobTemplateTemplateVolumesSecretItemsSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateVolumesSecretItems {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateVolumesSecretItems{}
}
if len(a) == 0 {
return []JobTemplateTemplateVolumesSecretItems{}
}
items := make([]JobTemplateTemplateVolumesSecretItems, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateVolumesSecretItems(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateVolumesSecretItems expands an instance of JobTemplateTemplateVolumesSecretItems into a JSON
// request object.
func expandJobTemplateTemplateVolumesSecretItems(c *Client, f *JobTemplateTemplateVolumesSecretItems, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Path; !dcl.IsEmptyValueIndirect(v) {
m["path"] = v
}
if v := f.Version; !dcl.IsEmptyValueIndirect(v) {
m["version"] = v
}
if v := f.Mode; !dcl.IsEmptyValueIndirect(v) {
m["mode"] = v
}
return m, nil
}
// flattenJobTemplateTemplateVolumesSecretItems flattens an instance of JobTemplateTemplateVolumesSecretItems from a JSON
// response object.
func flattenJobTemplateTemplateVolumesSecretItems(c *Client, i interface{}, res *Job) *JobTemplateTemplateVolumesSecretItems {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateVolumesSecretItems{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateVolumesSecretItems
}
r.Path = dcl.FlattenString(m["path"])
r.Version = dcl.FlattenString(m["version"])
r.Mode = dcl.FlattenInteger(m["mode"])
return r
}
// expandJobTemplateTemplateVolumesCloudSqlInstanceMap expands the contents of JobTemplateTemplateVolumesCloudSqlInstance into a JSON
// request object.
func expandJobTemplateTemplateVolumesCloudSqlInstanceMap(c *Client, f map[string]JobTemplateTemplateVolumesCloudSqlInstance, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateVolumesCloudSqlInstance(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateVolumesCloudSqlInstanceSlice expands the contents of JobTemplateTemplateVolumesCloudSqlInstance into a JSON
// request object.
func expandJobTemplateTemplateVolumesCloudSqlInstanceSlice(c *Client, f []JobTemplateTemplateVolumesCloudSqlInstance, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateVolumesCloudSqlInstance(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateVolumesCloudSqlInstanceMap flattens the contents of JobTemplateTemplateVolumesCloudSqlInstance from a JSON
// response object.
func flattenJobTemplateTemplateVolumesCloudSqlInstanceMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateVolumesCloudSqlInstance {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateVolumesCloudSqlInstance{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateVolumesCloudSqlInstance{}
}
items := make(map[string]JobTemplateTemplateVolumesCloudSqlInstance)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateVolumesCloudSqlInstance(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateVolumesCloudSqlInstanceSlice flattens the contents of JobTemplateTemplateVolumesCloudSqlInstance from a JSON
// response object.
func flattenJobTemplateTemplateVolumesCloudSqlInstanceSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateVolumesCloudSqlInstance {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateVolumesCloudSqlInstance{}
}
if len(a) == 0 {
return []JobTemplateTemplateVolumesCloudSqlInstance{}
}
items := make([]JobTemplateTemplateVolumesCloudSqlInstance, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateVolumesCloudSqlInstance(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateVolumesCloudSqlInstance expands an instance of JobTemplateTemplateVolumesCloudSqlInstance into a JSON
// request object.
func expandJobTemplateTemplateVolumesCloudSqlInstance(c *Client, f *JobTemplateTemplateVolumesCloudSqlInstance, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Instances; v != nil {
m["instances"] = v
}
return m, nil
}
// flattenJobTemplateTemplateVolumesCloudSqlInstance flattens an instance of JobTemplateTemplateVolumesCloudSqlInstance from a JSON
// response object.
func flattenJobTemplateTemplateVolumesCloudSqlInstance(c *Client, i interface{}, res *Job) *JobTemplateTemplateVolumesCloudSqlInstance {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateVolumesCloudSqlInstance{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateVolumesCloudSqlInstance
}
r.Instances = dcl.FlattenStringSlice(m["instances"])
return r
}
// expandJobTemplateTemplateVPCAccessMap expands the contents of JobTemplateTemplateVPCAccess into a JSON
// request object.
func expandJobTemplateTemplateVPCAccessMap(c *Client, f map[string]JobTemplateTemplateVPCAccess, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTemplateTemplateVPCAccess(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTemplateTemplateVPCAccessSlice expands the contents of JobTemplateTemplateVPCAccess into a JSON
// request object.
func expandJobTemplateTemplateVPCAccessSlice(c *Client, f []JobTemplateTemplateVPCAccess, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTemplateTemplateVPCAccess(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTemplateTemplateVPCAccessMap flattens the contents of JobTemplateTemplateVPCAccess from a JSON
// response object.
func flattenJobTemplateTemplateVPCAccessMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateVPCAccess {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateVPCAccess{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateVPCAccess{}
}
items := make(map[string]JobTemplateTemplateVPCAccess)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateVPCAccess(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTemplateTemplateVPCAccessSlice flattens the contents of JobTemplateTemplateVPCAccess from a JSON
// response object.
func flattenJobTemplateTemplateVPCAccessSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateVPCAccess {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateVPCAccess{}
}
if len(a) == 0 {
return []JobTemplateTemplateVPCAccess{}
}
items := make([]JobTemplateTemplateVPCAccess, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateVPCAccess(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTemplateTemplateVPCAccess expands an instance of JobTemplateTemplateVPCAccess into a JSON
// request object.
func expandJobTemplateTemplateVPCAccess(c *Client, f *JobTemplateTemplateVPCAccess, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Connector; !dcl.IsEmptyValueIndirect(v) {
m["connector"] = v
}
if v := f.Egress; !dcl.IsEmptyValueIndirect(v) {
m["egress"] = v
}
return m, nil
}
// flattenJobTemplateTemplateVPCAccess flattens an instance of JobTemplateTemplateVPCAccess from a JSON
// response object.
func flattenJobTemplateTemplateVPCAccess(c *Client, i interface{}, res *Job) *JobTemplateTemplateVPCAccess {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTemplateTemplateVPCAccess{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTemplateTemplateVPCAccess
}
r.Connector = dcl.FlattenString(m["connector"])
r.Egress = flattenJobTemplateTemplateVPCAccessEgressEnum(m["egress"])
return r
}
// expandJobTerminalConditionMap expands the contents of JobTerminalCondition into a JSON
// request object.
func expandJobTerminalConditionMap(c *Client, f map[string]JobTerminalCondition, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobTerminalCondition(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobTerminalConditionSlice expands the contents of JobTerminalCondition into a JSON
// request object.
func expandJobTerminalConditionSlice(c *Client, f []JobTerminalCondition, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobTerminalCondition(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobTerminalConditionMap flattens the contents of JobTerminalCondition from a JSON
// response object.
func flattenJobTerminalConditionMap(c *Client, i interface{}, res *Job) map[string]JobTerminalCondition {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTerminalCondition{}
}
if len(a) == 0 {
return map[string]JobTerminalCondition{}
}
items := make(map[string]JobTerminalCondition)
for k, item := range a {
items[k] = *flattenJobTerminalCondition(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobTerminalConditionSlice flattens the contents of JobTerminalCondition from a JSON
// response object.
func flattenJobTerminalConditionSlice(c *Client, i interface{}, res *Job) []JobTerminalCondition {
a, ok := i.([]interface{})
if !ok {
return []JobTerminalCondition{}
}
if len(a) == 0 {
return []JobTerminalCondition{}
}
items := make([]JobTerminalCondition, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTerminalCondition(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobTerminalCondition expands an instance of JobTerminalCondition into a JSON
// request object.
func expandJobTerminalCondition(c *Client, f *JobTerminalCondition, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Type; !dcl.IsEmptyValueIndirect(v) {
m["type"] = v
}
if v := f.State; !dcl.IsEmptyValueIndirect(v) {
m["state"] = v
}
if v := f.Message; !dcl.IsEmptyValueIndirect(v) {
m["message"] = v
}
if v := f.LastTransitionTime; !dcl.IsEmptyValueIndirect(v) {
m["lastTransitionTime"] = v
}
if v := f.Severity; !dcl.IsEmptyValueIndirect(v) {
m["severity"] = v
}
if v := f.Reason; !dcl.IsEmptyValueIndirect(v) {
m["reason"] = v
}
if v := f.InternalReason; !dcl.IsEmptyValueIndirect(v) {
m["internalReason"] = v
}
if v := f.DomainMappingReason; !dcl.IsEmptyValueIndirect(v) {
m["domainMappingReason"] = v
}
if v := f.RevisionReason; !dcl.IsEmptyValueIndirect(v) {
m["revisionReason"] = v
}
if v := f.ExecutionReason; !dcl.IsEmptyValueIndirect(v) {
m["executionReason"] = v
}
return m, nil
}
// flattenJobTerminalCondition flattens an instance of JobTerminalCondition from a JSON
// response object.
func flattenJobTerminalCondition(c *Client, i interface{}, res *Job) *JobTerminalCondition {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobTerminalCondition{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobTerminalCondition
}
r.Type = dcl.FlattenString(m["type"])
r.State = flattenJobTerminalConditionStateEnum(m["state"])
r.Message = dcl.FlattenString(m["message"])
r.LastTransitionTime = dcl.FlattenString(m["lastTransitionTime"])
r.Severity = flattenJobTerminalConditionSeverityEnum(m["severity"])
r.Reason = flattenJobTerminalConditionReasonEnum(m["reason"])
r.InternalReason = flattenJobTerminalConditionInternalReasonEnum(m["internalReason"])
r.DomainMappingReason = flattenJobTerminalConditionDomainMappingReasonEnum(m["domainMappingReason"])
r.RevisionReason = flattenJobTerminalConditionRevisionReasonEnum(m["revisionReason"])
r.ExecutionReason = flattenJobTerminalConditionExecutionReasonEnum(m["executionReason"])
return r
}
// expandJobConditionsMap expands the contents of JobConditions into a JSON
// request object.
func expandJobConditionsMap(c *Client, f map[string]JobConditions, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobConditions(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobConditionsSlice expands the contents of JobConditions into a JSON
// request object.
func expandJobConditionsSlice(c *Client, f []JobConditions, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobConditions(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobConditionsMap flattens the contents of JobConditions from a JSON
// response object.
func flattenJobConditionsMap(c *Client, i interface{}, res *Job) map[string]JobConditions {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobConditions{}
}
if len(a) == 0 {
return map[string]JobConditions{}
}
items := make(map[string]JobConditions)
for k, item := range a {
items[k] = *flattenJobConditions(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobConditionsSlice flattens the contents of JobConditions from a JSON
// response object.
func flattenJobConditionsSlice(c *Client, i interface{}, res *Job) []JobConditions {
a, ok := i.([]interface{})
if !ok {
return []JobConditions{}
}
if len(a) == 0 {
return []JobConditions{}
}
items := make([]JobConditions, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobConditions(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobConditions expands an instance of JobConditions into a JSON
// request object.
func expandJobConditions(c *Client, f *JobConditions, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Type; !dcl.IsEmptyValueIndirect(v) {
m["type"] = v
}
if v := f.State; !dcl.IsEmptyValueIndirect(v) {
m["state"] = v
}
if v := f.Message; !dcl.IsEmptyValueIndirect(v) {
m["message"] = v
}
if v := f.LastTransitionTime; !dcl.IsEmptyValueIndirect(v) {
m["lastTransitionTime"] = v
}
if v := f.Severity; !dcl.IsEmptyValueIndirect(v) {
m["severity"] = v
}
if v := f.Reason; !dcl.IsEmptyValueIndirect(v) {
m["reason"] = v
}
if v := f.RevisionReason; !dcl.IsEmptyValueIndirect(v) {
m["revisionReason"] = v
}
if v := f.ExecutionReason; !dcl.IsEmptyValueIndirect(v) {
m["executionReason"] = v
}
return m, nil
}
// flattenJobConditions flattens an instance of JobConditions from a JSON
// response object.
func flattenJobConditions(c *Client, i interface{}, res *Job) *JobConditions {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobConditions{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobConditions
}
r.Type = dcl.FlattenString(m["type"])
r.State = flattenJobConditionsStateEnum(m["state"])
r.Message = dcl.FlattenString(m["message"])
r.LastTransitionTime = dcl.FlattenString(m["lastTransitionTime"])
r.Severity = flattenJobConditionsSeverityEnum(m["severity"])
r.Reason = flattenJobConditionsReasonEnum(m["reason"])
r.RevisionReason = flattenJobConditionsRevisionReasonEnum(m["revisionReason"])
r.ExecutionReason = flattenJobConditionsExecutionReasonEnum(m["executionReason"])
return r
}
// expandJobLatestSucceededExecutionMap expands the contents of JobLatestSucceededExecution into a JSON
// request object.
func expandJobLatestSucceededExecutionMap(c *Client, f map[string]JobLatestSucceededExecution, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobLatestSucceededExecution(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobLatestSucceededExecutionSlice expands the contents of JobLatestSucceededExecution into a JSON
// request object.
func expandJobLatestSucceededExecutionSlice(c *Client, f []JobLatestSucceededExecution, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobLatestSucceededExecution(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobLatestSucceededExecutionMap flattens the contents of JobLatestSucceededExecution from a JSON
// response object.
func flattenJobLatestSucceededExecutionMap(c *Client, i interface{}, res *Job) map[string]JobLatestSucceededExecution {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobLatestSucceededExecution{}
}
if len(a) == 0 {
return map[string]JobLatestSucceededExecution{}
}
items := make(map[string]JobLatestSucceededExecution)
for k, item := range a {
items[k] = *flattenJobLatestSucceededExecution(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobLatestSucceededExecutionSlice flattens the contents of JobLatestSucceededExecution from a JSON
// response object.
func flattenJobLatestSucceededExecutionSlice(c *Client, i interface{}, res *Job) []JobLatestSucceededExecution {
a, ok := i.([]interface{})
if !ok {
return []JobLatestSucceededExecution{}
}
if len(a) == 0 {
return []JobLatestSucceededExecution{}
}
items := make([]JobLatestSucceededExecution, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobLatestSucceededExecution(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobLatestSucceededExecution expands an instance of JobLatestSucceededExecution into a JSON
// request object.
func expandJobLatestSucceededExecution(c *Client, f *JobLatestSucceededExecution, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Name; !dcl.IsEmptyValueIndirect(v) {
m["name"] = v
}
if v := f.CreateTime; !dcl.IsEmptyValueIndirect(v) {
m["createTime"] = v
}
return m, nil
}
// flattenJobLatestSucceededExecution flattens an instance of JobLatestSucceededExecution from a JSON
// response object.
func flattenJobLatestSucceededExecution(c *Client, i interface{}, res *Job) *JobLatestSucceededExecution {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobLatestSucceededExecution{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobLatestSucceededExecution
}
r.Name = dcl.FlattenString(m["name"])
r.CreateTime = dcl.FlattenString(m["createTime"])
return r
}
// expandJobLatestCreatedExecutionMap expands the contents of JobLatestCreatedExecution into a JSON
// request object.
func expandJobLatestCreatedExecutionMap(c *Client, f map[string]JobLatestCreatedExecution, res *Job) (map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := make(map[string]interface{})
for k, item := range f {
i, err := expandJobLatestCreatedExecution(c, &item, res)
if err != nil {
return nil, err
}
if i != nil {
items[k] = i
}
}
return items, nil
}
// expandJobLatestCreatedExecutionSlice expands the contents of JobLatestCreatedExecution into a JSON
// request object.
func expandJobLatestCreatedExecutionSlice(c *Client, f []JobLatestCreatedExecution, res *Job) ([]map[string]interface{}, error) {
if f == nil {
return nil, nil
}
items := []map[string]interface{}{}
for _, item := range f {
i, err := expandJobLatestCreatedExecution(c, &item, res)
if err != nil {
return nil, err
}
items = append(items, i)
}
return items, nil
}
// flattenJobLatestCreatedExecutionMap flattens the contents of JobLatestCreatedExecution from a JSON
// response object.
func flattenJobLatestCreatedExecutionMap(c *Client, i interface{}, res *Job) map[string]JobLatestCreatedExecution {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobLatestCreatedExecution{}
}
if len(a) == 0 {
return map[string]JobLatestCreatedExecution{}
}
items := make(map[string]JobLatestCreatedExecution)
for k, item := range a {
items[k] = *flattenJobLatestCreatedExecution(c, item.(map[string]interface{}), res)
}
return items
}
// flattenJobLatestCreatedExecutionSlice flattens the contents of JobLatestCreatedExecution from a JSON
// response object.
func flattenJobLatestCreatedExecutionSlice(c *Client, i interface{}, res *Job) []JobLatestCreatedExecution {
a, ok := i.([]interface{})
if !ok {
return []JobLatestCreatedExecution{}
}
if len(a) == 0 {
return []JobLatestCreatedExecution{}
}
items := make([]JobLatestCreatedExecution, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobLatestCreatedExecution(c, item.(map[string]interface{}), res))
}
return items
}
// expandJobLatestCreatedExecution expands an instance of JobLatestCreatedExecution into a JSON
// request object.
func expandJobLatestCreatedExecution(c *Client, f *JobLatestCreatedExecution, res *Job) (map[string]interface{}, error) {
if dcl.IsEmptyValueIndirect(f) {
return nil, nil
}
m := make(map[string]interface{})
if v := f.Name; !dcl.IsEmptyValueIndirect(v) {
m["name"] = v
}
if v := f.CreateTime; !dcl.IsEmptyValueIndirect(v) {
m["createTime"] = v
}
return m, nil
}
// flattenJobLatestCreatedExecution flattens an instance of JobLatestCreatedExecution from a JSON
// response object.
func flattenJobLatestCreatedExecution(c *Client, i interface{}, res *Job) *JobLatestCreatedExecution {
m, ok := i.(map[string]interface{})
if !ok {
return nil
}
r := &JobLatestCreatedExecution{}
if dcl.IsEmptyValueIndirect(i) {
return EmptyJobLatestCreatedExecution
}
r.Name = dcl.FlattenString(m["name"])
r.CreateTime = dcl.FlattenString(m["createTime"])
return r
}
// flattenJobLaunchStageEnumMap flattens the contents of JobLaunchStageEnum from a JSON
// response object.
func flattenJobLaunchStageEnumMap(c *Client, i interface{}, res *Job) map[string]JobLaunchStageEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobLaunchStageEnum{}
}
if len(a) == 0 {
return map[string]JobLaunchStageEnum{}
}
items := make(map[string]JobLaunchStageEnum)
for k, item := range a {
items[k] = *flattenJobLaunchStageEnum(item.(interface{}))
}
return items
}
// flattenJobLaunchStageEnumSlice flattens the contents of JobLaunchStageEnum from a JSON
// response object.
func flattenJobLaunchStageEnumSlice(c *Client, i interface{}, res *Job) []JobLaunchStageEnum {
a, ok := i.([]interface{})
if !ok {
return []JobLaunchStageEnum{}
}
if len(a) == 0 {
return []JobLaunchStageEnum{}
}
items := make([]JobLaunchStageEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobLaunchStageEnum(item.(interface{})))
}
return items
}
// flattenJobLaunchStageEnum asserts that an interface is a string, and returns a
// pointer to a *JobLaunchStageEnum with the same value as that string.
func flattenJobLaunchStageEnum(i interface{}) *JobLaunchStageEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobLaunchStageEnumRef(s)
}
// flattenJobTemplateTemplateExecutionEnvironmentEnumMap flattens the contents of JobTemplateTemplateExecutionEnvironmentEnum from a JSON
// response object.
func flattenJobTemplateTemplateExecutionEnvironmentEnumMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateExecutionEnvironmentEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateExecutionEnvironmentEnum{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateExecutionEnvironmentEnum{}
}
items := make(map[string]JobTemplateTemplateExecutionEnvironmentEnum)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateExecutionEnvironmentEnum(item.(interface{}))
}
return items
}
// flattenJobTemplateTemplateExecutionEnvironmentEnumSlice flattens the contents of JobTemplateTemplateExecutionEnvironmentEnum from a JSON
// response object.
func flattenJobTemplateTemplateExecutionEnvironmentEnumSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateExecutionEnvironmentEnum {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateExecutionEnvironmentEnum{}
}
if len(a) == 0 {
return []JobTemplateTemplateExecutionEnvironmentEnum{}
}
items := make([]JobTemplateTemplateExecutionEnvironmentEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateExecutionEnvironmentEnum(item.(interface{})))
}
return items
}
// flattenJobTemplateTemplateExecutionEnvironmentEnum asserts that an interface is a string, and returns a
// pointer to a *JobTemplateTemplateExecutionEnvironmentEnum with the same value as that string.
func flattenJobTemplateTemplateExecutionEnvironmentEnum(i interface{}) *JobTemplateTemplateExecutionEnvironmentEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobTemplateTemplateExecutionEnvironmentEnumRef(s)
}
// flattenJobTemplateTemplateVPCAccessEgressEnumMap flattens the contents of JobTemplateTemplateVPCAccessEgressEnum from a JSON
// response object.
func flattenJobTemplateTemplateVPCAccessEgressEnumMap(c *Client, i interface{}, res *Job) map[string]JobTemplateTemplateVPCAccessEgressEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTemplateTemplateVPCAccessEgressEnum{}
}
if len(a) == 0 {
return map[string]JobTemplateTemplateVPCAccessEgressEnum{}
}
items := make(map[string]JobTemplateTemplateVPCAccessEgressEnum)
for k, item := range a {
items[k] = *flattenJobTemplateTemplateVPCAccessEgressEnum(item.(interface{}))
}
return items
}
// flattenJobTemplateTemplateVPCAccessEgressEnumSlice flattens the contents of JobTemplateTemplateVPCAccessEgressEnum from a JSON
// response object.
func flattenJobTemplateTemplateVPCAccessEgressEnumSlice(c *Client, i interface{}, res *Job) []JobTemplateTemplateVPCAccessEgressEnum {
a, ok := i.([]interface{})
if !ok {
return []JobTemplateTemplateVPCAccessEgressEnum{}
}
if len(a) == 0 {
return []JobTemplateTemplateVPCAccessEgressEnum{}
}
items := make([]JobTemplateTemplateVPCAccessEgressEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTemplateTemplateVPCAccessEgressEnum(item.(interface{})))
}
return items
}
// flattenJobTemplateTemplateVPCAccessEgressEnum asserts that an interface is a string, and returns a
// pointer to a *JobTemplateTemplateVPCAccessEgressEnum with the same value as that string.
func flattenJobTemplateTemplateVPCAccessEgressEnum(i interface{}) *JobTemplateTemplateVPCAccessEgressEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobTemplateTemplateVPCAccessEgressEnumRef(s)
}
// flattenJobTerminalConditionStateEnumMap flattens the contents of JobTerminalConditionStateEnum from a JSON
// response object.
func flattenJobTerminalConditionStateEnumMap(c *Client, i interface{}, res *Job) map[string]JobTerminalConditionStateEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTerminalConditionStateEnum{}
}
if len(a) == 0 {
return map[string]JobTerminalConditionStateEnum{}
}
items := make(map[string]JobTerminalConditionStateEnum)
for k, item := range a {
items[k] = *flattenJobTerminalConditionStateEnum(item.(interface{}))
}
return items
}
// flattenJobTerminalConditionStateEnumSlice flattens the contents of JobTerminalConditionStateEnum from a JSON
// response object.
func flattenJobTerminalConditionStateEnumSlice(c *Client, i interface{}, res *Job) []JobTerminalConditionStateEnum {
a, ok := i.([]interface{})
if !ok {
return []JobTerminalConditionStateEnum{}
}
if len(a) == 0 {
return []JobTerminalConditionStateEnum{}
}
items := make([]JobTerminalConditionStateEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTerminalConditionStateEnum(item.(interface{})))
}
return items
}
// flattenJobTerminalConditionStateEnum asserts that an interface is a string, and returns a
// pointer to a *JobTerminalConditionStateEnum with the same value as that string.
func flattenJobTerminalConditionStateEnum(i interface{}) *JobTerminalConditionStateEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobTerminalConditionStateEnumRef(s)
}
// flattenJobTerminalConditionSeverityEnumMap flattens the contents of JobTerminalConditionSeverityEnum from a JSON
// response object.
func flattenJobTerminalConditionSeverityEnumMap(c *Client, i interface{}, res *Job) map[string]JobTerminalConditionSeverityEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTerminalConditionSeverityEnum{}
}
if len(a) == 0 {
return map[string]JobTerminalConditionSeverityEnum{}
}
items := make(map[string]JobTerminalConditionSeverityEnum)
for k, item := range a {
items[k] = *flattenJobTerminalConditionSeverityEnum(item.(interface{}))
}
return items
}
// flattenJobTerminalConditionSeverityEnumSlice flattens the contents of JobTerminalConditionSeverityEnum from a JSON
// response object.
func flattenJobTerminalConditionSeverityEnumSlice(c *Client, i interface{}, res *Job) []JobTerminalConditionSeverityEnum {
a, ok := i.([]interface{})
if !ok {
return []JobTerminalConditionSeverityEnum{}
}
if len(a) == 0 {
return []JobTerminalConditionSeverityEnum{}
}
items := make([]JobTerminalConditionSeverityEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTerminalConditionSeverityEnum(item.(interface{})))
}
return items
}
// flattenJobTerminalConditionSeverityEnum asserts that an interface is a string, and returns a
// pointer to a *JobTerminalConditionSeverityEnum with the same value as that string.
func flattenJobTerminalConditionSeverityEnum(i interface{}) *JobTerminalConditionSeverityEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobTerminalConditionSeverityEnumRef(s)
}
// flattenJobTerminalConditionReasonEnumMap flattens the contents of JobTerminalConditionReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionReasonEnumMap(c *Client, i interface{}, res *Job) map[string]JobTerminalConditionReasonEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTerminalConditionReasonEnum{}
}
if len(a) == 0 {
return map[string]JobTerminalConditionReasonEnum{}
}
items := make(map[string]JobTerminalConditionReasonEnum)
for k, item := range a {
items[k] = *flattenJobTerminalConditionReasonEnum(item.(interface{}))
}
return items
}
// flattenJobTerminalConditionReasonEnumSlice flattens the contents of JobTerminalConditionReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionReasonEnumSlice(c *Client, i interface{}, res *Job) []JobTerminalConditionReasonEnum {
a, ok := i.([]interface{})
if !ok {
return []JobTerminalConditionReasonEnum{}
}
if len(a) == 0 {
return []JobTerminalConditionReasonEnum{}
}
items := make([]JobTerminalConditionReasonEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTerminalConditionReasonEnum(item.(interface{})))
}
return items
}
// flattenJobTerminalConditionReasonEnum asserts that an interface is a string, and returns a
// pointer to a *JobTerminalConditionReasonEnum with the same value as that string.
func flattenJobTerminalConditionReasonEnum(i interface{}) *JobTerminalConditionReasonEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobTerminalConditionReasonEnumRef(s)
}
// flattenJobTerminalConditionInternalReasonEnumMap flattens the contents of JobTerminalConditionInternalReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionInternalReasonEnumMap(c *Client, i interface{}, res *Job) map[string]JobTerminalConditionInternalReasonEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTerminalConditionInternalReasonEnum{}
}
if len(a) == 0 {
return map[string]JobTerminalConditionInternalReasonEnum{}
}
items := make(map[string]JobTerminalConditionInternalReasonEnum)
for k, item := range a {
items[k] = *flattenJobTerminalConditionInternalReasonEnum(item.(interface{}))
}
return items
}
// flattenJobTerminalConditionInternalReasonEnumSlice flattens the contents of JobTerminalConditionInternalReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionInternalReasonEnumSlice(c *Client, i interface{}, res *Job) []JobTerminalConditionInternalReasonEnum {
a, ok := i.([]interface{})
if !ok {
return []JobTerminalConditionInternalReasonEnum{}
}
if len(a) == 0 {
return []JobTerminalConditionInternalReasonEnum{}
}
items := make([]JobTerminalConditionInternalReasonEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTerminalConditionInternalReasonEnum(item.(interface{})))
}
return items
}
// flattenJobTerminalConditionInternalReasonEnum asserts that an interface is a string, and returns a
// pointer to a *JobTerminalConditionInternalReasonEnum with the same value as that string.
func flattenJobTerminalConditionInternalReasonEnum(i interface{}) *JobTerminalConditionInternalReasonEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobTerminalConditionInternalReasonEnumRef(s)
}
// flattenJobTerminalConditionDomainMappingReasonEnumMap flattens the contents of JobTerminalConditionDomainMappingReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionDomainMappingReasonEnumMap(c *Client, i interface{}, res *Job) map[string]JobTerminalConditionDomainMappingReasonEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTerminalConditionDomainMappingReasonEnum{}
}
if len(a) == 0 {
return map[string]JobTerminalConditionDomainMappingReasonEnum{}
}
items := make(map[string]JobTerminalConditionDomainMappingReasonEnum)
for k, item := range a {
items[k] = *flattenJobTerminalConditionDomainMappingReasonEnum(item.(interface{}))
}
return items
}
// flattenJobTerminalConditionDomainMappingReasonEnumSlice flattens the contents of JobTerminalConditionDomainMappingReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionDomainMappingReasonEnumSlice(c *Client, i interface{}, res *Job) []JobTerminalConditionDomainMappingReasonEnum {
a, ok := i.([]interface{})
if !ok {
return []JobTerminalConditionDomainMappingReasonEnum{}
}
if len(a) == 0 {
return []JobTerminalConditionDomainMappingReasonEnum{}
}
items := make([]JobTerminalConditionDomainMappingReasonEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTerminalConditionDomainMappingReasonEnum(item.(interface{})))
}
return items
}
// flattenJobTerminalConditionDomainMappingReasonEnum asserts that an interface is a string, and returns a
// pointer to a *JobTerminalConditionDomainMappingReasonEnum with the same value as that string.
func flattenJobTerminalConditionDomainMappingReasonEnum(i interface{}) *JobTerminalConditionDomainMappingReasonEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobTerminalConditionDomainMappingReasonEnumRef(s)
}
// flattenJobTerminalConditionRevisionReasonEnumMap flattens the contents of JobTerminalConditionRevisionReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionRevisionReasonEnumMap(c *Client, i interface{}, res *Job) map[string]JobTerminalConditionRevisionReasonEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTerminalConditionRevisionReasonEnum{}
}
if len(a) == 0 {
return map[string]JobTerminalConditionRevisionReasonEnum{}
}
items := make(map[string]JobTerminalConditionRevisionReasonEnum)
for k, item := range a {
items[k] = *flattenJobTerminalConditionRevisionReasonEnum(item.(interface{}))
}
return items
}
// flattenJobTerminalConditionRevisionReasonEnumSlice flattens the contents of JobTerminalConditionRevisionReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionRevisionReasonEnumSlice(c *Client, i interface{}, res *Job) []JobTerminalConditionRevisionReasonEnum {
a, ok := i.([]interface{})
if !ok {
return []JobTerminalConditionRevisionReasonEnum{}
}
if len(a) == 0 {
return []JobTerminalConditionRevisionReasonEnum{}
}
items := make([]JobTerminalConditionRevisionReasonEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTerminalConditionRevisionReasonEnum(item.(interface{})))
}
return items
}
// flattenJobTerminalConditionRevisionReasonEnum asserts that an interface is a string, and returns a
// pointer to a *JobTerminalConditionRevisionReasonEnum with the same value as that string.
func flattenJobTerminalConditionRevisionReasonEnum(i interface{}) *JobTerminalConditionRevisionReasonEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobTerminalConditionRevisionReasonEnumRef(s)
}
// flattenJobTerminalConditionExecutionReasonEnumMap flattens the contents of JobTerminalConditionExecutionReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionExecutionReasonEnumMap(c *Client, i interface{}, res *Job) map[string]JobTerminalConditionExecutionReasonEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobTerminalConditionExecutionReasonEnum{}
}
if len(a) == 0 {
return map[string]JobTerminalConditionExecutionReasonEnum{}
}
items := make(map[string]JobTerminalConditionExecutionReasonEnum)
for k, item := range a {
items[k] = *flattenJobTerminalConditionExecutionReasonEnum(item.(interface{}))
}
return items
}
// flattenJobTerminalConditionExecutionReasonEnumSlice flattens the contents of JobTerminalConditionExecutionReasonEnum from a JSON
// response object.
func flattenJobTerminalConditionExecutionReasonEnumSlice(c *Client, i interface{}, res *Job) []JobTerminalConditionExecutionReasonEnum {
a, ok := i.([]interface{})
if !ok {
return []JobTerminalConditionExecutionReasonEnum{}
}
if len(a) == 0 {
return []JobTerminalConditionExecutionReasonEnum{}
}
items := make([]JobTerminalConditionExecutionReasonEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobTerminalConditionExecutionReasonEnum(item.(interface{})))
}
return items
}
// flattenJobTerminalConditionExecutionReasonEnum asserts that an interface is a string, and returns a
// pointer to a *JobTerminalConditionExecutionReasonEnum with the same value as that string.
func flattenJobTerminalConditionExecutionReasonEnum(i interface{}) *JobTerminalConditionExecutionReasonEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobTerminalConditionExecutionReasonEnumRef(s)
}
// flattenJobConditionsStateEnumMap flattens the contents of JobConditionsStateEnum from a JSON
// response object.
func flattenJobConditionsStateEnumMap(c *Client, i interface{}, res *Job) map[string]JobConditionsStateEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobConditionsStateEnum{}
}
if len(a) == 0 {
return map[string]JobConditionsStateEnum{}
}
items := make(map[string]JobConditionsStateEnum)
for k, item := range a {
items[k] = *flattenJobConditionsStateEnum(item.(interface{}))
}
return items
}
// flattenJobConditionsStateEnumSlice flattens the contents of JobConditionsStateEnum from a JSON
// response object.
func flattenJobConditionsStateEnumSlice(c *Client, i interface{}, res *Job) []JobConditionsStateEnum {
a, ok := i.([]interface{})
if !ok {
return []JobConditionsStateEnum{}
}
if len(a) == 0 {
return []JobConditionsStateEnum{}
}
items := make([]JobConditionsStateEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobConditionsStateEnum(item.(interface{})))
}
return items
}
// flattenJobConditionsStateEnum asserts that an interface is a string, and returns a
// pointer to a *JobConditionsStateEnum with the same value as that string.
func flattenJobConditionsStateEnum(i interface{}) *JobConditionsStateEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobConditionsStateEnumRef(s)
}
// flattenJobConditionsSeverityEnumMap flattens the contents of JobConditionsSeverityEnum from a JSON
// response object.
func flattenJobConditionsSeverityEnumMap(c *Client, i interface{}, res *Job) map[string]JobConditionsSeverityEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobConditionsSeverityEnum{}
}
if len(a) == 0 {
return map[string]JobConditionsSeverityEnum{}
}
items := make(map[string]JobConditionsSeverityEnum)
for k, item := range a {
items[k] = *flattenJobConditionsSeverityEnum(item.(interface{}))
}
return items
}
// flattenJobConditionsSeverityEnumSlice flattens the contents of JobConditionsSeverityEnum from a JSON
// response object.
func flattenJobConditionsSeverityEnumSlice(c *Client, i interface{}, res *Job) []JobConditionsSeverityEnum {
a, ok := i.([]interface{})
if !ok {
return []JobConditionsSeverityEnum{}
}
if len(a) == 0 {
return []JobConditionsSeverityEnum{}
}
items := make([]JobConditionsSeverityEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobConditionsSeverityEnum(item.(interface{})))
}
return items
}
// flattenJobConditionsSeverityEnum asserts that an interface is a string, and returns a
// pointer to a *JobConditionsSeverityEnum with the same value as that string.
func flattenJobConditionsSeverityEnum(i interface{}) *JobConditionsSeverityEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobConditionsSeverityEnumRef(s)
}
// flattenJobConditionsReasonEnumMap flattens the contents of JobConditionsReasonEnum from a JSON
// response object.
func flattenJobConditionsReasonEnumMap(c *Client, i interface{}, res *Job) map[string]JobConditionsReasonEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobConditionsReasonEnum{}
}
if len(a) == 0 {
return map[string]JobConditionsReasonEnum{}
}
items := make(map[string]JobConditionsReasonEnum)
for k, item := range a {
items[k] = *flattenJobConditionsReasonEnum(item.(interface{}))
}
return items
}
// flattenJobConditionsReasonEnumSlice flattens the contents of JobConditionsReasonEnum from a JSON
// response object.
func flattenJobConditionsReasonEnumSlice(c *Client, i interface{}, res *Job) []JobConditionsReasonEnum {
a, ok := i.([]interface{})
if !ok {
return []JobConditionsReasonEnum{}
}
if len(a) == 0 {
return []JobConditionsReasonEnum{}
}
items := make([]JobConditionsReasonEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobConditionsReasonEnum(item.(interface{})))
}
return items
}
// flattenJobConditionsReasonEnum asserts that an interface is a string, and returns a
// pointer to a *JobConditionsReasonEnum with the same value as that string.
func flattenJobConditionsReasonEnum(i interface{}) *JobConditionsReasonEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobConditionsReasonEnumRef(s)
}
// flattenJobConditionsRevisionReasonEnumMap flattens the contents of JobConditionsRevisionReasonEnum from a JSON
// response object.
func flattenJobConditionsRevisionReasonEnumMap(c *Client, i interface{}, res *Job) map[string]JobConditionsRevisionReasonEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobConditionsRevisionReasonEnum{}
}
if len(a) == 0 {
return map[string]JobConditionsRevisionReasonEnum{}
}
items := make(map[string]JobConditionsRevisionReasonEnum)
for k, item := range a {
items[k] = *flattenJobConditionsRevisionReasonEnum(item.(interface{}))
}
return items
}
// flattenJobConditionsRevisionReasonEnumSlice flattens the contents of JobConditionsRevisionReasonEnum from a JSON
// response object.
func flattenJobConditionsRevisionReasonEnumSlice(c *Client, i interface{}, res *Job) []JobConditionsRevisionReasonEnum {
a, ok := i.([]interface{})
if !ok {
return []JobConditionsRevisionReasonEnum{}
}
if len(a) == 0 {
return []JobConditionsRevisionReasonEnum{}
}
items := make([]JobConditionsRevisionReasonEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobConditionsRevisionReasonEnum(item.(interface{})))
}
return items
}
// flattenJobConditionsRevisionReasonEnum asserts that an interface is a string, and returns a
// pointer to a *JobConditionsRevisionReasonEnum with the same value as that string.
func flattenJobConditionsRevisionReasonEnum(i interface{}) *JobConditionsRevisionReasonEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobConditionsRevisionReasonEnumRef(s)
}
// flattenJobConditionsExecutionReasonEnumMap flattens the contents of JobConditionsExecutionReasonEnum from a JSON
// response object.
func flattenJobConditionsExecutionReasonEnumMap(c *Client, i interface{}, res *Job) map[string]JobConditionsExecutionReasonEnum {
a, ok := i.(map[string]interface{})
if !ok {
return map[string]JobConditionsExecutionReasonEnum{}
}
if len(a) == 0 {
return map[string]JobConditionsExecutionReasonEnum{}
}
items := make(map[string]JobConditionsExecutionReasonEnum)
for k, item := range a {
items[k] = *flattenJobConditionsExecutionReasonEnum(item.(interface{}))
}
return items
}
// flattenJobConditionsExecutionReasonEnumSlice flattens the contents of JobConditionsExecutionReasonEnum from a JSON
// response object.
func flattenJobConditionsExecutionReasonEnumSlice(c *Client, i interface{}, res *Job) []JobConditionsExecutionReasonEnum {
a, ok := i.([]interface{})
if !ok {
return []JobConditionsExecutionReasonEnum{}
}
if len(a) == 0 {
return []JobConditionsExecutionReasonEnum{}
}
items := make([]JobConditionsExecutionReasonEnum, 0, len(a))
for _, item := range a {
items = append(items, *flattenJobConditionsExecutionReasonEnum(item.(interface{})))
}
return items
}
// flattenJobConditionsExecutionReasonEnum asserts that an interface is a string, and returns a
// pointer to a *JobConditionsExecutionReasonEnum with the same value as that string.
func flattenJobConditionsExecutionReasonEnum(i interface{}) *JobConditionsExecutionReasonEnum {
s, ok := i.(string)
if !ok {
return nil
}
return JobConditionsExecutionReasonEnumRef(s)
}
// This function returns a matcher that checks whether a serialized resource matches this resource
// in its parameters (as defined by the fields in a Get, which definitionally define resource
// identity). This is useful in extracting the element from a List call.
func (r *Job) matcher(c *Client) func([]byte) bool {
return func(b []byte) bool {
cr, err := unmarshalJob(b, c, r)
if err != nil {
c.Config.Logger.Warning("failed to unmarshal provided resource in matcher.")
return false
}
nr := r.urlNormalized()
ncr := cr.urlNormalized()
c.Config.Logger.Infof("looking for %v\nin %v", nr, ncr)
if nr.Project == nil && ncr.Project == nil {
c.Config.Logger.Info("Both Project fields null - considering equal.")
} else if nr.Project == nil || ncr.Project == nil {
c.Config.Logger.Info("Only one Project field is null - considering unequal.")
return false
} else if *nr.Project != *ncr.Project {
return false
}
if nr.Location == nil && ncr.Location == nil {
c.Config.Logger.Info("Both Location fields null - considering equal.")
} else if nr.Location == nil || ncr.Location == nil {
c.Config.Logger.Info("Only one Location field is null - considering unequal.")
return false
} else if *nr.Location != *ncr.Location {
return false
}
if nr.Name == nil && ncr.Name == nil {
c.Config.Logger.Info("Both Name fields null - considering equal.")
} else if nr.Name == nil || ncr.Name == nil {
c.Config.Logger.Info("Only one Name field is null - considering unequal.")
return false
} else if *nr.Name != *ncr.Name {
return false
}
return true
}
}
type jobDiff struct {
// The diff should include one or the other of RequiresRecreate or UpdateOp.
RequiresRecreate bool
UpdateOp jobApiOperation
FieldName string // used for error logging
}
func convertFieldDiffsToJobDiffs(config *dcl.Config, fds []*dcl.FieldDiff, opts []dcl.ApplyOption) ([]jobDiff, error) {
opNamesToFieldDiffs := make(map[string][]*dcl.FieldDiff)
// Map each operation name to the field diffs associated with it.
for _, fd := range fds {
for _, ro := range fd.ResultingOperation {
if fieldDiffs, ok := opNamesToFieldDiffs[ro]; ok {
fieldDiffs = append(fieldDiffs, fd)
opNamesToFieldDiffs[ro] = fieldDiffs
} else {
config.Logger.Infof("%s required due to diff: %v", ro, fd)
opNamesToFieldDiffs[ro] = []*dcl.FieldDiff{fd}
}
}
}
var diffs []jobDiff
// For each operation name, create a jobDiff which contains the operation.
for opName, fieldDiffs := range opNamesToFieldDiffs {
// Use the first field diff's field name for logging required recreate error.
diff := jobDiff{FieldName: fieldDiffs[0].FieldName}
if opName == "Recreate" {
diff.RequiresRecreate = true
} else {
apiOp, err := convertOpNameToJobApiOperation(opName, fieldDiffs, opts...)
if err != nil {
return diffs, err
}
diff.UpdateOp = apiOp
}
diffs = append(diffs, diff)
}
return diffs, nil
}
func convertOpNameToJobApiOperation(opName string, fieldDiffs []*dcl.FieldDiff, opts ...dcl.ApplyOption) (jobApiOperation, error) {
switch opName {
case "updateJobUpdateJobOperation":
return &updateJobUpdateJobOperation{FieldDiffs: fieldDiffs}, nil
default:
return nil, fmt.Errorf("no such operation with name: %v", opName)
}
}
func extractJobFields(r *Job) error {
vBinaryAuthorization := r.BinaryAuthorization
if vBinaryAuthorization == nil {
// note: explicitly not the empty object.
vBinaryAuthorization = &JobBinaryAuthorization{}
}
if err := extractJobBinaryAuthorizationFields(r, vBinaryAuthorization); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vBinaryAuthorization) {
r.BinaryAuthorization = vBinaryAuthorization
}
vTemplate := r.Template
if vTemplate == nil {
// note: explicitly not the empty object.
vTemplate = &JobTemplate{}
}
if err := extractJobTemplateFields(r, vTemplate); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vTemplate) {
r.Template = vTemplate
}
vTerminalCondition := r.TerminalCondition
if vTerminalCondition == nil {
// note: explicitly not the empty object.
vTerminalCondition = &JobTerminalCondition{}
}
if err := extractJobTerminalConditionFields(r, vTerminalCondition); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vTerminalCondition) {
r.TerminalCondition = vTerminalCondition
}
vLatestSucceededExecution := r.LatestSucceededExecution
if vLatestSucceededExecution == nil {
// note: explicitly not the empty object.
vLatestSucceededExecution = &JobLatestSucceededExecution{}
}
if err := extractJobLatestSucceededExecutionFields(r, vLatestSucceededExecution); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vLatestSucceededExecution) {
r.LatestSucceededExecution = vLatestSucceededExecution
}
vLatestCreatedExecution := r.LatestCreatedExecution
if vLatestCreatedExecution == nil {
// note: explicitly not the empty object.
vLatestCreatedExecution = &JobLatestCreatedExecution{}
}
if err := extractJobLatestCreatedExecutionFields(r, vLatestCreatedExecution); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vLatestCreatedExecution) {
r.LatestCreatedExecution = vLatestCreatedExecution
}
return nil
}
func extractJobBinaryAuthorizationFields(r *Job, o *JobBinaryAuthorization) error {
return nil
}
func extractJobTemplateFields(r *Job, o *JobTemplate) error {
vTemplate := o.Template
if vTemplate == nil {
// note: explicitly not the empty object.
vTemplate = &JobTemplateTemplate{}
}
if err := extractJobTemplateTemplateFields(r, vTemplate); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vTemplate) {
o.Template = vTemplate
}
return nil
}
func extractJobTemplateTemplateFields(r *Job, o *JobTemplateTemplate) error {
vVPCAccess := o.VPCAccess
if vVPCAccess == nil {
// note: explicitly not the empty object.
vVPCAccess = &JobTemplateTemplateVPCAccess{}
}
if err := extractJobTemplateTemplateVPCAccessFields(r, vVPCAccess); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vVPCAccess) {
o.VPCAccess = vVPCAccess
}
return nil
}
func extractJobTemplateTemplateContainersFields(r *Job, o *JobTemplateTemplateContainers) error {
vResources := o.Resources
if vResources == nil {
// note: explicitly not the empty object.
vResources = &JobTemplateTemplateContainersResources{}
}
if err := extractJobTemplateTemplateContainersResourcesFields(r, vResources); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vResources) {
o.Resources = vResources
}
return nil
}
func extractJobTemplateTemplateContainersEnvFields(r *Job, o *JobTemplateTemplateContainersEnv) error {
vValueSource := o.ValueSource
if vValueSource == nil {
// note: explicitly not the empty object.
vValueSource = &JobTemplateTemplateContainersEnvValueSource{}
}
if err := extractJobTemplateTemplateContainersEnvValueSourceFields(r, vValueSource); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vValueSource) {
o.ValueSource = vValueSource
}
return nil
}
func extractJobTemplateTemplateContainersEnvValueSourceFields(r *Job, o *JobTemplateTemplateContainersEnvValueSource) error {
vSecretKeyRef := o.SecretKeyRef
if vSecretKeyRef == nil {
// note: explicitly not the empty object.
vSecretKeyRef = &JobTemplateTemplateContainersEnvValueSourceSecretKeyRef{}
}
if err := extractJobTemplateTemplateContainersEnvValueSourceSecretKeyRefFields(r, vSecretKeyRef); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vSecretKeyRef) {
o.SecretKeyRef = vSecretKeyRef
}
return nil
}
func extractJobTemplateTemplateContainersEnvValueSourceSecretKeyRefFields(r *Job, o *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef) error {
return nil
}
func extractJobTemplateTemplateContainersResourcesFields(r *Job, o *JobTemplateTemplateContainersResources) error {
return nil
}
func extractJobTemplateTemplateContainersPortsFields(r *Job, o *JobTemplateTemplateContainersPorts) error {
return nil
}
func extractJobTemplateTemplateContainersVolumeMountsFields(r *Job, o *JobTemplateTemplateContainersVolumeMounts) error {
return nil
}
func extractJobTemplateTemplateVolumesFields(r *Job, o *JobTemplateTemplateVolumes) error {
vSecret := o.Secret
if vSecret == nil {
// note: explicitly not the empty object.
vSecret = &JobTemplateTemplateVolumesSecret{}
}
if err := extractJobTemplateTemplateVolumesSecretFields(r, vSecret); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vSecret) {
o.Secret = vSecret
}
vCloudSqlInstance := o.CloudSqlInstance
if vCloudSqlInstance == nil {
// note: explicitly not the empty object.
vCloudSqlInstance = &JobTemplateTemplateVolumesCloudSqlInstance{}
}
if err := extractJobTemplateTemplateVolumesCloudSqlInstanceFields(r, vCloudSqlInstance); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vCloudSqlInstance) {
o.CloudSqlInstance = vCloudSqlInstance
}
return nil
}
func extractJobTemplateTemplateVolumesSecretFields(r *Job, o *JobTemplateTemplateVolumesSecret) error {
return nil
}
func extractJobTemplateTemplateVolumesSecretItemsFields(r *Job, o *JobTemplateTemplateVolumesSecretItems) error {
return nil
}
func extractJobTemplateTemplateVolumesCloudSqlInstanceFields(r *Job, o *JobTemplateTemplateVolumesCloudSqlInstance) error {
return nil
}
func extractJobTemplateTemplateVPCAccessFields(r *Job, o *JobTemplateTemplateVPCAccess) error {
return nil
}
func extractJobTerminalConditionFields(r *Job, o *JobTerminalCondition) error {
return nil
}
func extractJobConditionsFields(r *Job, o *JobConditions) error {
return nil
}
func extractJobLatestSucceededExecutionFields(r *Job, o *JobLatestSucceededExecution) error {
return nil
}
func extractJobLatestCreatedExecutionFields(r *Job, o *JobLatestCreatedExecution) error {
return nil
}
func postReadExtractJobFields(r *Job) error {
vBinaryAuthorization := r.BinaryAuthorization
if vBinaryAuthorization == nil {
// note: explicitly not the empty object.
vBinaryAuthorization = &JobBinaryAuthorization{}
}
if err := postReadExtractJobBinaryAuthorizationFields(r, vBinaryAuthorization); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vBinaryAuthorization) {
r.BinaryAuthorization = vBinaryAuthorization
}
vTemplate := r.Template
if vTemplate == nil {
// note: explicitly not the empty object.
vTemplate = &JobTemplate{}
}
if err := postReadExtractJobTemplateFields(r, vTemplate); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vTemplate) {
r.Template = vTemplate
}
vTerminalCondition := r.TerminalCondition
if vTerminalCondition == nil {
// note: explicitly not the empty object.
vTerminalCondition = &JobTerminalCondition{}
}
if err := postReadExtractJobTerminalConditionFields(r, vTerminalCondition); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vTerminalCondition) {
r.TerminalCondition = vTerminalCondition
}
vLatestSucceededExecution := r.LatestSucceededExecution
if vLatestSucceededExecution == nil {
// note: explicitly not the empty object.
vLatestSucceededExecution = &JobLatestSucceededExecution{}
}
if err := postReadExtractJobLatestSucceededExecutionFields(r, vLatestSucceededExecution); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vLatestSucceededExecution) {
r.LatestSucceededExecution = vLatestSucceededExecution
}
vLatestCreatedExecution := r.LatestCreatedExecution
if vLatestCreatedExecution == nil {
// note: explicitly not the empty object.
vLatestCreatedExecution = &JobLatestCreatedExecution{}
}
if err := postReadExtractJobLatestCreatedExecutionFields(r, vLatestCreatedExecution); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vLatestCreatedExecution) {
r.LatestCreatedExecution = vLatestCreatedExecution
}
return nil
}
func postReadExtractJobBinaryAuthorizationFields(r *Job, o *JobBinaryAuthorization) error {
return nil
}
func postReadExtractJobTemplateFields(r *Job, o *JobTemplate) error {
vTemplate := o.Template
if vTemplate == nil {
// note: explicitly not the empty object.
vTemplate = &JobTemplateTemplate{}
}
if err := extractJobTemplateTemplateFields(r, vTemplate); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vTemplate) {
o.Template = vTemplate
}
return nil
}
func postReadExtractJobTemplateTemplateFields(r *Job, o *JobTemplateTemplate) error {
vVPCAccess := o.VPCAccess
if vVPCAccess == nil {
// note: explicitly not the empty object.
vVPCAccess = &JobTemplateTemplateVPCAccess{}
}
if err := extractJobTemplateTemplateVPCAccessFields(r, vVPCAccess); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vVPCAccess) {
o.VPCAccess = vVPCAccess
}
return nil
}
func postReadExtractJobTemplateTemplateContainersFields(r *Job, o *JobTemplateTemplateContainers) error {
vResources := o.Resources
if vResources == nil {
// note: explicitly not the empty object.
vResources = &JobTemplateTemplateContainersResources{}
}
if err := extractJobTemplateTemplateContainersResourcesFields(r, vResources); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vResources) {
o.Resources = vResources
}
return nil
}
func postReadExtractJobTemplateTemplateContainersEnvFields(r *Job, o *JobTemplateTemplateContainersEnv) error {
vValueSource := o.ValueSource
if vValueSource == nil {
// note: explicitly not the empty object.
vValueSource = &JobTemplateTemplateContainersEnvValueSource{}
}
if err := extractJobTemplateTemplateContainersEnvValueSourceFields(r, vValueSource); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vValueSource) {
o.ValueSource = vValueSource
}
return nil
}
func postReadExtractJobTemplateTemplateContainersEnvValueSourceFields(r *Job, o *JobTemplateTemplateContainersEnvValueSource) error {
vSecretKeyRef := o.SecretKeyRef
if vSecretKeyRef == nil {
// note: explicitly not the empty object.
vSecretKeyRef = &JobTemplateTemplateContainersEnvValueSourceSecretKeyRef{}
}
if err := extractJobTemplateTemplateContainersEnvValueSourceSecretKeyRefFields(r, vSecretKeyRef); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vSecretKeyRef) {
o.SecretKeyRef = vSecretKeyRef
}
return nil
}
func postReadExtractJobTemplateTemplateContainersEnvValueSourceSecretKeyRefFields(r *Job, o *JobTemplateTemplateContainersEnvValueSourceSecretKeyRef) error {
return nil
}
func postReadExtractJobTemplateTemplateContainersResourcesFields(r *Job, o *JobTemplateTemplateContainersResources) error {
return nil
}
func postReadExtractJobTemplateTemplateContainersPortsFields(r *Job, o *JobTemplateTemplateContainersPorts) error {
return nil
}
func postReadExtractJobTemplateTemplateContainersVolumeMountsFields(r *Job, o *JobTemplateTemplateContainersVolumeMounts) error {
return nil
}
func postReadExtractJobTemplateTemplateVolumesFields(r *Job, o *JobTemplateTemplateVolumes) error {
vSecret := o.Secret
if vSecret == nil {
// note: explicitly not the empty object.
vSecret = &JobTemplateTemplateVolumesSecret{}
}
if err := extractJobTemplateTemplateVolumesSecretFields(r, vSecret); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vSecret) {
o.Secret = vSecret
}
vCloudSqlInstance := o.CloudSqlInstance
if vCloudSqlInstance == nil {
// note: explicitly not the empty object.
vCloudSqlInstance = &JobTemplateTemplateVolumesCloudSqlInstance{}
}
if err := extractJobTemplateTemplateVolumesCloudSqlInstanceFields(r, vCloudSqlInstance); err != nil {
return err
}
if !dcl.IsEmptyValueIndirect(vCloudSqlInstance) {
o.CloudSqlInstance = vCloudSqlInstance
}
return nil
}
func postReadExtractJobTemplateTemplateVolumesSecretFields(r *Job, o *JobTemplateTemplateVolumesSecret) error {
return nil
}
func postReadExtractJobTemplateTemplateVolumesSecretItemsFields(r *Job, o *JobTemplateTemplateVolumesSecretItems) error {
return nil
}
func postReadExtractJobTemplateTemplateVolumesCloudSqlInstanceFields(r *Job, o *JobTemplateTemplateVolumesCloudSqlInstance) error {
return nil
}
func postReadExtractJobTemplateTemplateVPCAccessFields(r *Job, o *JobTemplateTemplateVPCAccess) error {
return nil
}
func postReadExtractJobTerminalConditionFields(r *Job, o *JobTerminalCondition) error {
return nil
}
func postReadExtractJobConditionsFields(r *Job, o *JobConditions) error {
return nil
}
func postReadExtractJobLatestSucceededExecutionFields(r *Job, o *JobLatestSucceededExecution) error {
return nil
}
func postReadExtractJobLatestCreatedExecutionFields(r *Job, o *JobLatestCreatedExecution) error {
return nil
}
|
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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 main
import (
"reflect"
"testing"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/extensions"
)
type metricsRegistryMock struct {
readyNodes float64
unreadyNodes float64
deploymentReplicas map[string]float64
deploymentReplicasAvailable map[string]float64
containerRestarts map[string]float64
}
func (mr *metricsRegistryMock) setReadyNodes(count float64) {
mr.readyNodes = count
}
func (mr *metricsRegistryMock) setUnreadyNodes(count float64) {
mr.unreadyNodes = count
}
func (mr *metricsRegistryMock) setDeploymentReplicas(name, namespace string, count float64) {
if mr.deploymentReplicas == nil {
mr.deploymentReplicas = map[string]float64{}
}
mr.deploymentReplicas[name+"-"+namespace] = count
}
func (mr *metricsRegistryMock) setDeploymentReplicasAvailable(name, namespace string, count float64) {
if mr.deploymentReplicasAvailable == nil {
mr.deploymentReplicasAvailable = map[string]float64{}
}
mr.deploymentReplicasAvailable[name+"-"+namespace] = count
}
func (mr *metricsRegistryMock) setContainerRestarts(name, namespace, podName string, count float64) {
if mr.containerRestarts == nil {
mr.containerRestarts = map[string]float64{}
}
mr.containerRestarts[name+"-"+podName+"-"+namespace] = count
}
func getNode(condition api.ConditionStatus) api.Node {
return api.Node{
Status: api.NodeStatus{
Conditions: []api.NodeCondition{
{
Type: api.NodeReady,
Status: condition,
},
},
},
}
}
func getDeployment(name, namespace string, replicas, replicasAvailable int) extensions.Deployment {
return extensions.Deployment{
ObjectMeta: api.ObjectMeta{
Name: name,
Namespace: namespace,
},
Status: extensions.DeploymentStatus{
Replicas: int32(replicas),
AvailableReplicas: int32(replicasAvailable),
},
}
}
// This pod will have two containers - you can confiure the restart count on both.
func getPod(name, namespace string, containerStatuses []api.ContainerStatus) *api.Pod {
return &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Namespace: namespace,
},
Status: api.PodStatus{
ContainerStatuses: containerStatuses,
},
}
}
func getContainerStatus(name string, restartCount int) api.ContainerStatus {
return api.ContainerStatus{
Name: name,
RestartCount: int32(restartCount),
}
}
func TestRegisterNodeMetrics(t *testing.T) {
cases := []struct {
desc string
nodes []api.Node
registry *metricsRegistryMock
}{
{
desc: "three ready nodes, one unready node, one unknown node",
nodes: []api.Node{
getNode(api.ConditionTrue),
getNode(api.ConditionTrue),
getNode(api.ConditionTrue),
getNode(api.ConditionFalse),
getNode(api.ConditionUnknown),
},
registry: &metricsRegistryMock{
readyNodes: 3,
unreadyNodes: 2,
},
},
}
for _, c := range cases {
r := &metricsRegistryMock{}
registerNodeMetrics(r, c.nodes)
if !reflect.DeepEqual(r, c.registry) {
t.Errorf("error in case \"%s\": actual %v does not equal expected %v", c.desc, r, c.registry)
}
}
}
func TestRegisterDeploymentMetrics(t *testing.T) {
cases := []struct {
dpls []extensions.Deployment
registry *metricsRegistryMock
}{
{
dpls: []extensions.Deployment{
getDeployment("dpl1", "ns1", 2, 0),
getDeployment("dpl2", "ns2", 1, 1),
getDeployment("dpl3", "ns3", 0, 2),
},
registry: &metricsRegistryMock{
deploymentReplicas: map[string]float64{
"dpl1-ns1": 2,
"dpl2-ns2": 1,
"dpl3-ns3": 0,
},
deploymentReplicasAvailable: map[string]float64{
"dpl1-ns1": 0,
"dpl2-ns2": 1,
"dpl3-ns3": 2,
},
},
},
}
for i, c := range cases {
r := &metricsRegistryMock{}
registerDeploymentMetrics(r, c.dpls)
if !reflect.DeepEqual(r, c.registry) {
t.Errorf("error in case %d: actual %v does not equal expected %v", i, r, c.registry)
}
}
}
func TestRegisterPodMetrics(t *testing.T) {
cases := []struct {
pods []*api.Pod
registry *metricsRegistryMock
}{
{
pods: []*api.Pod{
getPod("pod1", "ns1", []api.ContainerStatus{
getContainerStatus("container1", 0),
}),
getPod("pod2", "ns2", []api.ContainerStatus{
getContainerStatus("container1", 1),
}),
getPod("pod3", "ns3", []api.ContainerStatus{
getContainerStatus("container1", 0),
getContainerStatus("container2", 2),
}),
},
registry: &metricsRegistryMock{
containerRestarts: map[string]float64{
"container1-pod1-ns1": 0,
"container1-pod2-ns2": 1,
"container1-pod3-ns3": 0,
"container2-pod3-ns3": 2,
},
},
},
}
for i, c := range cases {
r := &metricsRegistryMock{}
registerPodMetrics(r, c.pods)
if !reflect.DeepEqual(r, c.registry) {
t.Errorf("error in case %d: actual %v does not equal expected %v", i, r, c.registry)
}
}
}
|
package cmd
import (
"fmt"
"io/ioutil"
"log"
"os"
"github.com/spf13/cobra"
)
func RootCmd() *cobra.Command {
cmds := &cobra.Command{
Use: "suich",
Short: "Root command for switch context in k8s config",
Long: "",
PreRun: func(cmd *cobra.Command, args []string) {
ok, err := cmd.Flags().GetBool("debug")
fmt.Println(ok, err)
if ok, err := cmd.Flags().GetBool("debug"); err == nil &&ok {
fmt.Println("-------------")
log.SetOutput(os.Stdout)
}
},
Run: func(cmd *cobra.Command, args []string) {
log.Println("------")
// cmd.Execute()
cmd.Help()
},
}
log.SetFlags(0)
log.SetOutput(ioutil.Discard)
cmds.Flags().Bool("debug", false, "turn on debug mode")
cmds.AddCommand(SwitchCmd())
cmds.AddCommand(ChangeKubectl())
cmds.AddCommand(RemoveContext())
cmds.AddCommand(PortForward())
cmds.AddCommand(GCPConfigSwitch())
cmds.AddCommand(SuichNamespaceCMD())
cmds.AddCommand(GetLogsCmd())
cmds.AddCommand(patch())
return cmds
}
|
// An example package using Go-as-if-it-had-parametric-polymorphism,
// with an "iter" package in the standard library, following an
// already idiomatic Go iteration pattern.
//
// The feature is entirely imaginary, but I've tried to write
// the code to fit as much within Go's existing idioms as possible.
//
// Generics questions that this code does not attempt to resolve:
// - What semantics are there for equality of values
// with parametric types?
// - what happens if you convert a value with parametric type
// to an interface?
//
// Points given for pointing out syntax errors, logical inconsistencies
// or language-feature implementation roadtraps.
package main
import (
"os"
"log"
"iter"
)
func main() {
f, err := os.Open("/etc/passwd")
if err != nil {
log.Fatal(err)
}
r := strings.NewReader("light blue\nfaded khaki\n")
iter0 := iter.BufioScanner(bufio.NewScanner(f))
iter1 := iter.Slice<string>{"one", "two"}
both := iter.Sequence(iter0, iter1)
prefixed := iter.Map(both, func(s string) string {
return "x: " + s
})
foo, err := iter.Gather(prefixed)
if err != nil {
log.Fatal(err)
}
// foo is []string{"x: light blue", "x: faded khaki", "x: one", "x: two"}
fmt.Printf("%v\n", foo)
}
///////////////////////////////////////////////////////////
// The iter package implements a general iterator interface type, Iter,
// and some functions that operate on values of that type.
package iter
// Iter represents an iterable collection of values.
type Iter<T> interface {
// Next advances the iterator to the next value, which will then
// be available through the Value method. It returns
// false when the iteration stops, either by reaching the end
// or an error. After Scan returns false, the Err method
// will return any error that occurred during iteration..
Next() bool
// Value returns the most recent value generated by a call to Next.
// It may be called any number of times between calls to Next.
// If called after Next has returned false, it returns the zero value.
Value() T
// Err returns the first error encountered.
Err() error
// Close closes the iterator and frees any associated resources.
Close() error
}
// Gather iterates through all the items in iter
// and returns them as a slice.
func Gather<T>(iter Iter<T>) ([]T, error) {
var slice []T
while iter.Next() {
slice = append(slice, iter.Value()
}
return slice, iter.Err()
}
// Identity returns the identity function for
// a given type.
func Identity<T>() func(T) T {
return func(t T) T {
return t
}
}
// Map returns an iterator that produces
// a value f(x) for every value in the given iterator.
// Any non-nil error returned from the underlying iterator
// will be transformed by the given err function.
func Map<S, T>(
iter Iter<S>,
transformError func(error) error,
f func(S) T,
) Iter<T> {
if transformError == nil {
transformError = Identity<error>()
}
return &mapping{
Iter: iter,
f: f,
}
}
// mapping implements the iterator returned by Map.
// Note the embedding of a type name with
// a parametric type parameter.
// When checking for interface type compatibility,
// methods must be compatible. So if S==T
// then mapping will automatically
// implement Iter<S> but not Iter<T>.
// It will implement interface {
// Next() bool
// Close() error
// Err() error
// }
type mapping<S, T> struct {
Iter<S>
f func(S) T
transformError func(error) error
}
func (m *mapping) Value() bool {
return m.iter.Next()
}
func (m *mapping) Err() error {
return m.transformError
}
func BufioScanner(r *bufio.Scanner) Iter<string> {
return bufioScanner(r)
}
type bufioScanner struct {
r *bufio.Scanner
}
func (b bufioScanner) Next() bool {
return b.r.Scan()
}
func (b bufioScanner) Err() error {
return b.r.Err()
}
func (b bufioScanner) Value() string {
return b.r.Text()
}
func (b bufioScanner) Close() error {
return nil
}
type slice<T> struct {
first bool
values []T
}
// Slice implements Iter on a slice.
// The values are traversed from beginning to end.
func NewSlice<T>(values []T) Iter<T> {
return &slice{
first: true,
values: values,
}
}
func (s *slice) Next() bool {
if s.first {
s.first = false
} else {
s.values = s.elems[1:]
}
return len(s.values) > 0
}
func (s *slice) Err() error {
return nil
}
func (s *slice) Close() error {
return nil
}
func (s *slice) Value() s.T {
return s.values[0]
}
// Sequence returns an iterator that iterates
// through each of the given iterators in turn.
// The first error will terminate any remaining
// iterators. All are closed in turn when or before
// the returned iterator is closed.
//
func Sequence(iters ...Iter<T>) Iter<T> {
return &sequence{
iters: iters,
}
}
type sequence struct<T> {
iters []Iter<T>
err error
}
func (s *sequence) Next() bool {
for len(s.iters) > 0 {
iter := s.iters[0]
if iter.Next() {
return true
}
if err := iter.Err(); err != nil {
s.err = err
s.Close()
s.iters = nil
return false
}
s.iters = s.iters[1:]
}
return false
}
func (s *sequence) Err() error {
if s.err != nil {
return s.err
}
if len(s.iters) > 0 {
s.err = s.iters[0].Err()
return s.err
}
return nil
}
func (s *sequence) Value() s.T {
if len(s.iters) == 0 {
// Note the use of "zero" here, as a more
// general form of "nil" that is a valid
// zero value for any type, not just pointers.
return zero
}
return s.iters[0].Value()
}
func (s *sequence) Close() error {
var closeErr error
for len(s.iters) > 0 {
if err := s.iters[0].Close(); err != nil && closeErr == nil {
closeErr = err
}
s.iters = s.iters[1:]
}
return closeErr
}
// Concurrent returns a channel reading the
// results of al the given iterators running
// concurrently.
func Concurrent<T>(iters ...Iter<T>) chan T {
c := make(chan T)
go func() {
var wg sync.WaitGroup
for _, iter := range iters {
iter := iter
go func() {
defer wg.Done()
defer iter.Close()
for iter.Next() {
c <- iter.Value()
}
}()
}
wg.Wait()
close(c)
}()
return c
}
|
// This deals with calls coming from Second Life or OpenSimulator.
// it's essentially a RESTful thingy
package main
import (
"crypto/md5"
"database/sql"
"encoding/hex"
"fmt"
// "github.com/cznic/ql"
"net/http"
// "strconv"
"strings"
)
// GetMD5Hash takes a string which is to be encoded using MD5 and returns a string with the hex-encoded MD5 sum.
// Got this from https://gist.github.com/sergiotapia/8263278
func GetMD5Hash(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
// registerObject saves a HTTP URL for a single rental object, making it persistent.
// POST parameters:
// permURL: a permanent URL from llHTTPServer
// signature: to make spoofing harder
// timestamp: in-world timestamp retrieved with llGetTimestamp()
// request: currently only delete (to remove entry from database when the rental object is deleted)
func registerObject(w http.ResponseWriter, r *http.Request) {
// get all parameters in array
err := r.ParseForm()
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Extracting parameters failed:", err)
if r.Header.Get("X-Secondlife-Object-Key") == "" {
// Log.Debugf("Got '%s'\n", r.Header["X-Secondlife-Object-Key"])
logErrHTTP(w, http.StatusForbidden, funcName() + ": Only in-world requests allowed.")
return
}
if r.Form.Get("signature") == "" {
logErrHTTP(w, http.StatusForbidden, funcName() + ": Signature not found")
return
}
signature := GetMD5Hash(r.Header.Get("X-Secondlife-Object-Key") + r.Form.Get("timestamp") + ":" + LSLSignaturePIN)
if signature != r.Form.Get("signature") {
logErrHTTP(w, http.StatusForbidden, funcName() + ": Signature does not match - hack attempt?")
return
}
// open database connection and see if we can update the inventory for this object
db, err := sql.Open(PDO_Prefix, GoSLRentalDSN)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Connect failed:", err)
defer db.Close()
if r.Form.Get("permURL") != "" { // object registration
// Try to update first; if it fails, insert record.
// This is sadly the only way to do it with the SQL that ql supports, it should however work on any database
tx, err := db.Begin()
checkErrPanicHTTP(w, http.StatusServiceUnavailable, "Transaction begin failed: %s\n", err)
defer tx.Commit()
stmt, err := tx.Prepare("UPDATE Objects SET Name=?2, OwnerKey=?3, OwnerName=?4, PermURL=?5, Location=?6, Position=?7, Rotation=?8, Velocity=?9, LastUpdate=?10) WHERE UUID=?1");
checkErrPanicHTTP(w, http.StatusServiceUnavailable, "Update prepare failed: %s\n", err)
defer stmt.Close()
_, err = stmt.Exec(
r.Header.Get("X-Secondlife-Object-Key"),
r.Header.Get("X-Secondlife-Object-Name"),
r.Header.Get("X-Secondlife-Owner-Key"),
r.Header.Get("X-Secondlife-Owner-Name"),
r.Form.Get("permURL"),
r.Header.Get("X-Secondlife-Region"),
strings.Trim(r.Header.Get("X-Secondlife-Local-Position"), "<>()"),
strings.Trim(r.Header.Get("X-Secondlife-Local-Rotation"), "<>()"),
strings.Trim(r.Header.Get("X-Secondlife-Local-Velocity"), "<>()"),
r.Form.Get("timestamp"),
)
if (err != nil) {
// Update failed, means it's a new object, insert it instead
stmt, err := tx.Prepare("INSERT INTO Objects (UUID, Name, OwnerKey, OwnerName, PermURL, Location, Position, Rotation, Velocity, LastUpdate) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)");
checkErrPanicHTTP(w, http.StatusServiceUnavailable, "Insert prepare failed: %s\n", err)
_, err = stmt.Exec(
r.Header.Get("X-Secondlife-Object-Key"),
r.Header.Get("X-Secondlife-Object-Name"),
r.Header.Get("X-Secondlife-Owner-Key"),
r.Header.Get("X-Secondlife-Owner-Name"),
r.Form.Get("permURL"),
r.Header.Get("X-Secondlife-Region"),
strings.Trim(r.Header.Get("X-Secondlife-Local-Position"), "<>()"),
strings.Trim(r.Header.Get("X-Secondlife-Local-Rotation"), "<>()"),
strings.Trim(r.Header.Get("X-Secondlife-Local-Velocity"), "<>()"),
r.Form.Get("timestamp"),
)
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Insert exec failed:", err)
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-type", "text/plain; charset=utf-8")
replyText := "'" + r.Header.Get("X-Secondlife-Object-Name") +
"' successfully updated object '" +
r.Header.Get("X-Secondlife-Owner-Name") + "' (" +
r.Header.Get("X-Secondlife-Owner-Key") + ")."
fmt.Fprint(w, replyText)
// log.Printf(replyText) // debug
} else if r.Form.Get("request") == "delete" { // other requests, currently only deletion
stmt, err := db.Prepare("DELETE FROM Objects WHERE UUID=?")
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Delete object prepare failed:", err)
defer stmt.Close()
_, err = stmt.Exec(r.Header.Get("X-Secondlife-Object-Key"))
checkErrPanicHTTP(w, http.StatusServiceUnavailable, funcName() + ": Delete object exec failed:", err)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "'%s' (%s) successfully deleted.", r.Header.Get("X-Secondlife-Object-Name"), r.Header.Get("X-Secondlife-Object-Key"))
return
}
} |
package checklist
import (
"errors"
"fmt"
"os"
"strings"
"github.com/PuerkitoBio/goquery"
"net/http"
"image"
_ "image/jpeg"
_ "image/png"
"strconv"
)
const (
httpProto = "http://"
httpsProto = "https://"
propPairSeparator = "="
themeName = "white"
embedWidth = "500"
)
// CheckFile reads HTML file containing playlist from loadPath,
// checks it for inconsistencies and fixes them, if there are any.
// Then, function saves fixed file to savePath.
func CheckFile(loadPath, savePath string) (report []string, err error) {
doc, err := parseFile(loadPath)
if err != nil {
return nil, err
}
embed, err := getEmbed(doc)
if err != nil {
return nil, err
}
report = make([]string, 0, 5)
fixSrcAttribute(embed, &report)
fixWidthAttribute(embed, &report)
fixHeightAttribute(embed, &report)
writeDocumentToFile(savePath, doc)
return report, nil
}
func parseFile(path string) (*goquery.Document, error) {
file, err := os.Open(path)
if err != nil {
return nil, errors.New(fmt.Sprintf("Unable to open file '%s' (%s)", path, err))
}
defer file.Close()
doc, err := goquery.NewDocumentFromReader(file)
if err != nil {
return nil, errors.New(fmt.Sprintf("Invalid file '%s', can't parse (%s)", path, err))
}
return doc, nil
}
func writeDocumentToFile(path string, doc *goquery.Document) error {
file, err := os.Create(path)
if err != nil {
return errors.New(fmt.Sprintf("Unable to create file '%s' (%s)", path, err))
}
defer file.Close()
file.WriteString(doc.Text())
html, err := goquery.OuterHtml(doc.Find("embed"))
if err != nil {
return errors.New(fmt.Sprintf("Unexpected error: %s", err))
}
// We need this hack because for whatever reason goquery tends to escape special characters,
// when setting an attribute of element.
html = strings.Replace(html, "&", "&", -1)
file.WriteString(html)
return nil
}
func getEmbed(doc *goquery.Document) (*goquery.Selection, error) {
embedNode := doc.Find("embed")
switch embedNode.Size() {
case 0:
return nil, errors.New("Required <embed> element not found")
case 1:
return embedNode, nil
default:
return nil, errors.New("Found multiple <embed> elements")
}
}
func fixSrcAttribute(embedNode *goquery.Selection, finalReport *[]string) error {
srcAttr, isSrcExist := embedNode.Attr("src")
if !isSrcExist {
return errors.New("Required 'src' attribute of <embed> element not found")
}
srcSplitted := strings.Split(srcAttr, "?")
fixedSrc := fixPlaylistUrl(srcSplitted[0], finalReport) + "?" + fixPlaylistProperties(srcSplitted[1], finalReport)
embedNode.SetAttr("src", fixedSrc)
return nil
}
func fixPlaylistUrl(url string, report *[]string) string {
if strings.HasPrefix(url, httpProto) {
*report = append(*report, "Malformed playlist URL - http:// used instead of https://")
return strings.Replace(url, httpProto, httpsProto, 1)
}
return url
}
func fixPlaylistProperties(rawProps string, report *[]string) string {
srcPropPairs := strings.Split(rawProps, "&")
fixedProps := make([]string, len(srcPropPairs))
for i, prop := range srcPropPairs {
propPair := strings.Split(prop, propPairSeparator)
switch propPair[0] {
case "theme":
if propPair[1] != themeName {
*report = append(*report, "Invalid playlist theme ('theme' property) - should be white")
propPair[1] = themeName
prop = strings.Join(propPair, propPairSeparator)
}
case "w":
if propPair[1] != embedWidth {
*report = append(*report, "Invalid width value ('w' property) - should be 500")
propPair[1] = embedWidth
prop = strings.Join(propPair, propPairSeparator)
}
case "withart":
if strings.HasPrefix(propPair[1], httpProto) {
*report = append(*report, "Malformed cover art URL ('withart' property)- http:// used instead of https://")
prop = strings.Replace(prop, httpProto, httpsProto, 1)
}
}
fixedProps[i] = prop
}
return strings.Join(fixedProps, "&")
}
func fixWidthAttribute(embedNode *goquery.Selection, report *[]string) error {
widthAttr, isWidthExist := embedNode.Attr("width")
if !isWidthExist {
return errors.New("Required 'width' attribute of <embed> element not found")
}
if widthAttr != embedWidth {
*report = append(*report, "Invalid width value - should be 500")
embedNode.SetAttr("width", embedWidth)
}
return nil
}
func fixHeightAttribute(embedNode *goquery.Selection, report *[]string) error {
srcAttr, _ := embedNode.Attr("src")
srcPropPairs := strings.Split(srcAttr, "&")
var imgHeight float64
var tracklistHeight int
var err error
for _, prop := range srcPropPairs {
if strings.HasPrefix(prop, "withart") {
artPath := strings.Split(prop, propPairSeparator)[1]
imgHeight, err = getCoverHeight(artPath)
if err != nil {
return err
}
} else if strings.HasPrefix(prop, "height") {
tracklistHeight, err = strconv.Atoi(strings.Split(prop, propPairSeparator)[1])
if err != nil {
return err
}
}
}
embedNode.SetAttr("height", strconv.FormatFloat(imgHeight + float64(tracklistHeight + 10), 'f', -1, 64))
*report = append(*report, "Inappropriate height value")
return nil
}
func getCoverHeight(url string) (float64, error) {
img, err := http.Get(url)
if err != nil {
return 0, fmt.Errorf("Unable to download cover art: %s", err)
}
defer img.Body.Close()
imgConfig, _, err := image.DecodeConfig(img.Body)
if err != nil {
return 0, err
}
floatWidth := float64(imgConfig.Width)
floatHeight := float64(imgConfig.Height)
return 480 * floatHeight / floatWidth, nil
}
|
package types
// guardian module event types
const (
EventTypeSetFeed = "set_feed"
AttributeValueCategory = ModuleName
AttributeKeyFeedName = "feed_name"
AttributeKeyFeedValue = "feed_value"
)
|
package main
import (
"fmt"
"io/ioutil"
)
func main() {
// Create FILE and write some data to this file
// f, err := os.Create("output.txt")
// if err != nil {
// panic("unable to create file")
// }
// defer f.Close()
// cnt, err := f.WriteString("Hello, World!")
// if err != nil {
// panic("unable to write file")
// }
// fmt.Printf("Wrote %d bytes\n", cnt)
// Read data from file
// f, err := os.Open("output.txt")
// if err != nil {
// panic("unable to open file")
// }
// defer f.Close()
// buf := make([]byte, 64)
// cnt, err := f.Read(buf)
// if err != nil {
// panic("unable to read file")
// }
// fmt.Printf("Read %d bytes\n", cnt)
// fmt.Println(string(buf[:cnt]))
// Create and write to file with the IOUtil
// err := ioutil.WriteFile("out.txt", []byte("Hello, World!"), 0644)
// if err != nil {
// panic("unable to write file")
// }
buf, err := ioutil.ReadFile("out.txt")
if err != nil {
panic("unable to read file")
}
fmt.Println(string(buf))
}
|
package chartrepotest
import (
"net/http/httptest"
"os"
"testing"
)
// Metadata in Chart.yaml files
type Metadata struct {
AppVersion string `json:"appVersion"`
Name string `json:"name"`
Version string `json:"version"`
}
// ChartVersion type
type ChartVersion struct {
Name string `json:"name"`
Version string `json:"version"`
URLs []string `json:"urls"`
}
type httpError struct {
status int
body string
}
var (
username string = "user"
password string = "password"
// ChartMuseumTests defines two tests, using real & fake ChartMuseum services. This
// validates the publisher is correct and, at the same time, provides
// reasonable confidence the fake implementation is good enough.
ChartMuseumTests = []struct {
Desc string
Skip func(t *testing.T)
MakeServer func(t *testing.T) (string, func())
}{
{
"real service",
func(t *testing.T) {
key := "TEST_WITH_REAL_CHARTMUSEUM"
if os.Getenv(key) == "" {
t.Skipf("skipping because %s env var not set", key)
}
},
func(t *testing.T) (string, func()) {
return tChartMuseumReal(t, username, password)
},
},
{
"fake service",
func(t *testing.T) {},
func(t *testing.T) (string, func()) {
s := httptest.NewServer(newChartMuseumFake(t, username, password))
return s.URL, func() {
s.Close()
}
},
},
}
// HarborTests define a fake server for user with Harbor repositories
HarborTests = []struct {
Desc string
Skip func(t *testing.T)
MakeServer func(t *testing.T) (string, func())
}{
{
"fake service",
func(t *testing.T) {},
func(t *testing.T) (string, func()) {
s := httptest.NewServer(newHarborFake(t, username, password))
return s.URL, func() {
s.Close()
}
},
},
}
)
|
package models
import (
"bytes"
"database/sql"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"unicode"
"git.hoogi.eu/snafu/go-blog/httperror"
"git.hoogi.eu/snafu/go-blog/logger"
"git.hoogi.eu/snafu/go-blog/settings"
)
// File represents a file
type File struct {
ID int
UniqueName string `json:"unique_name"`
FullFilename string `json:"full_name"`
Link string `json:"link"`
ContentType string `json:"content_type"`
Inline bool `json:"inline"`
Size int64 `json:"size"`
LastModified time.Time `json:"last_modified"`
Data []byte `json:"-"`
FileInfo FileInfo
Author *User
}
// FileInfo contains Path, Name and Extension of a file.
// Use SplitFilename to split the information from a filename
type FileInfo struct {
Path string
Name string
Extension string
}
// FileDatasourceService defines an interface for CRUD operations of files
type FileDatasourceService interface {
Create(f *File) (int, error)
Get(fileID int, u *User) (*File, error)
GetByUniqueName(uniqueName string, u *User) (*File, error)
List(u *User, p *Pagination) ([]File, error)
Count(u *User) (int, error)
Update(f *File) error
Delete(fileID int) error
}
// validate validates if mandatory file fields are set
func (f *File) validate() error {
if len(f.FullFilename) == 0 {
return httperror.ValueRequired("filename")
}
if len(f.FullFilename) > 255 {
return httperror.ValueTooLong("filename", 255)
}
return nil
}
func (f File) randomFilename() string {
var buf bytes.Buffer
sanFilename := sanitizeFilename(f.FileInfo.Name)
if len(sanFilename) == 0 {
sanFilename = "unnamed"
}
buf.WriteString(sanFilename)
buf.WriteString(f.FileInfo.Extension)
return buf.String()
}
func SplitFilename(filename string) FileInfo {
base := filepath.Base(filename)
base = strings.TrimLeft(base, ".")
ext := filepath.Ext(base)
idx := strings.LastIndex(base, ".")
var name string
if idx > 0 {
name = base[:idx]
} else {
name = base
}
path := filepath.Dir(filename)
return FileInfo{
Name: name,
Extension: ext,
Path: path,
}
}
// FileService containing the service to interact with files
type FileService struct {
Datasource FileDatasourceService
Config settings.File
}
// GetByID returns the file based on the fileID; it the user is given and it is a non admin
// only file specific to this user is returned
func (fs *FileService) GetByID(fileID int, u *User) (*File, error) {
return fs.Datasource.Get(fileID, u)
}
// GetByUniqueName returns the file based on the unique name; it the user is given and it is a non admin
// only file specific to this user is returned
func (fs *FileService) GetByUniqueName(uniqueName string, u *User) (*File, error) {
return fs.Datasource.GetByUniqueName(uniqueName, u)
}
// List returns a list of files based on the filename; it the user is given and it is a non admin
// only files specific to this user are returned
func (fs *FileService) List(u *User, p *Pagination) ([]File, error) {
return fs.Datasource.List(u, p)
}
// Count returns a number of files based on the filename; it the user is given and it is a non admin
// only files specific to this user are counted
func (fs *FileService) Count(u *User) (int, error) {
return fs.Datasource.Count(u)
}
func (fs *FileService) ToggleInline(fileID int, u *User) error {
f, err := fs.Datasource.Get(fileID, u)
if err != nil {
return err
}
f.FileInfo = SplitFilename(f.FullFilename)
newName := f.randomFilename()
f.Inline = !f.Inline
err = os.Rename(filepath.Join(fs.Config.Location, f.UniqueName), filepath.Join(fs.Config.Location, newName))
f.UniqueName = newName
if err != nil {
return err
}
return fs.Datasource.Update(f)
}
// Delete deletes a file based on fileID; users which are not the owner are not allowed to remove files; except admins
func (fs *FileService) Delete(fileID int, u *User) error {
file, err := fs.Datasource.Get(fileID, u)
if err != nil {
return err
}
if !u.IsAdmin {
if file.Author.ID != u.ID {
return httperror.PermissionDenied("delete", "file", fmt.Errorf("could not remove file %d user %d has no permission", fileID, u.ID))
}
}
err = fs.Datasource.Delete(fileID)
if err != nil {
return err
}
return os.Remove(filepath.Join(fs.Config.Location, file.UniqueName))
}
// Upload uploaded files will be saved at the configured file location, filename is saved in the database
func (fs *FileService) Upload(f *File) (int, error) {
if err := f.validate(); err != nil {
return -1, err
}
f.FileInfo = SplitFilename(f.FullFilename)
if len(f.FileInfo.Extension) == 0 && !strings.HasPrefix(f.ContentType, "text/plain") {
return -1, httperror.New(
http.StatusUnprocessableEntity,
"The file has no extension and does not contain plain text.",
fmt.Errorf("the file %s has no extension and does not contain plain text, content type is: %s", f.FullFilename, f.ContentType))
}
if len(f.FileInfo.Extension) > 0 {
if _, ok := fs.Config.AllowedFileExtensions[f.FileInfo.Extension]; !ok {
return -1, httperror.New(
http.StatusUnprocessableEntity,
"The file type is not supported.",
fmt.Errorf("error during upload, the file type %s is not supported", f.FileInfo.Extension))
}
}
f.UniqueName = f.randomFilename()
file, err := fs.GetByUniqueName(f.UniqueName, nil)
if err != nil {
if err != sql.ErrNoRows {
return -1, err
}
}
if file != nil {
return -1, httperror.New(
http.StatusUnprocessableEntity,
"A file with this filename already exist. Please choose another filename.",
errors.New("a file with this filename already exist"))
}
fi := filepath.Join(fs.Config.Location, f.UniqueName)
if err = ioutil.WriteFile(fi, f.Data, 0640); err != nil {
return -1, err
}
i, err := fs.Datasource.Create(f)
if err != nil {
err2 := os.Remove(fi)
if err2 != nil {
logger.Log.Error(err2)
}
return -1, err
}
f.Data = nil
return i, nil
}
var filenameSubs = map[rune]string{
'/': "",
'\\': "",
':': "",
'*': "",
'?': "",
'"': "",
'<': "",
'>': "",
'|': "",
' ': "",
}
func isDot(r rune) bool {
return '.' == r
}
// sanitizeFilename sanitizes a filename for safe use when serving file
func sanitizeFilename(s string) string {
s = strings.ToValidUTF8(s, "")
s = strings.TrimFunc(s, unicode.IsSpace)
s = strings.Map(func(r rune) rune {
if _, ok := filenameSubs[r]; ok {
return -1
}
return r
}, s)
s = strings.TrimLeftFunc(s, isDot)
return s
}
|
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println("my favorite number is ", rand.Intn(10))
// rend.Intn 每次返回同一个数字
}
/*
包
每个 Go 程序都由包组成, 程序运行的入口是包 main
上面程序使用并导入包 "fmt" 和 "math/rand"
包名应该与导入路径的最后一个目录一致。例如, "math/rand" 包由 package rand 开始
*/
|
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(maxProfit([]int{7, 1, 5, 3, 6, 4}))
}
func maxProfit2(prices []int) int {
max := func(a, b int) int {
if a > b {
return a
}
return b
}
ans := math.MinInt
dp := make([]int, len(prices))
for i := 0; i < len(prices); i++ {
for j := i + 1; j < len(prices); j++ {
dp[i] = max(dp[i], prices[j]-prices[i])
}
if dp[i] > ans {
ans = dp[i]
}
}
if ans > 0 {
return ans
}
return 0
}
func maxProfit(prices []int) int {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
if len(prices) <= 1 {
return 0
}
buy := prices[0] //买入价格
profit := 0 //利润
for _, p := range prices {
if x := p - buy; x > profit {
profit = x
}
buy = min(buy, p)
}
return profit
}
|
package main
import "fmt"
func main() {
fmt.Println("Hello")
x := []int{2, 2, 1}
y := []int{4, 1, 2, 1, 2}
fmt.Println(singleNumber1(x))
fmt.Println(singleNumber1(y))
}
func singleNumber1(nums []int) int {
for i := 1; i < len(nums); i++ {
nums[0] ^= nums[i]
}
return nums[0]
}
|
package database
import (
"fmt"
"os"
mgo "gopkg.in/mgo.v2"
)
var db *mgo.Database
func init() {
host := os.Getenv("MONGO_HOST")
dbName := os.Getenv("MONGO_DB_NAME")
session, err := mgo.Dial(host)
if err != nil {
fmt.Println("session err:", err)
os.Exit(2)
}
db = session.DB(dbName)
}
func GetMongoDB() *mgo.Database {
return db
}
|
package main
import "fmt"
func main() {
var a []int
// a[0] = 10 //error
fmt.Println(a)
}
|
package github
import "time"
const Url = "https://api.github.com/repos/dah8ra/golangtraining/issues"
const IssueUrl = "https://api.github.com/repos/dah8ra/golangtraining/issues/"
const BaseUrl = "https://api.github.com/"
type Missing struct {
Message string
Errors *Errors
}
type Errors struct {
Resource string
Field string `json:"title"`
Code string `json:"missing_field"`
}
type IssuesSearchResult struct {
TotalCount int `json:"total_count"`
Items []*Issue
}
type Issue struct {
Number int
HTMLURL string `json:"html_url"`
Title string `json:"title"`
State string `json:"state"`
User *User
CreatedAt time.Time `json:"created_at"`
Body string // in Markdown format
}
type User struct {
Login string
HTMLURL string `json:"html_url"`
}
|
package model
import (
"os"
"strings"
"testing"
)
func setupDB() {
os.Remove("tmp.db")
InitDB("tmp.db")
}
func cleanDB() {
CloseDB()
os.Remove("tmp.db")
}
func setupUser() User {
return User{
Name: "Example User",
Email: "user@example.com",
Password: "foobar",
PasswordConfirmation: "foobar",
}
}
func TestUserName(t *testing.T) {
user := setupUser()
setupDB()
if errs := user.Validate(); errs != nil {
t.Error("should be valid")
}
cleanDB()
setupDB()
user.Name = " "
if errs := user.Validate(); errs == nil {
t.Error("Name should be present")
}
cleanDB()
setupDB()
user.Name = strings.Repeat("a", 51)
if errs := user.Validate(); errs == nil {
t.Error("Name should be less than 51")
}
cleanDB()
}
func TestUserEmail(t *testing.T) {
user := setupUser()
setupDB()
if errs := user.Validate(); errs != nil {
t.Error("should be valid")
}
cleanDB()
setupDB()
user.Email = " "
if errs := user.Validate(); errs == nil {
t.Error("should be preset")
}
cleanDB()
setupDB()
user.Email = strings.Repeat("a", 244) + "@example.com"
if errs := user.Validate(); errs == nil {
t.Errorf("Email should be less than 255")
}
cleanDB()
validAddresses := []string{
"user@example.com",
"USER@foo.COM",
"A_US-ER@foo.bar.org",
"first.last@foo.jp",
"alice+bob@baz.cn",
}
for _, validAddress := range validAddresses {
setupDB()
user.Email = validAddress
if errs := user.Validate(); errs != nil {
t.Errorf("Email should be valid (%v)", validAddress)
}
cleanDB()
}
invalidAddresses := []string{
"user@example,com",
"user_at_foo.org",
"user.name@example.",
//"foo@bar_baz.com",
"foo@bar+baz.com",
"foo@bar..com",
}
for _, invalidAddress := range invalidAddresses {
setupDB()
user.Email = invalidAddress
if errs := user.Validate(); errs == nil {
t.Errorf("Email should not be valid (%v)", invalidAddress)
}
cleanDB()
}
}
func TestUserPassword(t *testing.T) {
user := setupUser()
setupDB()
if errs := user.Validate(); errs != nil {
t.Error("User should be created")
}
cleanDB()
setupDB()
user.Password = " "
user.PasswordConfirmation = user.Password
if errs := user.Validate(); errs == nil {
t.Error("Password should be preset")
}
cleanDB()
setupDB()
user.Password = "aaaaa"
user.PasswordConfirmation = user.Password
if errs := user.Validate(); errs == nil {
t.Error("Password should have over 6 charactors")
}
cleanDB()
}
func TestCreateUser(t *testing.T) {
user := setupUser()
setupDB()
defer cleanDB()
_, err := CreateUser(user)
if err != nil {
t.Error("user should be created")
}
user.Name = "New User"
_, err = CreateUser(user)
if err == nil {
t.Error("user should not be created")
}
user.Email = "USER@EXAMPLE.COM"
_, err = CreateUser(user)
if err == nil {
t.Error("user should not be created")
}
}
func TestUserAuth(t *testing.T) {
user := setupUser()
setupDB()
defer cleanDB()
caretedUser, err := CreateUser(user)
if err != nil {
t.Error("user should be created")
}
if true == caretedUser.Authenticate("not_the_right_password") {
t.Error("user password should not match")
}
if false == caretedUser.Authenticate("foobar") {
t.Error("user password should match")
}
}
|
package models
import (
"encoding/json"
)
type Image struct {
ID string `json:"ID"`
Containers []Container `json:"Containers"`
}
func NewImages(data []byte) ([]Image, error) {
var i []Image
err := json.Unmarshal(data, &i)
return i, err
}
|
package datastoresql
import (
"github.com/direktiv/direktiv/pkg/refactor/core"
"github.com/direktiv/direktiv/pkg/refactor/datastore"
"github.com/direktiv/direktiv/pkg/refactor/events"
"github.com/direktiv/direktiv/pkg/refactor/logengine"
"github.com/direktiv/direktiv/pkg/refactor/mirror"
"gorm.io/gorm"
)
type sqlStore struct {
// database connection.
db *gorm.DB
// symmetric encryption key to encrypt and decrypt mirror data.
mirrorConfigEncryptionKey string
}
var _ datastore.Store = &sqlStore{}
// NewSQLStore builds direktiv data store. Param `db` should be an opened active connection to the database. Param
// `mirrorConfigEncryptionKey` is a symmetric encryption key string used to encrypt and decrypt mirror data.
// Database transactions management should be handled by the user of this datastore.Store implementation. The caller
// can start a transaction and pass it as Param `db`. After calling different operations on the store, the caller can
// either commit or rollback the connection.
func NewSQLStore(db *gorm.DB, mirrorConfigEncryptionKey string) datastore.Store {
return &sqlStore{
db: db,
mirrorConfigEncryptionKey: mirrorConfigEncryptionKey,
}
}
func NewServicesStore(db *gorm.DB) core.ServicesStore {
return &sqlServicesStore{
db: db,
}
}
// Mirror returns mirror store.
func (s *sqlStore) Mirror() mirror.Store {
return &sqlMirrorStore{
db: s.db,
configEncryptionKey: s.mirrorConfigEncryptionKey,
}
}
// FileAnnotations returns file annotations store.
func (s *sqlStore) FileAnnotations() core.FileAnnotationsStore {
return &sqlFileAnnotationsStore{
db: s.db,
}
}
// Logs returns a log store.
func (s *sqlStore) Logs() logengine.LogStore {
return &sqlLogStore{
db: s.db,
}
}
// Secrets returns secrets store.
func (s *sqlStore) Secrets() core.SecretsStore {
return &sqlSecretsStore{
db: s.db,
}
}
func (s *sqlStore) RuntimeVariables() core.RuntimeVariablesStore {
return &sqlRuntimeVariablesStore{
db: s.db,
}
}
func (s *sqlStore) Services() core.ServicesStore {
return &sqlServicesStore{
db: s.db,
}
}
func (s *sqlStore) EventFilter() events.CloudEventsFilterStore {
return &sqlNamespaceCloudEventFilter{db: s.db}
}
func (s *sqlStore) EventHistory() events.EventHistoryStore {
return &sqlEventHistoryStore{db: s.db}
}
func (s *sqlStore) EventListener() events.EventListenerStore {
return &sqlEventListenerStore{db: s.db}
}
func (s *sqlStore) EventListenerTopics() events.EventTopicsStore {
return &sqlEventTopicsStore{db: s.db}
}
func (s *sqlStore) NamespaceCloudEventFilter() events.CloudEventsFilterStore {
return &sqlNamespaceCloudEventFilter{db: s.db}
}
func (s *sqlStore) Namespaces() core.NamespacesStore {
return &sqlNamespacesStore{db: s.db}
}
|
package filters_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/bosh-prometheus/cf_exporter/filters"
)
var _ = Describe("CollectorsFilter", func() {
var (
err error
filters []string
collectorsFilter *CollectorsFilter
cfAPIv3Enabled bool
)
JustBeforeEach(func() {
collectorsFilter, err = NewCollectorsFilter(filters, cfAPIv3Enabled)
})
Describe("New", func() {
Context("when filters are supported", func() {
BeforeEach(func() {
filters = []string{
ApplicationsCollector,
OrganizationsCollector,
RoutesCollector,
SecurityGroupsCollector,
ServiceBindingsCollector,
ServiceInstancesCollector,
ServicePlansCollector,
ServicesCollector,
SpacesCollector,
StacksCollector,
}
})
It("does not return an error", func() {
Expect(err).ToNot(HaveOccurred())
})
Context("and has leading and/or trailing whitespaces", func() {
BeforeEach(func() {
filters = []string{" " + ApplicationsCollector + " "}
})
It("does not return an error", func() {
Expect(err).ToNot(HaveOccurred())
})
})
Context("when CF API V3 is required", func() {
BeforeEach(func() {
filters = append(filters, IsolationSegmentsCollector)
})
Context("and is enabled", func() {
BeforeEach(func() {
cfAPIv3Enabled = true
})
It("does not return an error", func() {
Expect(err).ToNot(HaveOccurred())
})
})
Context("and is not enabled", func() {
BeforeEach(func() {
cfAPIv3Enabled = false
})
It("returns an error", func() {
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("IsolationSegments Collector filter need CF API V3 enabled"))
})
})
})
})
Context("when filters are not supported", func() {
BeforeEach(func() {
filters = []string{ApplicationsCollector, "Unknown"}
})
It("returns an error", func() {
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Collector filter `Unknown` is not supported"))
})
})
})
Describe("Enabled", func() {
BeforeEach(func() {
filters = []string{ApplicationsCollector}
})
Context("when collector is enabled", func() {
It("returns true", func() {
Expect(collectorsFilter.Enabled(ApplicationsCollector)).To(BeTrue())
})
})
Context("when collector is not enabled", func() {
It("returns false", func() {
Expect(collectorsFilter.Enabled(OrganizationsCollector)).To(BeFalse())
})
})
Context("when there are no filters", func() {
BeforeEach(func() {
filters = []string{}
})
Context("when CF API V3 is enabled", func() {
BeforeEach(func() {
cfAPIv3Enabled = true
})
It("Applications Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ApplicationsCollector)).To(BeTrue())
})
It("Isolation Segments Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(IsolationSegmentsCollector)).To(BeTrue())
})
It("Organizations Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(OrganizationsCollector)).To(BeTrue())
})
It("Routes Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(RoutesCollector)).To(BeTrue())
})
It("Security Groups Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(SecurityGroupsCollector)).To(BeTrue())
})
It("Service Bindings Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ServiceBindingsCollector)).To(BeTrue())
})
It("Service Instances Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ServiceInstancesCollector)).To(BeTrue())
})
It("Service Plans Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ServicePlansCollector)).To(BeTrue())
})
It("Services Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ServicesCollector)).To(BeTrue())
})
It("Spaces Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(SpacesCollector)).To(BeTrue())
})
It("Stacks Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(StacksCollector)).To(BeTrue())
})
})
Context("when CF API V3 is not enabled", func() {
BeforeEach(func() {
cfAPIv3Enabled = false
})
It("Applications Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ApplicationsCollector)).To(BeTrue())
})
It("Isolation Segments Collector should be disabled", func() {
Expect(collectorsFilter.Enabled(IsolationSegmentsCollector)).To(BeFalse())
})
It("Organizations Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(OrganizationsCollector)).To(BeTrue())
})
It("Routes Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(RoutesCollector)).To(BeTrue())
})
It("Security Groups Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(SecurityGroupsCollector)).To(BeTrue())
})
It("Service Bindings Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ServiceBindingsCollector)).To(BeTrue())
})
It("Service Instances Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ServiceInstancesCollector)).To(BeTrue())
})
It("Service Plans Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ServicePlansCollector)).To(BeTrue())
})
It("Services Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(ServicesCollector)).To(BeTrue())
})
It("Spaces Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(SpacesCollector)).To(BeTrue())
})
It("Stacks Collector should be enabled", func() {
Expect(collectorsFilter.Enabled(StacksCollector)).To(BeTrue())
})
})
})
})
})
|
package networkd
import (
"fmt"
"os"
"os/exec"
"strings"
"text/template"
)
type networkDevice struct {
Name string
Destination string
}
const (
networkdPath = "/etc/systemd/network"
bridgeHostFile = "80-container-bridge.netdev"
networkHostFile = "82-container-bridge.network"
networkContainerFile = "80-container-host0.network"
)
const bridgeHostTemplate string = `[NetDev]
Name={{.Name}}
Kind=bridge
`
const networkHostTemplate string = `[Match]
Name={{.Name}}
[Network]
Address={{.Destination}}.1/24
DHCPServer=yes
DNS=8.8.8.8
IPMasquerade=yes
`
const networkContainerTemplate string = `[Match]
Virtualization=container
Name=host0
[Network]
DHCP=yes
[Route]
Gateway={{.Destination}}.1
`
func storeNetworkDefinition(dev networkDevice, text, path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()
var tmpl *template.Template
tmpl, err = template.New("device").Parse(text)
if err != nil {
return err
}
err = tmpl.Execute(f, dev)
if err != nil {
return err
}
return nil
}
func DefineHostNetwork(bridge, destination string) error {
dev := networkDevice{
Name: bridge,
Destination: strings.Replace(destination, ".0/24", "", 1),
}
bridgeHostPath := fmt.Sprintf("%s/%s", networkdPath, bridgeHostFile)
err := storeNetworkDefinition(dev, bridgeHostTemplate, bridgeHostPath)
if err != nil {
return err
}
networkHostPath := fmt.Sprintf("%s/%s", networkdPath, networkHostFile)
err = storeNetworkDefinition(dev, networkHostTemplate, networkHostPath)
if err != nil {
return err
}
return restart()
}
func DefineContainerNetwork(containerPath, destination string) error {
dev := networkDevice{
Destination: strings.Replace(destination, ".0/24", "", 1),
}
networkContainerPath := fmt.Sprintf("%s/%s/%s", containerPath, networkdPath, networkContainerFile)
return storeNetworkDefinition(dev, networkContainerTemplate, networkContainerPath)
}
func RemoveHostNetwork() error {
err := os.Remove(fmt.Sprintf("%s/%s", networkdPath, bridgeHostFile))
if err != nil {
return err
}
err = os.Remove(fmt.Sprintf("%s/%s", networkdPath, networkHostFile))
if err != nil {
return err
}
return restart()
}
func restart() error {
return exec.Command("systemctl", "restart", "systemd-networkd").Run()
}
|
package bitty
/*
Copyright 2020 IBM
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.
*/
import (
"fmt"
"math"
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type testIECUnit struct {
Unit IECUnit
Expected float64
}
func ExampleNewIECUnit() {
a, _ := NewIECUnit(10.0, Mib)
b, _ := NewIECUnit(1.0, "GiB")
_, cerr := NewIECUnit(3.0, "")
_, derr := NewIECUnit(32.0, "fooBar")
fmt.Printf("%v\n", a)
fmt.Printf("%v\n", b)
fmt.Printf("%v\n", cerr)
fmt.Printf("%v\n", derr)
// Output:
// &{10 Mib 2}
// &{1 GiB 3}
// unit symbol not supported: empty symbol
// unit symbol not supported: fooBar
}
func ExampleIECUnit_ByteSize() {
a, _ := NewIECUnit(10.0, MiB)
b, _ := NewIECUnit(10.0, Mib)
fmt.Printf("%.f\n", a.ByteSize())
fmt.Printf("%.f\n", b.ByteSize())
// Output:
// 10485760
// 1310720
}
func generateTestIECUnitByteSize(t *testing.T, sym UnitSymbol) testIECUnit {
u, err := NewIECUnit(rand.Float64(), sym)
if err != nil {
t.Error(err)
}
l := testIECUnit{Unit: *u}
le := float64(u.exponent * 10)
lb := float64(math.Exp2(le) * l.Unit.size)
switch sym {
case Bit:
l.Expected = l.Unit.size * 8
case Byte:
l.Expected = l.Unit.size
case Kib, Mib, Gib, Tib, Pib, Eib, Zib, Yib:
l.Expected = lb * 0.125
case KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB:
l.Expected = lb
default:
l.Expected = float64(0)
}
return l
}
func TestIEC_ByteSize(t *testing.T) {
rand.Seed(time.Now().UnixNano())
tests := make([]testIECUnit, 0, len(unitSymbolPairs))
for _, p := range unitSymbolPairs {
if p.Standard() != IEC {
break
}
l := generateTestIECUnitByteSize(t, p.Least())
r := generateTestIECUnitByteSize(t, p.Greatest())
tests = append(tests, l, r)
}
// Add a bad entry for negative testing
bu := testIECUnit{
Unit: IECUnit{rand.Float64(), UnitSymbol("FooBar"), 30},
Expected: float64(0),
}
tests = append(tests, bu)
// Run through all the tests
for _, tst := range tests {
assert.Equal(t, tst.Expected, tst.Unit.ByteSize())
}
}
func ExampleIECUnit_BitSize() {
a, _ := NewIECUnit(10.0, MiB)
b, _ := NewIECUnit(10.0, Mib)
fmt.Printf("%.f\n", a.BitSize())
fmt.Printf("%.f\n", b.BitSize())
// Output:
// 83886080
// 10485760
}
func generateTestIECUnitBitSize(t *testing.T, sym UnitSymbol) testIECUnit {
tu, err := NewIECUnit(rand.Float64()*10, sym)
if err != nil {
t.Error(err)
}
l := testIECUnit{Unit: *tu}
bytes := tu.ByteSize()
switch sym {
case Bit:
l.Expected = l.Unit.size
case Byte,
Kib, Mib, Gib, Tib, Pib, Eib, Zib, Yib,
KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB:
l.Expected = float64(bytes * 8)
default:
l.Expected = float64(0)
}
return l
}
func TestIECUnit_BitSize(t *testing.T) {
rand.Seed(time.Now().UnixNano())
tests := make([]testIECUnit, 0, len(unitSymbolPairs))
// Setup test cases based out of what is in IECUnitExponentMap
for _, p := range unitSymbolPairs {
if p.Standard() != IEC {
break
}
l := generateTestIECUnitBitSize(t, p.Least())
r := generateTestIECUnitBitSize(t, p.Greatest())
tests = append(tests, l, r)
}
// Add a bad entry for negative testing
bu := testIECUnit{
Unit: IECUnit{rand.Float64() * 10, UnitSymbol("FooBar"), 30},
Expected: float64(0),
}
tests = append(tests, bu)
// Run through all the tests
for _, tst := range tests {
assert.Equal(t, tst.Expected, tst.Unit.BitSize())
if t.Failed() {
fmt.Printf("size: %f, symbol: %s, bits: %f, expected: %f\n",
tst.Unit.size, tst.Unit.symbol,
tst.Unit.BitSize(), tst.Expected,
)
}
}
}
func ExampleIECUnit_SizeInUnit() {
a, _ := NewIECUnit(10.0, MiB)
inKiB := a.SizeInUnit(KiB)
inGiB := a.SizeInUnit(GiB)
inMib := a.SizeInUnit(Mib)
fmt.Println(inKiB, inGiB, inMib)
// Output:
// 10240 0.009765625 80
}
type testIECSizeInUnit struct {
unit IECUnit
to UnitSymbol
expected float64
}
func generateTestIECUnitSizeInUnit(t *testing.T, unit IECUnit, sym UnitSymbol) testIECSizeInUnit {
u := testIECSizeInUnit{unit: unit, to: sym}
r, err := NewIECUnit(unit.size, sym)
if err != nil {
t.Error(err)
}
var (
left = unit.ByteSize()
right = r.ByteSize()
diffExp = float64(unit.exponent - r.exponent)
)
if diffExp > 0 {
u.expected = right * diffExp
} else {
u.expected = (left / right) * u.unit.size
}
return u
}
func TestIECUnit_SizeInUnit(t *testing.T) {
rand.Seed(time.Now().UnixNano())
tests := make([]testIECSizeInUnit, 0, len(unitSymbolPairs))
for _, p := range unitSymbolPairs {
if p.Standard() != IEC {
break
}
l, err := NewIECUnit(rand.Float64()*10, p.Least())
if err != nil {
t.Error(err)
break
}
r, err := NewIECUnit(rand.Float64()*10, p.Greatest())
if err != nil {
t.Error(err)
break
}
for _, rp := range unitSymbolPairs {
lu := generateTestIECUnitSizeInUnit(t, *l, rp.Least())
ru := generateTestIECUnitSizeInUnit(t, *r, rp.Greatest())
tests = append(tests, lu, ru)
}
}
// Add a couple of bad entries for negative testing
bu := testIECSizeInUnit{
unit: IECUnit{rand.Float64() * 10, UnitSymbol("FooBar"), 30},
to: MiB,
expected: float64(0),
}
bur := testIECSizeInUnit{
unit: IECUnit{rand.Float64() * 10, MiB, 30},
to: UnitSymbol("FooBar"),
expected: float64(0),
}
tests = append(tests, bu, bur)
// Run through all the tests
for _, tst := range tests {
assert.Equal(t, tst.expected, tst.unit.SizeInUnit(tst.to))
}
}
func ExampleIECUnit_Add() {
// Test the same byte symbol
a, _ := NewIECUnit(2, MiB)
b, _ := NewIECUnit(2, MiB)
c, ok := a.Add(b).(*IECUnit)
if !ok {
panic(fmt.Errorf("Unit not *IECUnit: %v", c))
}
fmt.Printf(
"%.f %s + %.f %s = %.f %s\n",
a.Size(), a.Symbol(),
b.Size(), b.Symbol(),
c.Size(), c.Symbol(),
)
// Output:
// 2 MiB + 2 MiB = 4 MiB
}
type testIECUnitAdd struct {
left, right, expected *IECUnit
}
func TestIECUnit_Add(t *testing.T) {
rand.Seed(time.Now().UnixNano())
tests := make([]testIECUnitAdd, 0, len(iecUnitExponentMap))
// Setup test cases based out of what is in IECUnitExponentMap
for k := range iecUnitExponentMap {
tul, _ := NewIECUnit(rand.Float64()*10, k)
if tul == nil {
break
}
for l := range iecUnitExponentMap {
var (
ru *IECUnit
nexp int
nsym UnitSymbol
size float64
)
ru, _ = NewIECUnit(rand.Float64()*10, l)
u := testIECUnitAdd{left: tul, right: ru}
lok, rok := ValidateSymbols(tul.Symbol(), ru.Symbol())
if !lok && !rok {
nexp = 0
}
if lok && !rok {
nexp = tul.Exponent()
}
if rok && !lok {
nexp = ru.Exponent()
}
left := tul.ByteSize()
right := ru.ByteSize()
total := left + right
if total > 0 {
nexp = int(math.Round(math.Log2(total) / 10))
}
if tul.Exponent() >= ru.Exponent() {
nexp = tul.Exponent()
} else {
nexp = ru.Exponent()
}
lsym, ok := FindLeastUnitSymbol(IEC, nexp)
gsym, ok := FindGreatestUnitSymbol(IEC, nexp)
if !ok {
u.expected, _ = NewIECUnit(0, Byte)
} else {
smallSize := BytesToUnitSymbolSize(IEC, lsym, total)
lrgSize := BytesToUnitSymbolSize(IEC, gsym, total)
if lrgSize < 1 {
nsym = lsym
size = smallSize
} else {
nsym = gsym
size = lrgSize
}
u.expected, _ = NewIECUnit(size, nsym)
}
tests = append(tests, u)
}
}
// Add a couple of bad entries for negative testing
s := rand.Float64() * 10
gu, _ := NewIECUnit(s, MiB)
byteu, _ := NewIECUnit(0, Byte)
bu := &IECUnit{s, UnitSymbol("FooBar"), 30}
bul := testIECUnitAdd{
left: bu,
right: gu,
expected: gu,
}
bur := testIECUnitAdd{
left: gu,
right: bu,
expected: gu,
}
bub := testIECUnitAdd{
left: bu,
right: bu,
expected: byteu,
}
tests = append(tests, bul, bur, bub)
// Run through all the tests
for _, tst := range tests {
u, ok := tst.left.Add(tst.right).(*IECUnit)
assert.Equal(t, true, ok)
assert.Equal(t, tst.expected, u)
}
}
func ExampleIECUnit_Subtract() {
var (
c *IECUnit
ok bool
)
// Test the same byte symbol
a, _ := NewIECUnit(10, GiB)
b, _ := NewIECUnit(10.023, GiB)
c, ok = a.Subtract(b).(*IECUnit)
if !ok {
panic(fmt.Errorf("Unit not *IECUnit: %v", c))
}
fmt.Printf(
"%.3f %s - %.3f %s = %.3f %s\n",
a.size, a.symbol,
b.size, b.symbol,
c.size, c.symbol,
)
// Output:
// 10.000 GiB - 10.023 GiB = -23.552 MiB
}
type testIECUnitSubtract struct {
left, right, expected *IECUnit
}
func TestIECUnit_Subtract(t *testing.T) {
rand.Seed(time.Now().UnixNano())
tests := make([]testIECUnitSubtract, 0, len(iecUnitExponentMap))
// Setup test cases based out of what is in IECUnitExponentMap
for k := range iecUnitExponentMap {
tul, _ := NewIECUnit(rand.Float64()*10, k)
if tul == nil {
break
}
for l := range iecUnitExponentMap {
var (
ru *IECUnit
nexp int
nsym, lsym, gsym UnitSymbol
total float64
neg bool
)
ru, _ = NewIECUnit(rand.Float64()*10, l)
u := testIECUnitSubtract{left: tul, right: ru}
lok, rok := ValidateSymbols(tul.Symbol(), ru.Symbol())
if !lok && !rok {
nexp = 0
}
if lok && !rok {
nexp = tul.Exponent()
}
if rok && !lok {
nexp = ru.Exponent()
}
left := tul.ByteSize()
right := ru.ByteSize()
if left >= right {
total = left - right
} else {
total = right - left
neg = true
}
if total > 0 {
nexp = int(math.Round(math.Log2(total) / 10))
}
lsym, _ = FindLeastUnitSymbol(IEC, nexp)
gsym, _ = FindGreatestUnitSymbol(IEC, nexp)
smlSize := BytesToUnitSymbolSize(IEC, lsym, total)
lrgSize := BytesToUnitSymbolSize(IEC, gsym, total)
if lrgSize > 0 {
if neg {
lrgSize = -lrgSize
}
u.expected, _ = NewIECUnit(lrgSize, gsym)
} else {
if neg {
smlSize = -smlSize
}
u.expected, _ = NewIECUnit(smlSize, nsym)
}
tests = append(tests, u)
}
}
// Add a couple of bad entries for negative testing
s := rand.Float64() * 10
gu, _ := NewIECUnit(s, MiB)
byteu, _ := NewIECUnit(0, Byte)
bu := &IECUnit{s, UnitSymbol("FooBar"), 30}
bul := testIECUnitSubtract{
left: bu,
right: gu,
expected: gu,
}
bur := testIECUnitSubtract{
left: gu,
right: bu,
expected: gu,
}
bub := testIECUnitSubtract{
left: bu,
right: bu,
expected: byteu,
}
tests = append(tests, bul, bur, bub)
// Run through all the tests
for _, tst := range tests {
u, ok := tst.left.Subtract(tst.right).(*IECUnit)
assert.Equal(t, true, ok)
assert.Equal(t, tst.expected, u)
}
}
|
/*
Pelichan is a disk-backed channel pipe
Basic operation is to constantly pipe messages from Source to Sink channels.
Whenever Sink blocks, all incoming messages start being stored on disk in a LevelDB database.
When Sink cleanups both incoming and previously stored messages will be sent to Sink.
Simplified operation diagram:
user data +--------+ direct fwd +------+ consumers
--------->| SrcFwd |------------>| Sink |---->
SRC +--------+ +------+
store on Sink full | +--------+ ^
| | DskRdr |------/
V +--------+
+------+ ^ read n forward (RnF)
| Disk |---/
+------+
DiskBufferedChan (DBC) has three primary states:
1. Normal Operation - When it forwards incoming messages and try to store them on disk, if queue is full
2. Halt - (after calling halt method) when all reading/forwarding stopped, but DBC still can receive objects into
disk queue via Store() method.
3. Closed - when object is halted and LevelDB backend is closed, DBC now can be disposed
How to abort:
1. Close incoming Source pipe
After that all messages stored on disk will be pumped to Sink channel, and Sink will be closed afterwards
Call Close to close LevelDB backend and you're done.
If you want to save something in LevelDB, you can first wait for DiskReader to close with WaitHalt() and then
inject some messages via Store method, just before calling Close.
If you call halt during this messages in Sink will be sucked back on disk.
2. Call Halt()
This will stop both SourceForwarder and DiskReader, and all messages on disk be stored there. Messages
buffered in Sink will be sucked back to disk, LevelDB will be open till call of Close, so you can put in
some messages via Store before closing it.
3. Call Close()
You can just call Close to halt and close DBC ASAP
*/
package pelichan
|
package errors
import (
"fmt"
)
func panicTop1() (err error) {
defer func() {
r := recover()
rerr, ok := r.(error)
if !ok {
rerr = fmt.Errorf("panic: %v", r)
}
err = WithStack(rerr)
}()
return panicMiddle1()
}
func panicMiddle1() error {
return panicBottom1()
}
func panicBottom1() error {
panic("panicBottom1")
}
|
package logic
import (
"testing"
"fmt"
)
func TestNewLogicLogDecorator(t *testing.T) {
fmt.Println("Process with log.")
handler := NewHandler()
handler.WrapLog()
//Run the process.
handler.Operate1()
} |
package entity
type StatisticPerYear struct {
YearAndMon string `json:"year_and_month"`
Profit int64 `json:"profit"`
}
type StatisticPerMon struct {
Mon string `json:"mon"`
Profit int64 `json:"profit"`
}
type StatisticPerMonRes struct {
Year string `json:"year"`
Detail []StatisticPerMon `json:"detail"`
}
type StatisticPerYearReq struct {
Year string `json:"year"`
}
|
// Copyright 2020 Google Inc. All rights reserved.
//
// 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 remoteexec
import (
"sort"
"strings"
"android/soong/android"
"github.com/google/blueprint"
)
const (
// ContainerImageKey is the key identifying the container image in the platform spec.
ContainerImageKey = "container-image"
// PoolKey is the key identifying the pool to use for remote execution.
PoolKey = "Pool"
// DefaultImage is the default container image used for Android remote execution. The
// image was built with the Dockerfile at
// https://android.googlesource.com/platform/prebuilts/remoteexecution-client/+/refs/heads/master/docker/Dockerfile
DefaultImage = "docker://gcr.io/androidbuild-re-dockerimage/android-build-remoteexec-image@sha256:582efb38f0c229ea39952fff9e132ccbe183e14869b39888010dacf56b360d62"
// DefaultWrapperPath is the default path to the remote execution wrapper.
DefaultWrapperPath = "prebuilts/remoteexecution-client/live/rewrapper"
// DefaultPool is the name of the pool to use for remote execution when none is specified.
DefaultPool = "default"
// LocalExecStrategy is the exec strategy to indicate that the action should be run locally.
LocalExecStrategy = "local"
// RemoteExecStrategy is the exec strategy to indicate that the action should be run
// remotely.
RemoteExecStrategy = "remote"
// RemoteLocalFallbackExecStrategy is the exec strategy to indicate that the action should
// be run remotely and fallback to local execution if remote fails.
RemoteLocalFallbackExecStrategy = "remote_local_fallback"
)
var (
defaultLabels = map[string]string{"type": "tool"}
defaultExecStrategy = LocalExecStrategy
pctx = android.NewPackageContext("android/soong/remoteexec")
)
// REParams holds information pertinent to the remote execution of a rule.
type REParams struct {
// Platform is the key value pair used for remotely executing the action.
Platform map[string]string
// Labels is a map of labels that identify the rule.
Labels map[string]string
// ExecStrategy is the remote execution strategy: remote, local, or remote_local_fallback.
ExecStrategy string
// Inputs is a list of input paths or ninja variables.
Inputs []string
// RSPFile is the name of the ninja variable used by the rule as a placeholder for an rsp
// input.
RSPFile string
// OutputFiles is a list of output file paths or ninja variables as placeholders for rule
// outputs.
OutputFiles []string
// OutputDirectories is a list of output directories or ninja variables as placeholders for
// rule output directories.
OutputDirectories []string
// ToolchainInputs is a list of paths or ninja variables pointing to the location of
// toolchain binaries used by the rule.
ToolchainInputs []string
}
func init() {
pctx.VariableFunc("Wrapper", func(ctx android.PackageVarContext) string {
return wrapper(ctx.Config())
})
}
func wrapper(cfg android.Config) string {
if override := cfg.Getenv("RBE_WRAPPER"); override != "" {
return override
}
return DefaultWrapperPath
}
// Template generates the remote execution wrapper template to be added as a prefix to the rule's
// command.
func (r *REParams) Template() string {
return "${remoteexec.Wrapper}" + r.wrapperArgs()
}
// NoVarTemplate generates the remote execution wrapper template without variables, to be used in
// RuleBuilder.
func (r *REParams) NoVarTemplate(cfg android.Config) string {
return wrapper(cfg) + r.wrapperArgs()
}
func (r *REParams) wrapperArgs() string {
args := ""
var kvs []string
labels := r.Labels
if len(labels) == 0 {
labels = defaultLabels
}
for k, v := range labels {
kvs = append(kvs, k+"="+v)
}
sort.Strings(kvs)
args += " --labels=" + strings.Join(kvs, ",")
var platform []string
for k, v := range r.Platform {
if v == "" {
continue
}
platform = append(platform, k+"="+v)
}
if _, ok := r.Platform[ContainerImageKey]; !ok {
platform = append(platform, ContainerImageKey+"="+DefaultImage)
}
if platform != nil {
sort.Strings(platform)
args += " --platform=\"" + strings.Join(platform, ",") + "\""
}
strategy := r.ExecStrategy
if strategy == "" {
strategy = defaultExecStrategy
}
args += " --exec_strategy=" + strategy
if len(r.Inputs) > 0 {
args += " --inputs=" + strings.Join(r.Inputs, ",")
}
if r.RSPFile != "" {
args += " --input_list_paths=" + r.RSPFile
}
if len(r.OutputFiles) > 0 {
args += " --output_files=" + strings.Join(r.OutputFiles, ",")
}
if len(r.OutputDirectories) > 0 {
args += " --output_directories=" + strings.Join(r.OutputDirectories, ",")
}
if len(r.ToolchainInputs) > 0 {
args += " --toolchain_inputs=" + strings.Join(r.ToolchainInputs, ",")
}
return args + " -- "
}
// StaticRules returns a pair of rules based on the given RuleParams, where the first rule is a
// locally executable rule and the second rule is a remotely executable rule. commonArgs are args
// used for both the local and remotely executable rules. reArgs are used only for remote
// execution.
func StaticRules(ctx android.PackageContext, name string, ruleParams blueprint.RuleParams, reParams *REParams, commonArgs []string, reArgs []string) (blueprint.Rule, blueprint.Rule) {
ruleParamsRE := ruleParams
ruleParams.Command = strings.ReplaceAll(ruleParams.Command, "$reTemplate", "")
ruleParamsRE.Command = strings.ReplaceAll(ruleParamsRE.Command, "$reTemplate", reParams.Template())
return ctx.AndroidStaticRule(name, ruleParams, commonArgs...),
ctx.AndroidRemoteStaticRule(name+"RE", android.RemoteRuleSupports{RBE: true}, ruleParamsRE, append(commonArgs, reArgs...)...)
}
// MultiCommandStaticRules returns a pair of rules based on the given RuleParams, where the first
// rule is a locally executable rule and the second rule is a remotely executable rule. This
// function supports multiple remote execution wrappers placed in the template when commands are
// chained together with &&. commonArgs are args used for both the local and remotely executable
// rules. reArgs are args used only for remote execution.
func MultiCommandStaticRules(ctx android.PackageContext, name string, ruleParams blueprint.RuleParams, reParams map[string]*REParams, commonArgs []string, reArgs []string) (blueprint.Rule, blueprint.Rule) {
ruleParamsRE := ruleParams
for k, v := range reParams {
ruleParams.Command = strings.ReplaceAll(ruleParams.Command, k, "")
ruleParamsRE.Command = strings.ReplaceAll(ruleParamsRE.Command, k, v.Template())
}
return ctx.AndroidStaticRule(name, ruleParams, commonArgs...),
ctx.AndroidRemoteStaticRule(name+"RE", android.RemoteRuleSupports{RBE: true}, ruleParamsRE, append(commonArgs, reArgs...)...)
}
// EnvOverrideFunc retrieves a variable func that evaluates to the value of the given environment
// variable if set, otherwise the given default.
func EnvOverrideFunc(envVar, defaultVal string) func(ctx android.PackageVarContext) string {
return func(ctx android.PackageVarContext) string {
if override := ctx.Config().Getenv(envVar); override != "" {
return override
}
return defaultVal
}
}
|
package llsr
import (
"fmt"
"strings"
)
// Configuration for PostgreSQL connection.
type DatabaseConfig struct {
Database string
User string
Password string
Host string
Port int
}
// Creates new DatabaseConfiguration with given database name and User set to "postgres"
func NewDatabaseConfig(database string) *DatabaseConfig {
return &DatabaseConfig{
Database: database,
User: "postgres",
}
}
// Returns connection string that can be used in sql.Open
func (c *DatabaseConfig) ToConnectionString() string {
options := make([]string, 0)
if len(c.Database) > 0 {
options = append(options, fmt.Sprintf("dbname=%s", c.Database))
}
if len(c.User) > 0 {
options = append(options, fmt.Sprintf("user=%s", c.User))
}
if len(c.Password) > 0 {
options = append(options, fmt.Sprintf("password=%s", c.Password))
}
if len(c.Host) > 0 {
options = append(options, fmt.Sprintf("host=%s", c.Host))
}
if c.Port > 0 {
options = append(options, fmt.Sprintf("port=%d", c.Port))
}
options = append(options, "sslmode=disable")
return strings.Join(options, " ")
}
|
package main
import (
"encoding/binary"
"fmt"
"net"
"os"
"sync"
"time"
)
type numberOfVisitor struct {
number int32
lock sync.Mutex
}
func (nV *numberOfVisitor) increment() int32 {
nV.lock.Lock()
value:=nV.number
nV.number++
nV.lock.Unlock()
return value
}
func (nV *numberOfVisitor) getVisitors() int32{
return nV.number
}
func main() {
listener, err := net.Listen("tcp", ":5050")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
nV:=numberOfVisitor{}
fmt.Println("Server stated at ", time.Now().Format("Jan 2006 15:04:05"))
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
continue
}
fmt.Println("Client from IP", conn.RemoteAddr())
fmt.Println("Starting thread ", nV.getVisitors())
go handleConnection(conn, nV.increment())
}
}
func handleConnection(conn net.Conn, number int32) {
defer conn.Close()
err:= binary.Write(conn, binary.BigEndian, number)
if err != nil {
fmt.Println(err)
}
}
|
package frontservice
import (
"context"
calc "github.com/flexera/calc/front_service/gen/calc"
addersvc "github.com/flexera/calc/back_service/gen/calc"
adderclient "github.com/flexera/calc/front_service/services/adder"
)
// calc service example implementation.
// The example methods log the requests and return zero values.
type calcsrvc struct {
adderc adderclient.Client
}
// NewCalc returns the calc service implementation.
func NewCalc(adderc adderclient.Client) calc.Service {
return &calcsrvc{adderc}
}
// Add implements add.
func (s *calcsrvc) Add(ctx context.Context, p *calc.AddPayload) (res int, err error) {
return s.adderc.Add(ctx, &addersvc.AddPayload{
A: p.A,
B: p.B,
})
}
// Sub implements sub.
func (s *calcsrvc) Sub(ctx context.Context, p *calc.SubPayload) (res int, err error) {
return s.adderc.Sub(ctx, &addersvc.SubPayload{
A: p.A,
B: p.B,
})
}
// Mul implements mul.
func (s *calcsrvc) Mul(ctx context.Context, p *calc.MulPayload) (res int, err error) {
return s.adderc.Mul(ctx, &addersvc.MulPayload{
A: p.A,
B: p.B,
})
}
// Div implements div.
func (s *calcsrvc) Div(ctx context.Context, p *calc.DivPayload) (res float32, err error) {
return s.adderc.Div(ctx, &addersvc.DivPayload{
A: p.A,
B: p.B,
})
}
|
package main
import (
"fmt"
"time"
)
/**
* created: 2019/5/8 10:12
* By Will Fan
*/
func main() {
ch := make(chan int)
for i := 0; i <3; i++ {
go func(idx int) {
ch <- (idx + 1)*2
}(i)
}
fmt.Println(<-ch)
close(ch)
time.Sleep(2 * time.Second)
}
|
//-----------------------------------------------Paquetes E Imports-----------------------------------------------------
package Metodos
import (
"../Variables"
"bufio"
"fmt"
"github.com/gookit/color"
"os"
"strings"
)
//------------------------------------------------------Métodos---------------------------------------------------------
func LeerArchivoEntrada(Ruta string) (bool, []string) {
//Variables
var Archivo *os.File
var Scan *bufio.Scanner
var AvisoError error
var Extension []string
var LineasArchivo []string
var Cadena string
//Asignación
Ruta = Trim(Ruta)
Extension = make([]string, 0)
LineasArchivo = make([]string, 0)
Extension = SplitArchivo(Ruta)
if Extension[1] == "mia" {
Archivo, AvisoError = os.Open(Ruta)
//Catch Error
if AvisoError != nil {
color.HEX("#de4843", false).Println("Error Al Abrir El Archivo")
fmt.Println("")
return false, nil
}
Scan = bufio.NewScanner(Archivo)
//Leer Linea Por Linea
for Scan.Scan() {
Cadena += Trim(Scan.Text()) + "\n"
}
LineasArchivo = SplitContenidoArchivo(Cadena)
// Catch Error
if AvisoError = Scan.Err(); AvisoError != nil {
color.HEX("#de4843", false).Println("Error Al Abrir El Archivo")
fmt.Println("")
return false, nil
}
_ = Archivo.Close()
} else {
color.HEX("#de4843", false).Println("La Extension Del Archivo No Es La Correcta")
color.HEX("#de4843", false).Println("Extensión Válida: mia")
fmt.Println("")
return false, nil
}
return true, LineasArchivo
}
func LimpiarArreglo() {
for Contador := 0; Contador < len(Variables.ArregloArchivo); Contador++ {
Variables.ArregloArchivo[Contador] = ""
}
}
func RecuperarLDComando(ArregloAuxiliar []string) {
//Variables
var Final bool
var ContadorAuxiliar int
//Asignación
Final = false
ContadorAuxiliar = -1
//Limpiar Arreglo
LimpiarArreglo()
//Comienza Recuperación
for Con := 0; Con < len(ArregloAuxiliar); Con++ {
if Trim(ArregloAuxiliar[Con]) != "" {
if !Final {
ContadorAuxiliar++
Variables.ArregloArchivo[ContadorAuxiliar] = Trim(ArregloAuxiliar[Con])
} else {
if BuscarPrefijo(Trim(ArregloAuxiliar[Con])) {
Variables.ArregloArchivo[ContadorAuxiliar] = Variables.ArregloArchivo[ContadorAuxiliar] + " " + Trim(ArregloAuxiliar[Con])
} else {
Variables.ArregloArchivo[ContadorAuxiliar] = Variables.ArregloArchivo[ContadorAuxiliar] + Trim(ArregloAuxiliar[Con])
}
}
if BuscarSeparador(Trim(ArregloAuxiliar[Con])) {
Variables.ArregloArchivo[ContadorAuxiliar] = Trim(strings.Replace(Trim(Variables.ArregloArchivo[ContadorAuxiliar]), "\\*", "", 1))
Final = true
} else {
Final = false
}
}
}
}
|
package main
import "fmt"
func main() {
var sum int
var nums [5]int
fmt.Println("Length:", len(nums), "Capacity:", cap(nums))
for i := 0; i < 5; i++ {
var temp int
fmt.Scan(&temp)
nums[i] = temp
sum += temp
}
fmt.Printf("Arr:%v Type:%T Len:%v\n", nums, nums, len(nums))
fmt.Println("Sum of all elements:", sum)
fmt.Println("Length:", len(nums), "Capacity:", cap(nums))
}
|
/*
The goal of this challenge is to determine the angle of a line in a image.
Rules on the image:
The image background will be white (#FFFFFF)
The stroke of the line will be black (#000000)
The line will NOT be anti-aliased
The image will be 100x100 pixels
The line will start at the center of the image
The line will start pointing down (6-OClock)
The line will be 50 pixels long
The angle of the line will be measured going counterclockwise from the starting position
The image codec will be either .jpg or .png
Input format will be a file name passed by the command line arg, script input, or function arg. Output format is simple - just output the number of degrees (e.g. 90).
Answers can be ±1 degree of the stated measure. Here are a few example images:
Here is the code used to create the images (this is coded with Processing):
int deg = 45;
int centX = width/2, centY = height/2;
background(255);
noSmooth();
line(centX,
centY,
centX + sin(radians(deg))*50,
centY + cos(radians(deg))*50);
saveFrame("line-"+deg+".png");// image codec can be changed here. use '.png' or '.jpg'
*/
package main
import (
"bufio"
"flag"
"fmt"
"image"
"image/draw"
_ "image/png"
"log"
"math"
"os"
)
func main() {
flag.Parse()
if flag.NArg() != 1 {
usage()
}
m, err := readimage(flag.Arg(0))
check(err)
fmt.Println(detect(m))
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: [options] <image>")
flag.PrintDefaults()
os.Exit(2)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func readimage(name string) (*image.RGBA, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
br := bufio.NewReader(f)
m, _, err := image.Decode(br)
if err != nil {
return nil, err
}
r := m.Bounds()
p := image.NewRGBA(r)
draw.Draw(p, r, m, image.ZP, draw.Src)
return p, nil
}
func detect(m *image.RGBA) float64 {
p := image.Pt(math.MaxInt, math.MaxInt)
q := image.Pt(math.MinInt, math.MinInt)
r := m.Bounds()
for y := r.Min.Y; y < r.Max.Y; y++ {
for x := r.Min.X; x < r.Max.X; x++ {
c := m.RGBAAt(x, y)
if c.R != 0 || c.G != 0 || c.B != 0 {
continue
}
if p.Y > y || (p.Y == y && p.X > x) {
p = image.Pt(x, y)
}
if q.Y < y || (q.Y == y && q.X < x) {
q = image.Pt(x, y)
}
}
}
o := midpoint(r)
if distance(o, q) < distance(o, p) {
p, q = q, p
}
t := math.Atan2(float64(q.Y-p.Y), float64(q.X-p.X))
t = 360 - math.Mod(deg2rad(t)+270, 360)
if t >= 360 {
t -= 360
}
return t
}
func deg2rad(x float64) float64 {
return x * 180 / math.Pi
}
func distance(a, b image.Point) float64 {
return math.Hypot(float64(a.X-b.X), float64(a.Y-b.Y))
}
func midpoint(r image.Rectangle) image.Point {
return image.Pt(
(r.Min.X+r.Max.X)/2,
(r.Min.Y+r.Max.Y)/2,
)
}
|
package service
import (
"errors"
"github.com/Tanibox/tania-core/src/assets/domain"
"github.com/Tanibox/tania-core/src/assets/query"
"github.com/Tanibox/tania-core/src/assets/storage"
"github.com/gofrs/uuid"
)
type AreaServiceInMemory struct {
FarmReadQuery query.FarmReadQuery
ReservoirReadQuery query.ReservoirReadQuery
CropReadQuery query.CropReadQuery
}
func (s AreaServiceInMemory) FindFarmByID(uid uuid.UUID) (domain.AreaFarmServiceResult, error) {
result := <-s.FarmReadQuery.FindByID(uid)
if result.Error != nil {
return domain.AreaFarmServiceResult{}, result.Error
}
farm, ok := result.Result.(storage.FarmRead)
if !ok {
return domain.AreaFarmServiceResult{}, domain.AreaError{Code: domain.AreaErrorFarmNotFound}
}
if farm == (storage.FarmRead{}) {
return domain.AreaFarmServiceResult{}, domain.AreaError{Code: domain.AreaErrorFarmNotFound}
}
return domain.AreaFarmServiceResult{
UID: farm.UID,
Name: farm.Name,
}, nil
}
func (s AreaServiceInMemory) FindReservoirByID(reservoirUID uuid.UUID) (domain.AreaReservoirServiceResult, error) {
result := <-s.ReservoirReadQuery.FindByID(reservoirUID)
if result.Error != nil {
return domain.AreaReservoirServiceResult{}, result.Error
}
res, ok := result.Result.(storage.ReservoirRead)
if !ok {
return domain.AreaReservoirServiceResult{}, domain.AreaError{Code: domain.AreaErrorReservoirNotFound}
}
if res.UID == (uuid.UUID{}) {
return domain.AreaReservoirServiceResult{}, domain.AreaError{Code: domain.AreaErrorReservoirNotFound}
}
return domain.AreaReservoirServiceResult{
UID: res.UID,
Name: res.Name,
}, nil
}
func (s AreaServiceInMemory) CountCropsByAreaID(areaUID uuid.UUID) (int, error) {
result := <-s.CropReadQuery.CountCropsByArea(areaUID)
if result.Error != nil {
return 0, result.Error
}
totals, ok := result.Result.(query.CountAreaCropQueryResult)
if !ok {
return 0, errors.New("internal server error")
}
return totals.TotalCropBatch, nil
}
|
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 ladder
import (
"fmt"
"strconv"
"strings"
"sync"
"time"
proto "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider/common"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider/ladder/tasks"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/cloudprovider/template"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/utils"
"github.com/google/uuid"
)
var taskMgr sync.Once
func init() {
taskMgr.Do(func() {
cloudprovider.InitTaskManager(cloudName, newtask())
})
}
func newtask() *Task {
task := &Task{
works: make(map[string]interface{}),
}
// create nodeGroup
task.works[createNodePoolStep.StepMethod] = tasks.CreateNodePoolTask
// clean node task
task.works[removeNodesFromClusterStep.StepMethod] = tasks.RemoveNodesFromClusterTask
task.works[returnInstanceToResourcePoolStep.StepMethod] = tasks.ReturnInstanceToResourcePoolTask
// scale node task
task.works[applyCVMFromResourcePoolStep.StepMethod] = tasks.ApplyCVMFromResourcePoolTask
task.works[addNodesToClusterStep.StepMethod] = tasks.AddNodesToClusterTask
task.works[checkClusterNodeStatusStep.StepMethod] = tasks.CheckClusterNodeStatusTask
// task.works[resourcePoolLabelStep.StepMethod] = tasks.SetResourcePoolDeviceLabels
// delete nodeGroup task
task.works[checkCleanDBDataStep.StepMethod] = tasks.CheckCleanDBDataTask
return task
}
// Task background task manager
type Task struct {
works map[string]interface{}
}
// Name get cloudName
func (t *Task) Name() string {
return cloudName
}
// GetAllTask register all background task for worker running
func (t *Task) GetAllTask() map[string]interface{} {
return t.works
}
// BuildCreateVirtualClusterTask build create virtual cluster task
func (t *Task) BuildCreateVirtualClusterTask(cls *proto.Cluster,
opt *cloudprovider.CreateVirtualClusterOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildDeleteVirtualClusterTask build delete virtual cluster task
func (t *Task) BuildDeleteVirtualClusterTask(cls *proto.Cluster,
opt *cloudprovider.DeleteVirtualClusterOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildCreateNodeGroupTask build create node group task
func (t *Task) BuildCreateNodeGroupTask(group *proto.NodeGroup, opt *cloudprovider.CreateNodeGroupOption) (
*proto.Task, error) {
// yunti create nodeGroup steps
// step1: create underlying resourcePool and update nodeGroup relative info
// step2: deploy node group to cluster
// validate request params
if group == nil {
return nil, fmt.Errorf("BuildCreateNodeGroupTask group info empty")
}
if opt == nil || opt.Cluster == nil {
return nil, fmt.Errorf("BuildCreateNodeGroupTask TaskOptions is lost option or cluster")
}
err := opt.PoolInfo.Validate()
if err != nil {
return nil, err
}
nowStr := time.Now().Format(time.RFC3339)
task := &proto.Task{
TaskID: uuid.New().String(),
TaskType: cloudprovider.GetTaskType(cloudName, cloudprovider.CreateNodeGroup),
TaskName: cloudprovider.CreateNodeGroupTask.String(),
Status: cloudprovider.TaskStatusInit,
Message: "task initializing",
Start: nowStr,
Steps: make(map[string]*proto.Step),
StepSequence: make([]string, 0),
ClusterID: group.ClusterID,
ProjectID: group.ProjectID,
Creator: group.Creator,
Updater: group.Updater,
LastUpdate: nowStr,
CommonParams: make(map[string]string),
ForceTerminate: false,
NodeGroupID: group.NodeGroupID,
}
// generate taskName
taskName := fmt.Sprintf(createNodeGroupTaskTemplate, group.ClusterID, group.Name)
task.CommonParams[cloudprovider.TaskNameKey.String()] = taskName
// setting all steps details
createNodeGroupTask := &CreateNodeGroupOption{NodeGroup: group,
Cluster: opt.Cluster, PoolProvider: opt.PoolInfo.Provider, PoolID: opt.PoolInfo.ResourcePoolID}
// step1. call qcloud create node group
createNodeGroupTask.BuildCreateCloudNodeGroupStep(task)
// step2. ensure autoscaler(安装/更新CA组件) in cluster
common.BuildEnsureAutoScalerTaskStep(task, group.ClusterID, group.Provider)
// set current step
if len(task.StepSequence) == 0 {
return nil, fmt.Errorf("BuildCreateNodeGroupTask task StepSequence empty")
}
task.CurrentStep = task.StepSequence[0]
task.CommonParams[cloudprovider.JobTypeKey.String()] = cloudprovider.CreateNodeGroupJob.String()
return task, nil
}
// BuildCleanNodesInGroupTask clean specified nodes in NodeGroup
// including remove nodes from NodeGroup, clean data in nodes
func (t *Task) BuildCleanNodesInGroupTask(nodes []*proto.Node, group *proto.NodeGroup,
opt *cloudprovider.CleanNodesOption) (*proto.Task, error) {
// clean nodes in yunti only has two steps:
// 1. call LeaveClusterAndReturnCVM to clean cluster nodes
// 2. check cvm state and clean Node
// because cvms return to yunti resource pool, all clean works are handle by yunti
// we do little task here
// validate request params
if len(nodes) == 0 {
return nil, fmt.Errorf("BuildCleanNodesInGroupTask nodes info empty")
}
if group == nil {
return nil, fmt.Errorf("BuildCleanNodesInGroupTask group info empty")
}
if opt == nil || len(opt.Operator) == 0 || opt.Cluster == nil {
return nil, fmt.Errorf("BuildCleanNodesInGroupTask TaskOptions is lost")
}
var (
nodeIPs, nodeIDs, deviceIDs = make([]string, 0), make([]string, 0), make([]string, 0)
)
for _, node := range nodes {
nodeIPs = append(nodeIPs, node.InnerIP)
nodeIDs = append(nodeIDs, node.NodeID)
deviceIDs = append(deviceIDs, node.DeviceID)
}
// init task information
nowStr := time.Now().Format(time.RFC3339)
task := &proto.Task{
TaskID: uuid.New().String(),
TaskType: cloudprovider.GetTaskType(cloudName, cloudprovider.CleanNodeGroupNodes),
TaskName: cloudprovider.CleanNodesInGroupTask.String(),
Status: cloudprovider.TaskStatusInit,
Message: "task initializing",
Start: nowStr,
Steps: make(map[string]*proto.Step),
StepSequence: make([]string, 0),
ClusterID: group.ClusterID,
ProjectID: group.ProjectID,
Creator: opt.Operator,
Updater: opt.Operator,
LastUpdate: nowStr,
CommonParams: make(map[string]string),
ForceTerminate: false,
NodeGroupID: group.NodeGroupID,
NodeIPList: nodeIPs,
}
// generate taskName
taskName := fmt.Sprintf(cleanNodeGroupNodesTaskTemplate, group.ClusterID, group.Name)
task.CommonParams[cloudprovider.TaskNameKey.String()] = taskName
// setting all steps details
cleanTask := &CleanNodesInGroupTaskOption{
NodeGroup: group,
Cluster: opt.Cluster,
NodeIDs: nodeIDs,
NodeIPs: nodeIPs,
DeviceIDs: deviceIDs,
Operator: opt.Operator,
}
// step0: cluster cordon nodes
cleanTask.BuildCordonNodesStep(task)
// 业务自定义流程: 缩容前置流程支持 标准运维任务和执行业务job脚本
if group.NodeTemplate != nil && len(group.NodeTemplate.ScaleInPreScript) > 0 {
common.BuildJobExecuteScriptStep(task, common.JobExecParas{
ClusterID: opt.Cluster.ClusterID,
Content: group.NodeTemplate.ScaleInPreScript,
NodeIps: strings.Join(nodeIPs, ","),
Operator: opt.Operator,
StepName: common.PreInitStepJob,
AllowSkipJobTask: group.NodeTemplate.AllowSkipScaleInWhenFailed,
})
}
if group.NodeTemplate != nil && group.NodeTemplate.ScaleInExtraAddons != nil {
err := template.BuildSopsFactory{
StepName: template.UserPreInit,
Cluster: opt.Cluster,
Extra: template.ExtraInfo{
NodeIPList: strings.Join(nodeIPs, ","),
NodeOperator: opt.Operator,
ShowSopsUrl: true,
}}.BuildSopsStep(task, group.NodeTemplate.ScaleInExtraAddons, true)
if err != nil {
return nil, fmt.Errorf("BuildCleanNodesInGroupTask business BuildBkSopsStepAction failed: %v", err)
}
}
// platform clean sops task
if opt.Cloud != nil && opt.Cloud.NodeGroupManagement != nil && opt.Cloud.NodeGroupManagement.CleanNodesInGroup != nil {
err := template.BuildSopsFactory{
StepName: template.SystemInit,
Cluster: opt.Cluster,
Extra: template.ExtraInfo{
NodeIPList: strings.Join(nodeIPs, ","),
NodeOperator: opt.Operator,
ModuleID: cloudprovider.GetScaleInModuleID(opt.AsOption, group.NodeTemplate),
BusinessID: cloudprovider.GetBusinessID(opt.AsOption, group.NodeTemplate, false),
}}.BuildSopsStep(task, opt.Cloud.NodeGroupManagement.CleanNodesInGroup, true)
if err != nil {
return nil, fmt.Errorf("BuildCleanNodesInGroupTask business BuildBkSopsStepAction failed: %v", err)
}
}
// step1: cluster scale-in to clean nodes
cleanTask.BuildRemoveNodesStep(task)
// step2: cluster return nodes
cleanTask.BuildReturnNodesStep(task)
if len(task.StepSequence) > 0 {
task.CurrentStep = task.StepSequence[0]
}
// Job-type
task.CommonParams[cloudprovider.JobTypeKey.String()] = cloudprovider.CleanNodeGroupNodesJob.String()
task.CommonParams[cloudprovider.NodeIPsKey.String()] = strings.Join(nodeIPs, ",")
task.CommonParams[cloudprovider.NodeIDsKey.String()] = strings.Join(nodeIDs, ",")
return task, nil
}
// BuildUpdateDesiredNodesTask scale cluster nodes
func (t *Task) BuildUpdateDesiredNodesTask(desired uint32, group *proto.NodeGroup,
opt *cloudprovider.UpdateDesiredNodeOption) (*proto.Task, error) {
// validate request params
if desired == 0 {
return nil, fmt.Errorf("BuildUpdateDesiredNodesTask desired is zero")
}
if group == nil {
return nil, fmt.Errorf("BuildUpdateDesiredNodesTask group info empty")
}
if opt == nil || len(opt.Operator) == 0 || opt.Cluster == nil {
return nil, fmt.Errorf("BuildUpdateDesiredNodesTask TaskOptions is lost")
}
// init task information
nowStr := time.Now().Format(time.RFC3339)
task := &proto.Task{
TaskID: uuid.New().String(),
TaskType: cloudprovider.GetTaskType(cloudName, cloudprovider.UpdateNodeGroupDesiredNode),
TaskName: cloudprovider.UpdateDesiredNodesTask.String(),
Status: cloudprovider.TaskStatusInit,
Message: "task initializing",
Start: nowStr,
Steps: make(map[string]*proto.Step),
StepSequence: make([]string, 0),
ClusterID: group.ClusterID,
ProjectID: group.ProjectID,
Creator: opt.Operator,
Updater: opt.Operator,
LastUpdate: nowStr,
CommonParams: make(map[string]string),
ForceTerminate: false,
NodeGroupID: group.NodeGroupID,
}
// generate taskName
taskName := fmt.Sprintf(updateNodeGroupDesiredNodeTemplate, group.ClusterID, group.Name)
task.CommonParams[cloudprovider.TaskNameKey.String()] = taskName
// passwd := group.GetLaunchTemplate().GetInitLoginPassword()
passwd := utils.BuildInstancePwd()
task.CommonParams[cloudprovider.PasswordKey.String()] = passwd
updateDesiredNodes := &UpdateDesiredNodesTaskOption{
NodeGroup: group,
Cluster: opt.Cluster,
Desired: int(desired),
Operator: opt.Operator,
}
// step1: apply Instance from resourcePool
updateDesiredNodes.BuildApplyInstanceStep(task)
// step2: add Nodes to cluster
updateDesiredNodes.BuildAddNodesToClusterStep(task)
// step3: check nodes status
updateDesiredNodes.BuildCheckClusterNodeStatusStep(task)
// platform define sops task
if opt.Cloud != nil && opt.Cloud.NodeGroupManagement != nil && opt.Cloud.NodeGroupManagement.UpdateDesiredNodes != nil {
err := template.BuildSopsFactory{
StepName: template.SystemInit,
Cluster: opt.Cluster,
Extra: template.ExtraInfo{
InstancePasswd: passwd,
NodeIPList: "",
NodeOperator: opt.Operator,
ModuleID: cloudprovider.GetScaleOutModuleID(opt.Cluster, opt.AsOption, group.NodeTemplate, true),
BusinessID: cloudprovider.GetBusinessID(opt.AsOption, group.NodeTemplate, true),
}}.BuildSopsStep(task, opt.Cloud.NodeGroupManagement.UpdateDesiredNodes, false)
if err != nil {
return nil, fmt.Errorf("BuildScalingNodesTask platform BuildBkSopsStepAction failed: %v", err)
}
}
// 业务扩容节点后置自定义流程: 支持job后置脚本和标准运维任务
if group.NodeTemplate != nil && len(group.NodeTemplate.UserScript) > 0 {
common.BuildJobExecuteScriptStep(task, common.JobExecParas{
ClusterID: group.ClusterID,
Content: group.NodeTemplate.UserScript,
NodeIps: "",
Operator: opt.Operator,
StepName: common.PostInitStepJob,
AllowSkipJobTask: group.NodeTemplate.GetAllowSkipScaleOutWhenFailed(),
})
}
// business define sops task
if group.NodeTemplate != nil && group.NodeTemplate.ScaleOutExtraAddons != nil {
err := template.BuildSopsFactory{
StepName: template.UserAfterInit,
Cluster: opt.Cluster,
Extra: template.ExtraInfo{
InstancePasswd: passwd,
NodeIPList: "",
NodeOperator: opt.Operator,
ShowSopsUrl: true,
}}.BuildSopsStep(task, group.NodeTemplate.ScaleOutExtraAddons, false)
if err != nil {
return nil, fmt.Errorf("BuildScalingNodesTask business BuildBkSopsStepAction failed: %v", err)
}
}
// step3: annotation nodes
updateDesiredNodes.BuildNodeAnnotationsStep(task)
// step4: nodes common labels: sZoneID / bizID
updateDesiredNodes.BuildNodeCommonLabelsStep(task)
// step5: set resourcePool labels
updateDesiredNodes.BuildResourcePoolDeviceLabelStep(task)
// step6: unCordon nodes
updateDesiredNodes.BuildUnCordonNodesStep(task)
// set current step
if len(task.StepSequence) == 0 {
return nil, fmt.Errorf("BuildUpdateDesiredNodesTask task StepSequence empty")
}
task.CurrentStep = task.StepSequence[0]
// set common parameters && JobType
task.CommonParams[cloudprovider.ClusterIDKey.String()] = group.ClusterID
task.CommonParams[cloudprovider.ScalingNodesNumKey.String()] = strconv.Itoa(int(desired))
// Job-type
task.CommonParams[cloudprovider.JobTypeKey.String()] = cloudprovider.UpdateNodeGroupDesiredNodeJob.String()
task.CommonParams[cloudprovider.ManualKey.String()] = strconv.FormatBool(opt.Manual)
return task, nil
}
// BuildDeleteNodeGroupTask delete nodegroup
func (t *Task) BuildDeleteNodeGroupTask(group *proto.NodeGroup, nodes []*proto.Node,
opt *cloudprovider.DeleteNodeGroupOption) (*proto.Task, error) {
// validate request params
if group == nil {
return nil, fmt.Errorf("BuildDeleteNodeGroupTask group info empty")
}
if opt == nil || len(opt.Operator) == 0 || opt.Cloud == nil || opt.Cluster == nil {
return nil, fmt.Errorf("BuildDeleteNodeGroupTask TaskOptions is lost")
}
var (
nodeIPs, nodeIDs, deviceIDs = make([]string, 0), make([]string, 0), make([]string, 0)
)
for _, node := range nodes {
nodeIPs = append(nodeIPs, node.InnerIP)
nodeIDs = append(nodeIDs, node.NodeID)
deviceIDs = append(deviceIDs, node.DeviceID)
}
//init task information
nowStr := time.Now().Format(time.RFC3339)
task := &proto.Task{
TaskID: uuid.New().String(),
TaskType: cloudprovider.GetTaskType(cloudName, cloudprovider.DeleteNodeGroup),
TaskName: cloudprovider.DeleteNodeGroupTask.String(),
Status: cloudprovider.TaskStatusInit,
Message: "task initializing",
Start: nowStr,
Steps: make(map[string]*proto.Step),
StepSequence: make([]string, 0),
ClusterID: group.ClusterID,
ProjectID: group.ProjectID,
Creator: opt.Operator,
Updater: opt.Operator,
LastUpdate: nowStr,
CommonParams: make(map[string]string),
ForceTerminate: false,
NodeGroupID: group.NodeGroupID,
}
// generate taskName
taskName := fmt.Sprintf(deleteNodeGroupTaskTemplate, group.ClusterID, group.Name)
task.CommonParams[cloudprovider.TaskNameKey.String()] = taskName
cleanNodesTask := CleanNodesInGroupTaskOption{
NodeGroup: group,
Cluster: opt.Cluster,
NodeIDs: nodeIDs,
NodeIPs: nodeIPs,
DeviceIDs: deviceIDs,
Operator: opt.Operator,
}
// first clean nodegroup nodes if node group exist nodes
if len(nodeIDs) > 0 && len(nodeIPs) > 0 {
common.BuildCordonNodesTaskStep(task, opt.Cluster.ClusterID, nodeIPs)
// 业务自定义流程: 缩容前置流程支持 标准运维任务和执行业务job脚本
if group.NodeTemplate != nil && len(group.NodeTemplate.ScaleInPreScript) > 0 {
common.BuildJobExecuteScriptStep(task, common.JobExecParas{
ClusterID: opt.Cluster.ClusterID,
Content: group.NodeTemplate.ScaleInPreScript,
NodeIps: strings.Join(nodeIPs, ","),
Operator: opt.Operator,
StepName: common.PreInitStepJob,
})
}
// business define sops task
if group.NodeTemplate != nil && group.NodeTemplate.ScaleInExtraAddons != nil {
err := template.BuildSopsFactory{
StepName: template.UserPreInit,
Cluster: opt.Cluster,
Extra: template.ExtraInfo{
NodeIPList: strings.Join(nodeIPs, ","),
NodeOperator: opt.Operator,
ShowSopsUrl: true,
}}.BuildSopsStep(task, group.NodeTemplate.ScaleInExtraAddons, true)
if err != nil {
return nil, fmt.Errorf("BuildCleanNodesInGroupTask business BuildBkSopsStepAction failed: %v", err)
}
}
// platform clean sops task
if opt.Cloud != nil && opt.Cloud.NodeGroupManagement != nil && opt.Cloud.NodeGroupManagement.CleanNodesInGroup != nil {
err := template.BuildSopsFactory{
StepName: template.SystemInit,
Cluster: opt.Cluster,
Extra: template.ExtraInfo{
NodeIPList: strings.Join(nodeIPs, ","),
NodeOperator: opt.Operator,
ModuleID: cloudprovider.GetScaleInModuleID(opt.AsOption, group.NodeTemplate),
BusinessID: cloudprovider.GetBusinessID(opt.AsOption, group.NodeTemplate, false),
}}.BuildSopsStep(task, opt.Cloud.NodeGroupManagement.CleanNodesInGroup, true)
if err != nil {
return nil, fmt.Errorf("BuildCleanNodesInGroupTask business BuildBkSopsStepAction failed: %v", err)
}
}
// step1: cluster scale-in to clean nodes
cleanNodesTask.BuildRemoveNodesStep(task)
// step2: cluster return nodes
cleanNodesTask.BuildReturnNodesStep(task)
}
deleteNodeGroupOption := &DeleteNodeGroupOption{
NodeGroup: group,
Cluster: opt.Cluster,
NodeIDs: nodeIDs,
NodeIPs: nodeIPs,
Operator: opt.Operator,
}
// step3: previous call successful and delete local storage information
deleteNodeGroupOption.BuildCheckCleanDBDataStep(task)
// step4: delete nodeGroup from CA
common.BuildEnsureAutoScalerTaskStep(task, group.ClusterID, group.Provider)
// set current step
if len(task.StepSequence) == 0 {
return nil, fmt.Errorf("BuildDeleteNodeGroupTask task StepSequence empty")
}
task.CurrentStep = task.StepSequence[0]
// Job-type
task.CommonParams[cloudprovider.JobTypeKey.String()] = cloudprovider.DeleteNodeGroupJob.String()
task.CommonParams[cloudprovider.NodeIPsKey.String()] = strings.Join(nodeIPs, ",")
task.CommonParams[cloudprovider.NodeIDsKey.String()] = strings.Join(nodeIDs, ",")
return task, nil
}
// BuildCreateClusterTask build create cluster task
func (t *Task) BuildCreateClusterTask(cls *proto.Cluster, opt *cloudprovider.CreateClusterOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildImportClusterTask build import cluster task
func (t *Task) BuildImportClusterTask(cls *proto.Cluster, opt *cloudprovider.ImportClusterOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildDeleteClusterTask build delete cluster task
func (t *Task) BuildDeleteClusterTask(cls *proto.Cluster, opt *cloudprovider.DeleteClusterOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildAddNodesToClusterTask build addNodesToCluster task
func (t *Task) BuildAddNodesToClusterTask(cls *proto.Cluster, nodes []*proto.Node,
opt *cloudprovider.AddNodesOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildRemoveNodesFromClusterTask build removeNodesFromCluster task
func (t *Task) BuildRemoveNodesFromClusterTask(cls *proto.Cluster, nodes []*proto.Node,
opt *cloudprovider.DeleteNodesOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildMoveNodesToGroupTask build move nodes to group task
func (t *Task) BuildMoveNodesToGroupTask(nodes []*proto.Node, group *proto.NodeGroup,
opt *cloudprovider.MoveNodesOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildSwitchNodeGroupAutoScalingTask ensure auto scaler status and update nodegroup status to normal
func (t *Task) BuildSwitchNodeGroupAutoScalingTask(group *proto.NodeGroup, enable bool,
opt *cloudprovider.SwitchNodeGroupAutoScalingOption) (*proto.Task, error) {
// validate request params
if group == nil {
return nil, fmt.Errorf("BuildSwitchNodeGroupAutoScalingTask nodegroup info empty")
}
if opt == nil {
return nil, fmt.Errorf("BuildSwitchNodeGroupAutoScalingTask TaskOptions is lost")
}
nowStr := time.Now().Format(time.RFC3339)
task := &proto.Task{
TaskID: uuid.New().String(),
TaskType: cloudprovider.GetTaskType(cloudName, cloudprovider.SwitchNodeGroupAutoScaling),
TaskName: cloudprovider.SwitchNodeGroupAutoScalingTask.String(),
Status: cloudprovider.TaskStatusInit,
Message: "task initializing",
Start: nowStr,
Steps: make(map[string]*proto.Step),
StepSequence: make([]string, 0),
ClusterID: group.ClusterID,
ProjectID: group.ProjectID,
Creator: group.Creator,
Updater: group.Updater,
LastUpdate: nowStr,
CommonParams: make(map[string]string),
ForceTerminate: false,
NodeGroupID: group.NodeGroupID,
}
// generate taskName
taskName := fmt.Sprintf(switchNodeGroupAutoScalingTaskTemplate, group.ClusterID, group.Name)
task.CommonParams[cloudprovider.TaskNameKey.String()] = taskName
// step1. ensure auto scaler
common.BuildEnsureAutoScalerTaskStep(task, group.ClusterID, group.Provider)
// set current step
if len(task.StepSequence) == 0 {
return nil, fmt.Errorf("BuildSwitchNodeGroupAutoScalingTask task StepSequence empty")
}
task.CurrentStep = task.StepSequence[0]
task.CommonParams[cloudprovider.JobTypeKey.String()] = cloudprovider.SwitchNodeGroupAutoScalingJob.String()
return task, nil
}
// BuildAddExternalNodeToCluster add external to cluster
func (t *Task) BuildAddExternalNodeToCluster(group *proto.NodeGroup, nodes []*proto.Node,
opt *cloudprovider.AddExternalNodesOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildDeleteExternalNodeFromCluster remove external node from cluster
func (t *Task) BuildDeleteExternalNodeFromCluster(group *proto.NodeGroup, nodes []*proto.Node,
opt *cloudprovider.DeleteExternalNodesOption) (*proto.Task, error) {
return nil, cloudprovider.ErrCloudNotImplemented
}
// BuildUpdateAutoScalingOptionTask xxx
func (t *Task) BuildUpdateAutoScalingOptionTask(scalingOption *proto.ClusterAutoScalingOption,
opt *cloudprovider.UpdateScalingOption) (*proto.Task, error) {
// validate request params
if scalingOption == nil {
return nil, fmt.Errorf("BuildUpdateAutoScalingOptionTask scaling option info empty")
}
if opt == nil {
return nil, fmt.Errorf("BuildUpdateAutoScalingOptionTask TaskOptions is lost")
}
nowStr := time.Now().Format(time.RFC3339)
task := &proto.Task{
TaskID: uuid.New().String(),
TaskType: cloudprovider.GetTaskType(cloudName, cloudprovider.UpdateAutoScalingOption),
TaskName: cloudprovider.UpdateAutoScalingOptionTask.String(),
Status: cloudprovider.TaskStatusInit,
Message: "task initializing",
Start: nowStr,
Steps: make(map[string]*proto.Step),
StepSequence: make([]string, 0),
ClusterID: scalingOption.ClusterID,
ProjectID: scalingOption.ProjectID,
Creator: scalingOption.Creator,
Updater: scalingOption.Updater,
LastUpdate: nowStr,
CommonParams: make(map[string]string),
ForceTerminate: false,
}
// generate taskName
taskName := fmt.Sprintf(updateAutoScalingOptionTemplate, scalingOption.ClusterID)
task.CommonParams[cloudprovider.TaskNameKey.String()] = taskName
// setting all steps details
// step1. ensure auto scaler
common.BuildEnsureAutoScalerTaskStep(task, scalingOption.ClusterID, scalingOption.Provider)
// set current step
if len(task.StepSequence) == 0 {
return nil, fmt.Errorf("BuildUpdateAutoScalingOptionTask task StepSequence empty")
}
task.CurrentStep = task.StepSequence[0]
task.CommonParams[cloudprovider.JobTypeKey.String()] = cloudprovider.UpdateAutoScalingOptionJob.String()
return task, nil
}
// BuildSwitchAsOptionStatusTask xxx
func (t *Task) BuildSwitchAsOptionStatusTask(scalingOption *proto.ClusterAutoScalingOption,
enable bool, opt *cloudprovider.CommonOption) (*proto.Task, error) {
// validate request params
if scalingOption == nil {
return nil, fmt.Errorf("BuildSwitchAutoScalingOptionStatusTask scalingOption info empty")
}
if opt == nil {
return nil, fmt.Errorf("BuildSwitchAutoScalingOptionStatusTask TaskOptions is lost")
}
nowStr := time.Now().Format(time.RFC3339)
task := &proto.Task{
TaskID: uuid.New().String(),
TaskType: cloudprovider.GetTaskType(cloudName, cloudprovider.SwitchAutoScalingOptionStatus),
TaskName: cloudprovider.SwitchAutoScalingOptionStatusTask.String(),
Status: cloudprovider.TaskStatusInit,
Message: "task initializing",
Start: nowStr,
Steps: make(map[string]*proto.Step),
StepSequence: make([]string, 0),
ClusterID: scalingOption.ClusterID,
ProjectID: scalingOption.ProjectID,
Creator: scalingOption.Creator,
Updater: scalingOption.Updater,
LastUpdate: nowStr,
CommonParams: make(map[string]string),
ForceTerminate: false,
}
// generate taskName
taskName := fmt.Sprintf(switchAutoScalingOptionStatusTemplate, scalingOption.ClusterID)
task.CommonParams[cloudprovider.TaskNameKey.String()] = taskName
// setting all steps details
// step1. ensure auto scaler
common.BuildEnsureAutoScalerTaskStep(task, scalingOption.ClusterID, scalingOption.Provider)
// set current step
if len(task.StepSequence) == 0 {
return nil, fmt.Errorf("BuildSwitchAutoScalingOptionStatusTask task StepSequence empty")
}
task.CurrentStep = task.StepSequence[0]
task.CommonParams[cloudprovider.JobTypeKey.String()] = cloudprovider.SwitchAutoScalingOptionStatusJob.String()
return task, nil
}
// BuildUpdateNodeGroupTask when update nodegroup, we need to create background task,
func (t *Task) BuildUpdateNodeGroupTask(group *proto.NodeGroup, opt *cloudprovider.CommonOption) (*proto.Task, error) {
// validate request params
if group == nil {
return nil, fmt.Errorf("BuildUpdateNodeGroupTask group info empty")
}
if opt == nil {
return nil, fmt.Errorf("BuildUpdateNodeGroupTask TaskOptions is lost")
}
nowStr := time.Now().Format(time.RFC3339)
task := &proto.Task{
TaskID: uuid.New().String(),
TaskType: cloudprovider.GetTaskType(cloudName, cloudprovider.UpdateNodeGroup),
TaskName: cloudprovider.UpdateNodeGroupTask.String(),
Status: cloudprovider.TaskStatusInit,
Message: "task initializing",
Start: nowStr,
Steps: make(map[string]*proto.Step),
StepSequence: make([]string, 0),
ClusterID: group.ClusterID,
ProjectID: group.ProjectID,
Creator: group.Creator,
Updater: group.Updater,
LastUpdate: nowStr,
CommonParams: make(map[string]string),
ForceTerminate: false,
NodeGroupID: group.NodeGroupID,
}
// generate taskName
taskName := fmt.Sprintf(updateNodeGroupTaskTemplate, group.ClusterID, group.NodeGroupID)
task.CommonParams[cloudprovider.TaskNameKey.String()] = taskName
// setting all steps details
// step1. ensure auto scaler
common.BuildEnsureAutoScalerTaskStep(task, group.ClusterID, group.Provider)
// set current step
if len(task.StepSequence) == 0 {
return nil, fmt.Errorf("BuildUpdateNodeGroupTask task StepSequence empty")
}
task.CurrentStep = task.StepSequence[0]
task.CommonParams[cloudprovider.JobTypeKey.String()] = cloudprovider.UpdateNodeGroupJob.String()
return task, nil
}
|
// +build unit
package teampasswordmanager
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestCustomFields(t *testing.T) {
cf1 := CustomField{
Label: "one",
Data: "1",
}
cf2 := CustomField{
Label: "two",
Data: "2",
}
// Create a Password struct
password := Password{
CustomField1: cf1,
CustomField2: cf2,
}
// check the custom field array is returned
arrayCustomFields := password.CustomFields()
if arrayCustomFields[0] != cf1 ||
arrayCustomFields[1] != cf2 {
t.Errorf(
"Array of customfields not initialised correctly, expected (%s) and (%s) but array returned was (%s)",
cf1,
cf2,
arrayCustomFields,
)
}
}
func TestGetPasswordByID(t *testing.T) {
password := Password{
ID: 1,
Name: "postgres",
Project: Project{
ID: 2,
Name: "stage.devops__foo--bar",
},
Tags: "tag1, tag2",
Username: "username",
Password: "secretpassword",
}
passwordAsJSON, err := json.Marshal(password)
assertNoError(t, err)
server := httptest.NewServer(
http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.URL.String() == "/passwords/1.json" {
rw.Write([]byte(passwordAsJSON))
}
}))
// Close the server when test finishes
defer server.Close()
c := Client{
apiURL: server.URL + "/",
authToken: "1234",
httpClient: server.Client(),
}
output, err := c.GetPassword(1)
assertNoError(t, err)
if output != password {
t.Errorf("Expected (%s) but got (%s)", password.String(), output.String())
}
}
func TestGetPasswordByName(t *testing.T) {
// Create the test data and the server
pass1 := Password{
ID: 1,
Name: "postgres",
Project: Project{
ID: 2,
Name: "stage.devops__foo--bar",
},
Tags: "tag1, tag2",
Username: "username",
Password: "secretpassword",
}
pass2 := Password{
ID: 2,
Name: "foo",
Project: Project{
ID: 3,
Name: "bar",
},
Tags: "tag1, tag2",
Username: "username",
Password: "secretpassword",
}
passwordList := []Password{}
passwordList = append(passwordList, pass1)
passwordList = append(passwordList, pass2)
passwordListAsJSON, err := json.Marshal(passwordList)
assertNoError(t, err)
passwordTwoAsJSON, err := json.Marshal(pass2)
assertNoError(t, err)
server := httptest.NewServer(
http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// Test request parameters
if req.URL.String() == "/passwords.json" {
rw.Write([]byte(passwordListAsJSON))
} else if req.URL.String() == "/passwords/2.json" {
rw.Write([]byte(passwordTwoAsJSON))
} else {
panic("Unexpected url requested: " + req.URL.String())
}
}))
// Close the server when test finishes
defer server.Close()
c := Client{
apiURL: server.URL + "/",
authToken: "1234",
httpClient: server.Client(),
}
// should return password 2
output, err := c.GetPasswordByName("foo", "bar")
assertNoError(t, err)
if output != pass2 {
t.Errorf("Expected (%s) but got (%s)", pass2.String(), output.String())
}
}
func TestGetCustomFieldByName(t *testing.T) {
pass1 := Password{
ID: 1,
Name: "postgres",
Project: Project{
ID: 2,
Name: "stage.devops__foo--bar",
},
Tags: "tag1, tag2",
Username: "username",
Password: "secretpassword",
CustomField1: CustomField{
Label: "bar",
Data: "baz",
},
}
output, err := pass1.CustomField("foo")
assert(t, output == "", "Output was not equal to nothing")
assert(t, err != nil, "Error was not returned")
output, err = pass1.CustomField("bar")
assert(t, output == "baz", "Output was not equal to the value of the data for this label")
assert(t, err == nil, "Error should be nil")
}
|
/*
Copyright 2019 The Kubernetes 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 v1alpha1
import (
"errors"
"sync"
)
const (
// NotFound is the not found error message.
NotFound = "not found"
)
// StateData is a generic type for arbitrary data stored in CycleState.
type StateData interface {
// Clone is an interface to make a copy of StateData. For performance reasons,
// clone should make shallow copies for members (e.g., slices or maps) that are not
// impacted by PreFilter's optional AddPod/RemovePod methods.
Clone() StateData
}
// StateKey is the type of keys stored in CycleState.
type StateKey string
// CycleState provides a mechanism for plugins to store and retrieve arbitrary data.
// StateData stored by one plugin can be read, altered, or deleted by another plugin.
// CycleState does not provide any data protection, as all plugins are assumed to be
// trusted.
type CycleState struct {
mx sync.RWMutex
storage map[StateKey]StateData
// if recordPluginMetrics is true, PluginExecutionDuration will be recorded for this cycle.
recordPluginMetrics bool
}
// NewCycleState initializes a new CycleState and returns its pointer.
func NewCycleState() *CycleState {
return &CycleState{
storage: make(map[StateKey]StateData),
}
}
// ShouldRecordPluginMetrics returns whether PluginExecutionDuration metrics should be recorded.
func (c *CycleState) ShouldRecordPluginMetrics() bool {
if c == nil {
return false
}
return c.recordPluginMetrics
}
// SetRecordPluginMetrics sets recordPluginMetrics to the given value.
func (c *CycleState) SetRecordPluginMetrics(flag bool) {
if c == nil {
return
}
c.recordPluginMetrics = flag
}
// Clone creates a copy of CycleState and returns its pointer. Clone returns
// nil if the context being cloned is nil.
func (c *CycleState) Clone() *CycleState {
if c == nil {
return nil
}
copy := NewCycleState()
for k, v := range c.storage {
copy.Write(k, v.Clone())
}
return copy
}
// Read retrieves data with the given "key" from CycleState. If the key is not
// present an error is returned.
// This function is not thread safe. In multi-threaded code, lock should be
// acquired first.
func (c *CycleState) Read(key StateKey) (StateData, error) {
if v, ok := c.storage[key]; ok {
return v, nil
}
return nil, errors.New(NotFound)
}
// Write stores the given "val" in CycleState with the given "key".
// This function is not thread safe. In multi-threaded code, lock should be
// acquired first.
func (c *CycleState) Write(key StateKey, val StateData) {
c.storage[key] = val
}
// Delete deletes data with the given key from CycleState.
// This function is not thread safe. In multi-threaded code, lock should be
// acquired first.
func (c *CycleState) Delete(key StateKey) {
delete(c.storage, key)
}
// Lock acquires CycleState lock.
func (c *CycleState) Lock() {
c.mx.Lock()
}
// Unlock releases CycleState lock.
func (c *CycleState) Unlock() {
c.mx.Unlock()
}
// RLock acquires CycleState read lock.
func (c *CycleState) RLock() {
c.mx.RLock()
}
// RUnlock releases CycleState read lock.
func (c *CycleState) RUnlock() {
c.mx.RUnlock()
}
|
package list
import "errors"
type ListNode struct {
data interface{}
next *ListNode
}
type SingleList struct {
root *ListNode
}
func (l *SingleList) AddNode(value interface{}) {
if nil == value {
return
}
newNode := &ListNode{
data: value,
}
if nil == l.root {
l.root = newNode
return
}
tmpNode := l.root
for nil != tmpNode.next {
tmpNode = tmpNode.next
}
tmpNode.next = newNode
}
// 删除尾部
func (l *SingleList) Remove() {
tmpNode := l.root
for nil != tmpNode.next && nil != tmpNode.next.next {
tmpNode = tmpNode.next
}
tmpNode.next = nil
}
// 链表的删除需要之前删除节点的前驱节点
// 删除的时候要先连再断 (既先将前驱节点与这个节点的后继节点相连接)
func (l *SingleList) RemoveByValue(value interface{}) (bool, error) {
tmpNode := l.root
if tmpNode.data == value {
l.root = tmpNode.next
return true, nil
}
for tmpNode.next != nil && tmpNode.next.data != value {
tmpNode = tmpNode.next
}
// tmpNode.next=nil | tmpNode.next.value=value
if nil == tmpNode.next {
return false, errors.New("元素不存在")
}
tmpNode.next = tmpNode.next.next
return true, nil
}
func (l *SingleList) RemoveByIndex(index int) (bool, error) {
if index <= 0 {
return false, errors.New("no such index,根节点从1开始算起")
} else if index == 1 {
l.root = l.root.next
return true, nil
}
tmpNode := l.root
// 获取他的前驱节点
for i := 1; i < index-1; i++ {
if nil == tmpNode.next {
// 不额外定义一个变量来判断
return false, errors.New("index超过链表的长度")
}
}
tmpNode.next = tmpNode.next.next
return true, nil
}
func (l *SingleList) IteratorNode() []interface{} {
values := make([]interface{}, 0)
tmpNode := l.root
for nil != tmpNode {
values = append(values, tmpNode.data)
tmpNode = tmpNode.next
}
return values
}
|
package user
import (
. "cms/structs"
"cms/database/mysql"
log "github.com/sirupsen/logrus"
)
func GetUserByName(username string) (user User) {
user, err := mysql.FindUserByName(username)
if err != nil {
log.Error(err)
}
return
}
|
package etcd
import (
"time"
etctClient "github.com/coreos/etcd/clientv3"
"os"
"github.com/astaxie/beego/logs"
"context"
"fmt"
)
var (
client *etctClient.Client
)
func InitEtcd(Endpoint []string) (err error) {
client, err = etctClient.New(etctClient.Config{Endpoints: Endpoint,
DialTimeout: 5 * time.Second})
if os.IsExist(err) {
logs.Error(err)
return
}
logs.Info("etcd connect success")
return
}
func PutToEtcd(topic,msg string) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
cancel()
res, err := client.Put(ctx, topic, msg)
if os.IsExist(err) {
panic(err)
logs.Error("put etcd fail", topic, msg)
}
fmt.Printf("put etcd topic==%v msg:=====%v\n",topic,msg)
fmt.Println(res.OpResponse(),"================")
}
|
/*
Copyright 2017 The Kubernetes 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 validate
import (
"github.com/kubernetes-sigs/cri-tools/pkg/framework"
internalapi "k8s.io/cri-api/pkg/apis"
runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
. "github.com/onsi/ginkgo"
)
var _ = framework.KubeDescribe("Streaming", func() {
f := framework.NewDefaultCRIFramework()
var rc internalapi.RuntimeService
var ic internalapi.ImageManagerService
BeforeEach(func() {
rc = f.CRIClient.CRIRuntimeClient
ic = f.CRIClient.CRIImageClient
})
Context("runtime should support streaming interfaces", func() {
var podID string
AfterEach(func() {
By("stop PodSandbox")
rc.StopPodSandbox(podID)
By("delete PodSandbox")
rc.RemovePodSandbox(podID)
})
It("runtime should support portforward in host network", func() {
By("create a PodSandbox with container port port mapping in host network")
var podConfig *runtimeapi.PodSandboxConfig
portMappings := []*runtimeapi.PortMapping{
{
ContainerPort: webServerHostNetContainerPort,
},
}
podID, podConfig = createPodSandboxWithPortMapping(rc, portMappings, true)
By("create a web server container")
containerID := createHostNetWebServerContainer(rc, ic, podID, podConfig, "container-for-host-net-portforward-test")
By("start the web server container")
startContainer(rc, containerID)
req := createDefaultPortForward(rc, podID)
By("check the output of portforward")
checkPortForward(rc, req, webServerHostPortForHostNetPortFroward, webServerHostNetContainerPort)
})
})
})
|
package notion
// Pagination allows an integration to request a part of the list, receiving an array of results and a next_cursor in the response.
// The integration can use the next_cursor in another request to receive the next part of the list.
type Pagination struct {
NextCursor string `json:"next_cursor,omitempty"`
HasMore bool `json:"has_more"`
}
|
// Copyright 2018 Kuei-chun Chen. All rights reserved.
package util
import (
"reflect"
"testing"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func TestCloneDoc(t *testing.T) {
var edoc = bson.M{"name": "keyhole"}
var doc = bson.M{"_id": primitive.NewObjectID(), "sub": edoc}
newDoc := CloneDoc(doc)
if reflect.DeepEqual(doc["sub"], newDoc["sub"]) {
t.Fatal()
}
}
|
package main
import (
"log"
"os"
"github.com/adrg/xdg"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
const (
SettingsPath = "MasterPlan/settings08.json"
SettingsLegacyPath = "masterplan-settings08.json"
SettingsTheme = "Theme"
SettingsWindowPosition = "WindowPosition"
SettingsSaveWindowPosition = "SaveWindowPosition"
SettingsCustomFontPath = "CustomFontPath"
SettingsTargetFPS = "TargetFPS"
SettingsUnfocusedFPS = "UnfocusedFPS"
SettingsBorderlessWindow = "BorderlessWindow"
SettingsOutlineWindow = "OutlineWindow"
SettingsAlwaysShowNumbering = "AlwaysShowNumbering"
SettingsNumberTopLevelCards = "NumberTopLevelCards"
SettingsDisplayMessages = "DisplayMessages"
SettingsDoubleClickMode = "DoubleClickMode"
SettingsShowGrid = "ShowGrid"
SettingsFlashSelected = "FlashSelected"
SettingsFocusOnElapsedTimers = "FocusOnElapsedTimers"
SettingsNotifyOnElapsedTimers = "NotifyOnElapsedTimers"
SettingsPlayAlarmSound = "PlayAlarmSound"
SettingsShowAboutDialogOnStart = "ShowAboutDialogOnStart"
SettingsReversePan = "ReversePan"
SettingsAutoLoadLastProject = "AutoLoadLastProject"
SettingsScreenshotPath = "ScreenshotPath"
SettingsSmoothMovement = "SmoothMovement"
SettingsFocusOnSelectingWithKeys = "FocusOnSelectingWithKeys"
SettingsWindowTransparency = "Window Transparency"
SettingsWindowTransparencyMode = "Transparency Mode"
SettingsFocusOnUndo = "FocusOnUndo"
SettingsSuccessfulLoad = "SuccesfulLoad"
SettingsAutoBackup = "Automatic Backups"
SettingsAutoBackupTime = "Backup Timer"
SettingsMaxAutoBackups = "Max Automatic Backup Count"
SettingsMouseWheelSensitivity = "Mouse Wheel Sensitivity"
SettingsZoomToCursor = "Zoom to Cursor"
SettingsCardShadows = "Card Shadows"
SettingsFlashDeadlines = "Flash Deadlines"
SettingsDeadlineDisplay = "Display Deadlines As"
SettingsMaxInternalImageSize = "Max Internal Image Buffer Size"
SettingsPlaceNewCardsInStack = "Position New Cards in Stack"
SettingsHideGridOnZoomOut = "Hide Grid on Zoom out"
SettingsDisplayNumberedPercentagesAs = "Display Numbered Percentages"
SettingsShowTableHeaders = "Display Table Headers"
// SettingsCacheAudioBeforePlayback = "Cache Audio Before Playback"
SettingsAudioVolume = "AudioVolume"
SettingsAudioBufferSize = "Audio Playback Buffer Size"
SettingsAudioSampleRate = "Audio Playback Sample Rate"
DeadlineDisplayCountdown = "Days"
DeadlineDisplayDate = "Date"
DeadlineDisplayIcons = "Icons"
DoubleClickLast = "Creates card of prev. type"
DoubleClickCheckbox = "Creates Checkbox card"
DoubleClickNothing = "Does nothing"
WindowTransparencyNever = "Never"
WindowTransparencyAlways = "Always"
WindowTransparencyMouse = "When mouse is outside window"
WindowTransparencyWindow = "When window is inactive"
)
const (
NumberedPercentagePercent = "Percent"
NumberedPercentageOff = "Off"
NumberedPercentageCurrentMax = "X / Y"
)
const (
Percentage10 = "10%"
Percentage25 = "25%"
Percentage50 = "50%"
Percentage75 = "75%"
Percentage100 = "100%"
Percentage150 = "150%"
Percentage200 = "200%"
Percentage300 = "300%"
Percentage400 = "400%"
Percentage800 = "800%"
)
const (
AudioSampleRate11025 = "11025"
AudioSampleRate22050 = "22050"
AudioSampleRate44100 = "44100"
AudioSampleRate48000 = "48000"
AudioSampleRate88200 = "88200"
AudioSampleRate96000 = "96000"
// AudioSampleRate192000 = "192000"
)
const (
AudioBufferSize32 = "32"
AudioBufferSize64 = "64"
AudioBufferSize128 = "128"
AudioBufferSize256 = "256"
AudioBufferSize512 = "512"
AudioBufferSize1024 = "1024"
AudioBufferSize2048 = "2048"
AudioBufferSize4096 = "4096"
AudioBufferSize8192 = "8192"
AudioBufferSize16384 = "16384"
)
var percentageToNumber map[string]float32 = map[string]float32{
Percentage10: 0.1,
Percentage25: 0.25,
Percentage50: 0.5,
Percentage75: 0.75,
Percentage100: 1,
Percentage150: 1.5,
Percentage200: 2,
Percentage300: 3,
Percentage400: 4,
Percentage800: 8,
}
const (
ImageBufferSize512 = "512"
ImageBufferSize1024 = "1024"
ImageBufferSize2048 = "2048"
ImageBufferSize4096 = "4096"
ImageBufferSize8192 = "8192"
ImageBufferSize16384 = "16384"
ImageBufferSizeMax = "Max"
)
const (
TableHeadersSelected = "Selected"
TableHeadersHover = "Hovering"
TableHeadersAlways = "Always"
)
func NewProgramSettings() *Properties {
// We're setting the defaults here; after setting them, we'll attempt to load settings from a preferences file below
props := NewProperties()
props.Get(SettingsTheme).Set("Moonlight")
props.Get(SettingsTargetFPS).Set(60.0)
props.Get(SettingsUnfocusedFPS).Set(60.0)
props.Get(SettingsDisplayMessages).Set(true)
props.Get(SettingsDoubleClickMode).Set(DoubleClickLast)
props.Get(SettingsShowGrid).Set(true)
props.Get(SettingsSaveWindowPosition).Set(true)
props.Get(SettingsFlashSelected).Set(true)
props.Get(SettingsFocusOnElapsedTimers).Set(false)
props.Get(SettingsNotifyOnElapsedTimers).Set(true)
props.Get(SettingsPlayAlarmSound).Set(true)
props.Get(SettingsShowAboutDialogOnStart).Set(true)
props.Get(SettingsReversePan).Set(false)
props.Get(SettingsCustomFontPath).Set("")
props.Get(SettingsScreenshotPath).Set("")
props.Get(SettingsAutoLoadLastProject).Set(false)
props.Get(SettingsSmoothMovement).Set(true)
props.Get(SettingsNumberTopLevelCards).Set(true)
props.Get(SettingsFocusOnSelectingWithKeys).Set(true)
props.Get(SettingsFocusOnUndo).Set(true)
props.Get(SettingsOutlineWindow).Set(false)
props.Get(SettingsAutoBackup).Set(true)
props.Get(SettingsAutoBackupTime).Set(10.0)
props.Get(SettingsMaxAutoBackups).Set(6.0)
props.Get(SettingsMouseWheelSensitivity).Set(Percentage100)
props.Get(SettingsZoomToCursor).Set(true)
props.Get(SettingsCardShadows).Set(true)
props.Get(SettingsFlashDeadlines).Set(true)
props.Get(SettingsMaxInternalImageSize).Set(ImageBufferSize2048)
props.Get(SettingsPlaceNewCardsInStack).Set(false)
props.Get(SettingsHideGridOnZoomOut).Set(true)
props.Get(SettingsDisplayNumberedPercentagesAs).Set(NumberedPercentagePercent)
props.Get(SettingsShowTableHeaders).Set(TableHeadersSelected)
// Audio settings; not shown in MasterPlan because it's very rarely necessary to tweak
props.Get(SettingsAudioVolume).Set(80.0)
props.Get(SettingsAudioSampleRate).Set(AudioSampleRate44100)
props.Get(SettingsAudioBufferSize).Set(AudioBufferSize512)
transparency := props.Get(SettingsWindowTransparency)
transparency.Set(1.0)
transparency.OnChange = func() {
globals.WindowTargetTransparency = transparency.AsFloat()
}
props.Get(SettingsWindowTransparencyMode).Set(WindowTransparencyNever)
borderless := props.Get(SettingsBorderlessWindow)
borderless.Set(false)
borderless.OnChange = func() {
if globals.Window != nil {
globals.Window.SetBordered(!borderless.AsBool())
}
}
path, _ := xdg.ConfigFile(SettingsPath)
// Attempt to load the properties here
if FileExists(path) {
jsonData, err := os.ReadFile(path)
if err != nil {
panic(err)
}
globals.SettingsLoaded = true
data := gjson.Get(string(jsonData), "properties").String()
props.Deserialize(data)
recentFiles := gjson.Get(string(jsonData), "recent files")
if recentFiles.Exists() {
array := recentFiles.Array()
for i := 0; i < len(array); i++ {
globals.RecentFiles = append(globals.RecentFiles, array[i].String())
}
}
globals.Keybindings.Deserialize(string(jsonData))
}
props.OnChange = func(property *Property) {
SaveSettings()
}
return props
}
func SaveSettings() {
path, _ := xdg.ConfigFile(SettingsPath)
saveData, _ := sjson.Set("{}", "version", globals.Version.String())
saveData, _ = sjson.SetRaw(saveData, "properties", globals.Settings.Serialize())
saveData, _ = sjson.Set(saveData, "recent files", globals.RecentFiles)
saveData, _ = sjson.SetRaw(saveData, "keybindings", globals.Keybindings.Serialize())
saveData = gjson.Get(saveData, "@pretty").String()
if file, err := os.Create(path); err != nil {
log.Println(err)
} else {
file.Write([]byte(saveData))
file.Close()
}
}
// func (ps *OldProgramSettings) CleanUpRecentPlanList() {
// newList := []string{}
// for i, s := range ps.RecentPlanList {
// _, err := os.Stat(s)
// if err == nil {
// newList = append(newList, ps.RecentPlanList[i]) // We could alter the slice to cut out the strings that are invalid, but this is visually cleaner and easier to understand
// }
// }
// ps.RecentPlanList = newList
// }
|
package protocol
import (
"io/ioutil"
"net"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("InstructionIO", func() {
var server, client net.Conn
var io *InstructionIO
BeforeEach(func() {
server, client = net.Pipe()
io = NewInstructionIO(client)
})
AfterEach(func() {
client.Close()
server.Close()
})
It("formats and sends the instruction", func() {
ins := NewInstruction("hello", "ग्वाकोमोल")
go func() {
io.Write(ins)
io.Close()
}()
Expect(ioutil.ReadAll(server)).To(Equal([]byte("5.hello,9.ग्वाकोमोल;")))
})
It("reads and parses received instruction", func() {
msg1 := "5.hello,9.ग्वाकोमोल;"
msg2 := "5.empty,0.;"
go func() {
server.Write([]byte(msg1))
server.Write([]byte(msg2))
server.Close()
}()
ins1, err1 := io.Read()
Expect(err1).To(BeNil())
Expect(ins1.String()).To(Equal(msg1))
ins2, err2 := io.Read()
Expect(err2).To(BeNil())
Expect(ins2.String()).To(Equal(msg2))
})
})
|
package sqlite
import _ "github.com/mattn/go-sqlite3" // Import the sqlite driver.
|
package uptimed
import "sort"
func GetStats() (stats *Stats, err error) {
var records *Records
var yesterday *Record
stats = new(Stats)
stats.Score, err = GetScore()
if err != nil {
return nil, err
}
records, err = GetRecords()
if err != nil {
return nil, err
}
sort.Sort(BySince(*records))
yesterday = (*records)[len(*records)-2]
stats.Average = int64(yesterday.Average)
stats.Trend = int64(yesterday.Trend)
stats.Total = 0
for _, r := range *records {
stats.Total += r.Uptime
}
return
}
|
/*
Create a for loop using this syntax
for condition { }
Have it print out the years you have been alive.
*/
package main
import "fmt"
func main() {
for birthYear := 1992; birthYear <= 2021; birthYear++ {
fmt.Println(birthYear)
}
}
|
package cache
import (
"fmt"
)
type FormatManager interface {
Save(entries *[]DBCacheEntry, path string) error
}
// available formatters - lazy loaded formatters
var availableFormatters = map[string]func() FormatManager{
"csv": GetSingletonCSVFormatter,
"parquet": GetSingletonParquetFormatter,
}
func GetFormatter(formatterType string) (FormatManager, error) {
// return an instance of FormatManager if it exists
if singleton, ok := availableFormatters[formatterType]; ok {
return singleton(), nil
}
return nil, fmt.Errorf("Impossible to find specified formatter %s", formatterType)
}
|
package main
import "fmt"
func main() {
arrays := []int{1,232,545,12,56,12,10}
input := 10
for i,num := range arrays {
if num == input {
fmt.Println("value : ",num)
fmt.Println("Index",i)
arrays = RemoveIndex(arrays, i)
}
}
fmt.Println(arrays)
}
func RemoveIndex(s []int, index int) []int {
return append(s[:index], s[index+1:]...)
}
|
package main
import "fmt"
func lessThanTen(i int) (response string, error string) {
if i < 10 {
response = "The number is less than 10"
error = ""
} else {
response = "The number is too big"
error = "ERROR: hit an error"
}
return response, error
}
func main() {
result, err := lessThanTen(5)
if err != "" {
fmt.Println(err)
return
}
fmt.Println(result)
} |
package iirepo
import (
"os"
)
// Init creates the (hidden) .ii/ repo directory, if it doesn't exist, under ‘rootpath’.
func Init(rootpath string) error {
repopath := Path(rootpath)
if err := os.MkdirAll(repopath, os.ModePerm); nil != err {
return err
}
return nil
}
|
package chat
import (
"github.com/sirupsen/logrus"
"net/http"
"simple_websocket/internal/handlers"
)
//Конфигурация логгирования
func (chat *Chat) configLogger() error {
log_level, err := logrus.ParseLevel(chat.config.LoggerLevel)
if err != nil {
chat.logger.SetLevel(log_level)
return nil
}
return err
}
// configRoutes конфигурируем роутинг
func (chat *Chat) configRoutes() {
chat.routes.Get("/", http.HandlerFunc(handlers.Home))
chat.routes.Get("/ws", http.HandlerFunc(handlers.WsEndpoint))
fileServer := http.FileServer(http.Dir("./static"))
chat.routes.Get("/static/", http.StripPrefix("/static", fileServer))
} |
// 匿名字段也可以进行嵌套和继承
package main
import "fmt"
type A struct {
name string
Age int
}
type B struct {
A
int // 匿名字段~~
n int
}
func main() {
var b B
b.int = 20 // 如何使用匿名字段~~~
b.n = 15 // n是int类型的变量~~ 引用的话也得直接说明
fmt.Printf("匿名字段int=[%v]\nint变量n=[%v]", b.int, b.n)
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//739. Daily Temperatures
//Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
//For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
//Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
//func dailyTemperatures(temperatures []int) []int {
//}
// Time Is Money |
package awssqs
import (
"fmt"
"time"
)
// the maximum number of messages in a block
var MAX_SQS_BLOCK_COUNT = uint(10)
// the maximum size of a block
var MAX_SQS_BLOCK_SIZE = uint(262144)
// the maximum size of a message
var MAX_SQS_MESSAGE_SIZE = MAX_SQS_BLOCK_SIZE
// the maximum queue wait time (in seconds)
var MAX_SQS_WAIT_TIME = uint(20)
// Errors
var ErrBlockCountTooLarge = fmt.Errorf("block count is too large. Must be %d or less", MAX_SQS_BLOCK_COUNT)
var ErrBlockTooLarge = fmt.Errorf("block size is too large. Must be %d or less", MAX_SQS_BLOCK_SIZE)
var ErrMessageTooLarge = fmt.Errorf("message size is too large. Must be %d or less", MAX_SQS_MESSAGE_SIZE)
var ErrWaitTooLarge = fmt.Errorf("wait time is too large. Must be %d or less", MAX_SQS_WAIT_TIME)
var ErrBadQueueName = fmt.Errorf("queue name does not exist")
var ErrBadQueueHandle = fmt.Errorf("queue handle is bad")
var ErrOneOrMoreOperationsUnsuccessful = fmt.Errorf("one or more operations were not successful")
var ErrBadReceiptHandle = fmt.Errorf("receipt handle format is incorrect for large message support")
var ErrMismatchedContentsSize = fmt.Errorf("actual S3 message size differs from expected size")
var ErrMissingConfiguration = fmt.Errorf("configuration information is incomplete")
// standard attribute keys and values
var AttributeKeyRecordId = "id"
var AttributeKeyRecordType = "type"
var AttributeKeyRecordSource = "source"
var AttributeKeyRecordOperation = "operation"
var AttributeValueRecordTypeB64Marc = "base64/marc"
var AttributeValueRecordTypeXml = "xml"
var AttributeValueRecordOperationUpdate = "update"
var AttributeValueRecordOperationDelete = "delete"
// simplifications
type QueueHandle string
type ReceiptHandle string
type OpStatus bool
// just a KV pair
type Attribute struct {
Name string
Value string
}
type Attributes []Attribute
type Message struct {
Attribs Attributes
ReceiptHandle ReceiptHandle
FirstSent uint64 // epoch time (http://en.wikipedia.org/wiki/Unix_time)
FirstReceived uint64 // epoch time (http://en.wikipedia.org/wiki/Unix_time)
Payload []byte
Incomplete bool // this message is incomplete and may be handled differently
// used by the implementation
oversize bool // this is an oversize message and is handled differently
}
type AWS_SQS interface {
// QueueHandle get a queue handle (URL) when provided a queue name
QueueHandle(string) (QueueHandle, error)
// GetMessagesAvailable get the count of messages available in the specified queue
GetMessagesAvailable(queueName string) (uint, error)
// BatchMessageGet get a batch of messages from the specified queue. Will return on receipt of any
// messages without waiting and will wait no longer than the wait time if no messages are received.
BatchMessageGet(queue QueueHandle, maxMessages uint, waitTime time.Duration) ([]Message, error)
// BatchMessagePut put a batch of messages to the specified queue.
// in the event of one or more failure, the operation status array will indicate which
// messages were processed successfully and which were not.
BatchMessagePut(queue QueueHandle, messages []Message) ([]OpStatus, error)
// BatchMessageDelete mark a batch of messages from the specified queue as suitable for delete. This mechanism
// prevents messages from being reprocessed.
BatchMessageDelete(queue QueueHandle, messages []Message) ([]OpStatus, error)
// MessagePutRetry retry a batched put after one or more of the operations fails.
// retry the specified amount of times and return an error of after retrying one or messages
// has still not been sent successfully.
MessagePutRetry(queue QueueHandle, messages []Message, opStatus []OpStatus, retryCount uint) error
}
// AwsSqsConfig our configuration structure
type AwsSqsConfig struct {
MessageBucketName string // the name of the bucket to use for oversize messages
}
// NewAwsSqs factory for our SQS interface
func NewAwsSqs(config AwsSqsConfig) (AWS_SQS, error) {
// mock the implementation here if necessary
aws, err := newAwsSqs(config)
return aws, err
}
//
// end of file
//
|
package openstack
import (
"github.com/openshift/installer/pkg/terraform"
"github.com/openshift/installer/pkg/terraform/providers"
"github.com/openshift/installer/pkg/terraform/stages"
)
// PlatformStages are the stages to run to provision the infrastructure in
// OpenStack.
var PlatformStages = []terraform.Stage{
stages.NewStage(
"openstack",
"masters",
[]providers.Provider{providers.OpenStack, providers.Ignition},
),
stages.NewStage(
"openstack",
"bootstrap",
[]providers.Provider{providers.OpenStack},
stages.WithNormalBootstrapDestroy(),
),
}
|
// Copyright 2015 PingCAP, Inc.
//
// 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 printer
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPrintResult(t *testing.T) {
cols := []string{"col1", "col2", "col3"}
datas := [][]string{{"11"}, {"21", "22", "23"}}
result, ok := GetPrintResult(cols, datas)
require.False(t, ok)
require.Equal(t, "", result)
datas = [][]string{{"11", "12", "13"}, {"21", "22", "23"}}
expect := `
+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| 11 | 12 | 13 |
| 21 | 22 | 23 |
+------+------+------+
`
result, ok = GetPrintResult(cols, datas)
require.True(t, ok)
require.Equal(t, expect[1:], result)
datas = nil
result, ok = GetPrintResult(cols, datas)
require.False(t, ok)
require.Equal(t, "", result)
cols = nil
result, ok = GetPrintResult(cols, datas)
require.False(t, ok)
require.Equal(t, "", result)
}
|
package controller
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/nicobianchetti/Go-CleanArchitecture/cache"
"github.com/nicobianchetti/Go-CleanArchitecture/model"
"github.com/nicobianchetti/Go-CleanArchitecture/service"
)
//IPermisoController interac with IPermisoService
type IPermisoController interface {
GetAll(w http.ResponseWriter, r *http.Request)
GetByID(w http.ResponseWriter, r *http.Request)
Create(w http.ResponseWriter, r *http.Request)
Update(w http.ResponseWriter, r *http.Request)
Delete(w http.ResponseWriter, r *http.Request)
}
type permisoController struct{}
var (
permisoService service.IPermisoService
permisoCache cache.PermisoCache
)
//NewPermisoController create new instance of controller
func NewPermisoController(service service.IPermisoService, cache cache.PermisoCache) IPermisoController {
permisoService = service
permisoCache = cache
return &permisoController{}
}
func (c *permisoController) GetAll(w http.ResponseWriter, r *http.Request) {
pr, err := permisoService.GetAll()
if err != nil {
responsePermisos(w, http.StatusNotFound, nil)
}
var dtoPermiso []*model.DTOPermisoResponse
for _, permiso := range pr {
dtoItem := model.NewPermisoDTOWFromPermiso(&permiso)
dtoPermiso = append(dtoPermiso, dtoItem)
}
responsePermisos(w, http.StatusOK, dtoPermiso)
}
func (c *permisoController) GetByID(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var permisoC *model.Permiso = permisoCache.Get(vars["id"])
if permisoC == nil {
permiso, err := permisoService.GetByID(vars["id"])
fmt.Println("Permiso service:", permiso)
if err != nil {
http.Error(w, "Permiso Not found", http.StatusNotFound)
return
}
if permiso == nil {
http.Error(w, "Permiso Not found in DB", http.StatusNotFound)
return
}
fmt.Println("Antes del set a cache")
permisoCache.Set(vars["id"], permiso)
dtoPermiso := model.NewPermisoDTOWFromPermiso(permiso)
responsePermiso(w, http.StatusOK, dtoPermiso)
} else {
dtoPermiso := model.NewPermisoDTOWFromPermiso(permisoC)
responsePermiso(w, http.StatusOK, dtoPermiso)
}
}
func (c *permisoController) Create(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var permisoDTO model.DTOPermisoRequest
err := decoder.Decode(&permisoDTO)
defer r.Body.Close()
if err != nil {
responsePermiso(w, http.StatusBadRequest, nil)
return
}
permiso := model.NewPermisoFromDTO(&permisoDTO)
permisoRes, err := permisoService.Create(permiso)
dtoItem := model.NewPermisoDTOWFromPermiso(permisoRes)
if err != nil {
responsePermiso(w, http.StatusBadRequest, nil)
return
}
responsePermiso(w, http.StatusCreated, dtoItem)
}
func (c *permisoController) Update(w http.ResponseWriter, r *http.Request) {
// fmt.Print("\n Entra al update")
// vars := mux.Vars(r)
// id := vars["id"]
// fmt.Print("\n ID ", id)
// decoder := json.NewDecoder(r.Body)
// var permisoDTO DTOPermisoRequest
// err := decoder.Decode(&permisoDTO)
// fmt.Print("\n Permiso DTO ", permisoDTO)
// defer r.Body.Close()
// if err != nil {
// responsePermiso(w, http.StatusInternalServerError, nil)
// return
// }
// permiso := NewPermisoFromDTO(&permisoDTO)
// spew.Dump(permiso)
// err = c.controller.Update(id, permiso)
// if err != nil {
// responsePermiso(w, http.StatusInternalServerError, nil)
// fmt.Print(err)
// return
// }
// responsePermiso(w, http.StatusOK, nil)
}
func (c *permisoController) Delete(w http.ResponseWriter, r *http.Request) {
// vars := mux.Vars(r)
// err := c.controller.Delete(vars["id"])
// if err != nil {
// responsePermiso(w, http.StatusNotFound, nil)
// return
// }
// responsePermiso(w, http.StatusNoContent, nil)
}
func responsePermiso(w http.ResponseWriter, status int, permiso *model.DTOPermisoResponse) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(permiso)
}
func responsePermisos(w http.ResponseWriter, status int, permisos []*model.DTOPermisoResponse) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(permisos)
}
|
package main
import (
"fmt"
"log"
"net"
"os"
"sort"
"strings"
"sync"
// "time"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("You need to provide an IP or CIDR block.\n")
} else {
ipPtr := make(map[string]string)
//ipPtr := make(map[ip]string)
for _, cidr := range os.Args[1:] {
fmt.Println("You entered:", cidr)
ip, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
log.Fatal(err)
}
for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {
ipPtr[ip.String()] = ""
//ipPtr[ip] = ""
}
}
var wg sync.WaitGroup
for ip, _ := range ipPtr {
wg.Add(1)
go func(ip string) {
//go func(ip ip) {
defer wg.Done()
records, err := net.LookupAddr(ip)
if err != nil {
//words := make([]string)
var words []string
words = append(words, " => NXDOMAIN, got(", err.Error(), ")")
ipPtr[ip] = strings.Join(words, "")
//ipPtr[ip] = fmt.Printf("%s => NXDOMAIN, got (%s)"), ip, err)
} else {
ipPtr[ip] = strings.Join(records, ",")
//fmt.Println(ipPtr[ip])
}
}(ip)
}
//wg.Done()
fmt.Println("Performing all lookups, please be patient")
wg.Wait()
var keys []string
for k := range ipPtr {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, "=>", ipPtr[k])
}
/*
for ip, ptr := range ipPtr {
fmt.Println(ip, "=>", ptr)
}
*/
fmt.Println("The end!")
}
}
func inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}
/*
func ptrLookup(ip string, c chan string) {
records, err := net.LookupAddr(ip)
if err != nil {
//words := make([]string)
var words []string
words = append(words, " => NXDOMAIN, got(", err.Error(), ")")
ipPtr[ip] = strings.Join(words, "")
fmt.Println(ipPtr[ip])
//ipPtr[ip] = fmt.Printf("%s => NXDOMAIN, got (%s)"), ip, err)
}
}
*/
|
// echo loop
package main
import (
"bufio"
"log"
"os"
"time"
"./client"
"./server"
)
func main() {
port := string(":8080")
ch := make(chan string)
go func() {
if err := server.Listen(port); err != nil {
log.Fatal("main:server:", err)
}
}()
time.Sleep(time.Second)
go func() {
for {
if err := client.Client(port, ch); err != nil {
log.Fatal("main:client:", err)
} else {
log.Println("CLIENT: call agein")
continue
}
}
}()
// main input loop
for sc := bufio.NewScanner(os.Stdin); sc.Scan(); {
if sc.Err() != nil {
log.Fatalf("main: %v", sc.Err())
}
ch <- sc.Text()
}
log.Println("exit main loop")
}
|
/*
Here is the (quite scary) Five little ducks song(it is not long):
Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.
Four little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only three little ducks came back.
Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.
Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.
One little duck went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but none of the little ducks came back.
Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.
Your task is not to output this song. You should take a verse and output the next verse, cyclically (the next verse of the last verse is the first verse).
Rules
No standard loopholes, please.
Input/output will be taken via our standard input/output methods.
The exact verse must be outputted, and there should be no differences when compared to the song lyrics. The input will not be different when it is compared to the song lyrics too.
Examples
Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.
Expected:
Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.
Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.
Expected:
Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.
*/
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(verse(`Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.`))
fmt.Println(verse(`Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.`))
}
func verse(s string) string {
t := strings.Split(poem, "\n\n")
for i := range t {
if s == t[i] {
return t[(i+1)%len(t)]
}
}
return ""
}
const poem = `Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.
Four little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only three little ducks came back.
Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.
Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.
One little duck went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but none of the little ducks came back.
Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.`
|
package main
import (
"fmt"
"time"
"github.com/aws-controllers-k8s/dev-tools/pkg/cache"
)
func main() {
c, err := cache.NewFSStore("test.txt", 3600*time.Second)
fmt.Println(err)
v, err := c.Get("a")
fmt.Println("++", err == nil)
fmt.Println(err, v.([]byte))
defer c.Save()
}
|
package stack
import "errors"
var Underflow = errors.New("stack underflow");
type cell struct {
next *cell
value interface{}
}
type Stack struct {
top *cell
}
func New() Stack {
return Stack{nil}
}
func (s *Stack) Push(v interface{}) error {
s.top = &cell{s.top, v}
return nil
}
func (s *Stack) Pop() (interface{}, error) {
if s.top == nil {
return nil, Underflow
}
v := s.top.value
s.top = s.top.next
return v, nil
}
func (s Stack) Top() interface{} {
if s.top == nil {
return nil
}
return s.top.value
}
func (s Stack) IsEmpty() bool {
return s.top == nil
} |
package meda
import (
"context"
"database/sql"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
// ChunkIterator is a utility to iterate over fixed-size chunks of a table.
// Each chunk consists of a number of rows whose IDs are in between two
// values. ChunkIterator has no associated resources and does not have to be
// closed.
type ChunkIterator struct {
// NextChunkQuery is the query used to retrieve the last id of the next
// chunk. The query is passed two parameters: 1) The last id of the
// previous chunk and 2) the chunk size.
NextChunkQuery string
ChunkSize uint64
finished bool
err error
previousID uint64
lastID uint64
}
// Next queries the next chunk of size ChunkSize using NextChunkQuery. If
// false is returned either the end of the table has been reached (no more
// chunks) or an error occurred. The user must check Err to distinguish
// between the two cases.
//
// The ids required to run queries on the chunk can be retrieved through
// PreviousID and LastID. These methods may only be used after Next has
// returned true. Each chunk consists of all records with id > PreviousID and
// id <= LastID.
func (c *ChunkIterator) Next(ctx context.Context, queryer sqlx.QueryerContext) bool {
if c.err != nil || c.finished {
return false
}
var lastID uint64
err := queryer.QueryRowxContext(ctx, c.NextChunkQuery, c.lastID, c.ChunkSize).Scan(&lastID)
if err == sql.ErrNoRows {
c.finished = true
return false
} else if err != nil {
c.err = errors.Wrap(err, "(*ChunkIterator).Next: query next chunk")
return false
}
c.previousID, c.lastID = c.lastID, lastID
return true
}
// Err returns any error which occurred during querying the next chunk and
// interpreting the result.
func (c *ChunkIterator) Err() error {
return c.err
}
// PreviousID returns the last id of the previous chunk. This method may only
// be called after Next has returned true.
func (c *ChunkIterator) PreviousID() uint64 {
return c.previousID
}
// LastID returns the last id of the current chunk. This method may only be
// called after Next has returned true.
func (c *ChunkIterator) LastID() uint64 {
return c.lastID
}
// ChunkIteratorByRand is a utility to iterate over approximately fixed-size
// chunks of a table using a column containing RAND() values.
// ChunkIteratorByRand is a modified version of ChunkIterator working with
// float64 instead of uint64 values.
// Each chunk consists of a number of rows whose rand values are in between
// two values. ChunkIteratorByRand has no associated resources and does not
// have to be closed.
type ChunkIteratorByRand struct {
// NextChunkQuery is the query used to retrieve the last rand value of the
// next chunk. The query is passed two parameters: 1) The last rand value
// of the previous chunk and 2) the chunk size.
NextChunkQuery string
ChunkSize uint64
finished bool
err error
previousRand float64
lastRand float64
}
// Next queries the next chunk of size ChunkSize using NextChunkQuery. If
// false is returned either the end of the table has been reached (no more
// chunks) or an error occurred. The user must check Err to distinguish
// between the two cases.
//
// The rand values required to run queries on the chunk can be retrieved
// through PreviousRand and LastRand. These methods may only be used after
// Next has returned true. Each chunk consists of all records with rand >
// PreviousRand and id <= LastRand.
// This may be more records than specified by ChunkSize, as rand is not a
// unique column. However, each chunk still refers to distinct set of rows.
// No row is contained in two chunks.
func (c *ChunkIteratorByRand) Next(ctx context.Context, queryer sqlx.QueryerContext) bool {
if c.err != nil || c.finished {
return false
}
var lastRand float64
err := queryer.QueryRowxContext(ctx, c.NextChunkQuery, c.lastRand, c.ChunkSize).Scan(&lastRand)
if err == sql.ErrNoRows {
c.finished = true
return false
} else if err != nil {
c.err = errors.Wrap(err, "(*ChunkIteratorByRand).Next: query next chunk")
return false
}
c.previousRand, c.lastRand = c.lastRand, lastRand
return true
}
// Err returns any error which occurred during querying the next chunk and
// interpreting the result.
func (c *ChunkIteratorByRand) Err() error {
return c.err
}
// PreviousRand returns the last rand value of the previous chunk. This method
// may only be called after Next has returned true.
func (c *ChunkIteratorByRand) PreviousRand() float64 {
return c.previousRand
}
// LastRand returns the last rand value of the current chunk. This method may
// only be called after Next has returned true.
func (c *ChunkIteratorByRand) LastRand() float64 {
return c.lastRand
}
|
/*
Copyright IBM Corporation 2020
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 source
import (
log "github.com/sirupsen/logrus"
sourcetypes "github.com/konveyor/move2kube/internal/collector/sourcetypes"
common "github.com/konveyor/move2kube/internal/common"
"github.com/konveyor/move2kube/internal/source/compose"
irtypes "github.com/konveyor/move2kube/internal/types"
collecttypes "github.com/konveyor/move2kube/types/collection"
plantypes "github.com/konveyor/move2kube/types/plan"
)
// ComposeTranslator implements Translator interface
type ComposeTranslator struct {
}
// GetTranslatorType returns the translator type
func (c ComposeTranslator) GetTranslatorType() plantypes.TranslationTypeValue {
return plantypes.Compose2KubeTranslation
}
// GetServiceOptions returns the service options for inputPath
func (c ComposeTranslator) GetServiceOptions(inputPath string, plan plantypes.Plan) ([]plantypes.Service, error) {
servicesMap := make(map[string]plantypes.Service)
//Load images
yamlpaths, err := common.GetFilesByExt(inputPath, []string{".yaml", ".yml"})
if err != nil {
log.Warnf("Unable to fetch yaml files and recognize compose yamls : %s", err)
}
imagemetadatapaths := make(map[string]string)
for _, path := range yamlpaths {
im := new(collecttypes.ImageInfo)
if common.ReadYaml(path, &im) == nil && im.Kind == string(collecttypes.ImageMetadataKind) {
for _, imagetag := range im.Spec.Tags {
imagemetadatapaths[imagetag] = path
}
}
}
//Fill data into plan
for _, path := range yamlpaths {
dc := new(sourcetypes.DockerCompose)
if common.ReadYaml(path, &dc) == nil {
path, _ = plan.GetRelativePath(path)
for serviceName, dcservice := range dc.DCServices {
log.Debugf("Found a Docker compose service : %s", serviceName)
serviceName = common.NormalizeForServiceName(serviceName)
if _, ok := servicesMap[serviceName]; !ok {
servicesMap[serviceName] = c.newService(serviceName)
}
service := servicesMap[serviceName]
service.Image = dcservice.Image
service.UpdateContainerBuildPipeline = false
service.UpdateDeployPipeline = true
service.AddSourceArtifact(plantypes.ComposeFileArtifactType, path)
if imagepath, ok := imagemetadatapaths[dcservice.Image]; ok {
imagepath, _ = plan.GetRelativePath(imagepath)
service.AddSourceArtifact(plantypes.ImageInfoArtifactType, imagepath)
}
servicesMap[serviceName] = service
}
}
}
services := make([]plantypes.Service, len(servicesMap))
i := 0
for _, service := range servicesMap {
services[i] = service
i++
}
return services, nil
}
type composeIRTranslator interface {
ConvertToIR(filepath string, serviceName string) (irtypes.IR, error)
}
// Translate translates the service to IR
func (c ComposeTranslator) Translate(services []plantypes.Service, p plantypes.Plan) (irtypes.IR, error) {
ir := irtypes.NewIR(p)
for _, service := range services {
if service.TranslationType == c.GetTranslatorType() {
for _, path := range service.SourceArtifacts[plantypes.ComposeFileArtifactType] {
fullpath := p.GetFullPath(path)
log.Debugf("File %s being loaded from compose service : %s", fullpath, service.ServiceName)
var dcfile sourcetypes.DockerCompose
err := common.ReadYaml(fullpath, &dcfile)
if err != nil {
log.Errorf("Unable to read docker compose yaml %s for version : %s", path, err)
}
log.Debugf("Docker Compose version: %s", dcfile.Version)
var t composeIRTranslator
switch dcfile.Version {
case "", "1", "1.0", "2", "2.0", "2.1":
t = new(compose.V1V2Loader)
case "3", "3.0", "3.1", "3.2", "3.3", "3.4", "3.5", "3.6", "3.7", "3.8":
t = new(compose.V3Loader)
default:
log.Errorf("Version %s of Docker Compose is not supported (%s). Please use version 1, 2 or 3.", dcfile.Version, fullpath)
}
cir, err := t.ConvertToIR(fullpath, service.ServiceName)
if err != nil {
log.Errorf("Unable to parse docker compose file %s using %T : %s", fullpath, t, err)
} else {
ir.Merge(cir)
}
log.Debugf("Services returned by compose translator : %d", len(ir.Services))
}
for _, path := range service.SourceArtifacts[plantypes.ImageInfoArtifactType] {
var imgMD collecttypes.ImageInfo
err := common.ReadYaml(p.GetFullPath(path), &imgMD)
if err != nil {
log.Errorf("Unable to read image yaml %s : %s", path, err)
} else {
ir.AddContainer(irtypes.NewContainerFromImageInfo(imgMD))
}
}
}
}
return ir, nil
}
func (c ComposeTranslator) newService(serviceName string) plantypes.Service {
service := plantypes.NewService(serviceName, c.GetTranslatorType())
service.AddSourceType(plantypes.ComposeSourceTypeValue)
service.ContainerBuildType = plantypes.ReuseContainerBuildTypeValue //TODO: Identify when to use enhance
return service
}
|
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
for i := 1; i <= 20; i++ {
values := []string{}
d3 := i%3 == 0
d5 := i%5 == 0
if !d3 && !d5 {
values = append(values, strconv.Itoa(i))
} else {
if d3 {
values = append(values, "Fizz")
}
if d5 {
values = append(values, "Buzz")
}
}
if i > 1 {
fmt.Print(", ")
}
fmt.Print(strings.Join(values, " "))
}
}
|
/*
* KSQL
*
* This is a swagger spec for ksqldb
*
* API version: 1.0.0
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package swagger
type Format string
// List of format
const (
JSON_Format Format = "JSON"
AVRO_Format Format = "AVRO"
PROTOBUF_Format Format = "PROTOBUF"
DELIMITED_Format Format = "DELIMITED"
)
|
// Copyright Jetstack Ltd. See LICENSE for details.
package cmd
import (
"fmt"
"path/filepath"
"github.com/spf13/cobra"
"github.com/jetstack/vault-helper/pkg/read"
)
// initCmd represents the init command
var readCmd = &cobra.Command{
Use: "read [vault path]",
Short: "Read arbitrary vault path. If no output file specified, output to console.",
Run: func(cmd *cobra.Command, args []string) {
log, err := LogLevel(cmd)
if err != nil {
Must(err)
}
i, err := newInstanceToken(cmd)
if err != nil {
Must(err)
}
if err := i.TokenRenewRun(); err != nil {
Must(err)
}
r := read.New(log, i)
if len(args) != 1 {
Must(fmt.Errorf("incorrect number of arguments given. Usage: vault-helper read [vault path] [flags]"))
}
r.SetVaultPath(args[0])
if err := setFlagsRead(r, cmd); err != nil {
Must(err)
}
if err := r.RunRead(); err != nil {
Must(err)
}
},
}
func init() {
instanceTokenFlags(readCmd)
readCmd.PersistentFlags().String(read.FlagOutputPath, "", "Set destination file path of read responce. Output to console if no filepath given (default <console>)")
readCmd.Flag(read.FlagOutputPath).Shorthand = "d"
readCmd.PersistentFlags().String(read.FlagField, "", "If included, the raw value of the specified field will be output. If not, output entire responce in JSON (default <all>)")
readCmd.Flag(read.FlagField).Shorthand = "f"
readCmd.PersistentFlags().String(read.FlagOwner, "", "Set owner of output file. Uid value also accepted. (default <current user>)")
readCmd.Flag(read.FlagOwner).Shorthand = "o"
readCmd.PersistentFlags().String(read.FlagGroup, "", "Set group of output file. Gid value also accepted. (default <current user-group>)")
readCmd.Flag(read.FlagGroup).Shorthand = "g"
RootCmd.AddCommand(readCmd)
}
func setFlagsRead(r *read.Read, cmd *cobra.Command) error {
value, err := cmd.PersistentFlags().GetString(read.FlagOutputPath)
if err != nil {
return fmt.Errorf("error parsing %s '%s': %v", read.FlagOutputPath, value, err)
}
if value != "" {
abs, err := filepath.Abs(value)
if err != nil {
return fmt.Errorf("error generating absoute path from destination '%s': %v", value, err)
}
r.SetFilePath(abs)
}
value, err = cmd.PersistentFlags().GetString(read.FlagField)
if err != nil {
return fmt.Errorf("error parsing %s '%s': %v", read.FlagField, value, err)
}
if value != "" {
r.SetFieldName(value)
}
value, err = cmd.PersistentFlags().GetString(read.FlagOwner)
if err != nil {
return fmt.Errorf("error parsing %s '%s': %v", read.FlagOwner, value, err)
}
if value != "" {
r.SetOwner(value)
}
value, err = cmd.PersistentFlags().GetString(read.FlagGroup)
if err != nil {
return fmt.Errorf("error parsing %s '%s': %v", read.FlagGroup, value, err)
}
if value != "" {
r.SetGroup(value)
}
return nil
}
|
package operations
import (
"encoding/csv"
"errors"
"math"
"math/rand"
"os"
"strconv"
"time"
)
// Compare returns
func Compare(bc1 []byte, bc2 []byte) (bool, int, int) {
//comparable := true
firstBigger := 0
secondBigger := 0
for i := 0; i < len(bc1); i++ {
if bc1[i] < bc2[i] {
secondBigger += int(bc2[i]) - int(bc1[i])
} else if bc1[i] > bc2[i] {
firstBigger += int(bc1[i]) - int(bc2[i])
}
}
if firstBigger != 0 && secondBigger != 0 {
return false, firstBigger, secondBigger
}
return true, firstBigger, secondBigger
}
func HappenedBefore(bc1 []byte, bc2 []byte) (float64, error) {
comparable, firstBigger, secondBigger := Compare(bc1, bc2)
if !comparable {
return 1, errors.New("bloom clocks are not comparable")
}
if firstBigger > secondBigger {
return 1, errors.New("first bloom clock is bigger")
}
return falsePositiveRate(bc1, bc2), nil
}
func HappenedAfter(bc1 []byte, bc2 []byte) (float64, error) {
comparable, firstBigger, secondBigger := Compare(bc1, bc2)
if !comparable {
return 1, errors.New("bloom clocks are not comparable")
}
if firstBigger < secondBigger {
return 1, errors.New("first bloom clock is bigger")
}
return falsePositiveRate(bc1, bc2), nil
}
func sumOfBloomClock(bc []byte) int {
ret := 0
for i := range bc {
ret += int(bc[i])
}
return ret
}
func falsePositiveRate(bc1 []byte, bc2 []byte) float64 {
sumA := sumOfBloomClock(bc1)
sumB := sumOfBloomClock(bc2)
return math.Pow(1-math.Pow(1-0.5, float64(sumB)), float64(sumA))
}
// Shuffle randomize elements of neighbors
func Shuffle(slice []int) {
r := rand.New(rand.NewSource(time.Now().Unix()))
for len(slice) > 0 {
n := len(slice)
randIndex := r.Intn(n)
slice[n-1], slice[randIndex] = slice[randIndex], slice[n-1]
slice = slice[:n-1]
}
}
func WriteToCSV(nodePort int, element string, bloomclock string) error {
file, err := os.OpenFile(strconv.Itoa(nodePort)+".csv", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return err
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
var data = [][]string{{strconv.FormatInt(time.Now().Unix(), 10), bloomclock, element}}
for _, value := range data {
err := writer.Write(value)
if err != nil {
return err
}
}
return nil
}
func MergerBloomClock(bc1 []byte, bc2 []byte) []byte {
var ret []byte
for i := 0; i < len(bc1); i++ {
if bc1[i] <= bc2[i] {
ret = append(ret, bc2[i])
} else if bc1[i] > bc2[i] {
ret = append(ret, bc1[i])
}
}
return ret
}
func SubtractSlice(nodes, broadcast []string) []string {
var ret []string
for _, v := range nodes {
if !in(v, broadcast) {
ret = append(ret, v)
}
}
return ret
}
func in(element string, nodes []string) bool {
for _, v := range nodes {
if v == element {
return true
}
}
return false
}
func Intersection(s1, s2 []string) string {
for i := range s2 {
if in(s2[i], s1) {
return s2[i]
}
}
return ""
}
|
package api
import (
"encoding/json"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"github.com/sirsean/packhunter/model"
"github.com/sirsean/packhunter/mongo"
"github.com/sirsean/packhunter/ph"
"github.com/sirsean/packhunter/rank"
"github.com/sirsean/packhunter/service"
"github.com/sirsean/packhunter/web"
"net/http"
"strings"
)
var postDecoder = schema.NewDecoder()
func ListMyTags(w http.ResponseWriter, r *http.Request) {
session := mongo.Session()
defer session.Close()
user, _ := web.CurrentUser(r, session)
tags := make([]model.BasicTag, len(user.Tags))
for i, t := range user.Tags {
tag, _ := service.GetTagByIdHex(session, t.Id)
tags[i] = tag.Basic()
}
response, _ := json.Marshal(tags)
w.Write(response)
}
func ShowTag(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
session := mongo.Session()
defer session.Close()
tag, _ := service.GetTagByIdHex(session, id)
response, _ := json.Marshal(tag)
w.Write(response)
}
func CreateTag(w http.ResponseWriter, r *http.Request) {
type CreateForm struct {
Name string `schema:"name"`
Public bool `schema:"public"`
}
session := mongo.Session()
defer session.Close()
currentUser, _ := web.CurrentUser(r, session)
r.ParseForm()
form := new(CreateForm)
postDecoder.Decode(form, r.PostForm)
tag := model.Tag{
Name: form.Name,
Public: form.Public,
}
service.CreateTag(session, ¤tUser, &tag)
response, _ := json.Marshal(tag)
w.Write(response)
}
func GetTagProducts(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
session := mongo.Session()
defer session.Close()
currentUser, _ := web.CurrentUser(r, session)
tag, _ := service.GetTagByIdHex(session, id)
products := rank.ForTag(currentUser.AccessToken, tag)
response, _ := json.Marshal(products)
w.Write(response)
}
func SubscribeToTag(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
session := mongo.Session()
defer session.Close()
currentUser, _ := web.CurrentUser(r, session)
tag, _ := service.GetTagByIdHex(session, id)
currentUser.AddTag(tag)
service.SaveUser(session, ¤tUser)
}
func UnsubscribeFromTag(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
session := mongo.Session()
defer session.Close()
currentUser, _ := web.CurrentUser(r, session)
tag, _ := service.GetTagByIdHex(session, id)
currentUser.RemoveTag(tag)
service.SaveUser(session, ¤tUser)
}
func SetTagUsers(w http.ResponseWriter, r *http.Request) {
type UsersForm struct {
Usernames string `schema:"usernames"`
}
vars := mux.Vars(r)
id := vars["id"]
session := mongo.Session()
defer session.Close()
currentUser, _ := web.CurrentUser(r, session)
r.ParseForm()
form := new(UsersForm)
postDecoder.Decode(form, r.PostForm)
usernames := strings.Split(form.Usernames, ",")
tag, _ := service.GetTagByIdHex(session, id)
for _, u := range tag.Users {
if !usernamesContains(usernames, u.Username) {
tag.RemoveUser(u)
}
}
for _, username := range usernames {
user := ph.GetUserByUsername(currentUser.AccessToken, username)
tag.AddUser(user)
}
service.SaveTag(session, &tag)
}
func usernamesContains(usernames []string, username string) bool {
for _, u := range usernames {
if u == username {
return true
}
}
return false
}
|
package gokun
import (
"crypto/tls"
"errors"
)
type Config struct {
Server string
Port uint
Password string
Nick string
User string
RealName string
Channnels string
SSL bool
SSLConfig *tls.Config
}
func (cfg *Config) IsValid() error {
if cfg.Server == "" {
return errors.New("Please Set Server Config")
}
if cfg.Nick == "" {
return errors.New("Please Set Nick Config")
}
return nil
}
|
package pathfileops
import "testing"
func TestPathValidityStatusCode_EqualOperator_01(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Unknown()
result := false
if status1==status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Unknown()\n" +
"Expected the equal operator (status1==status2) to return true.\n" +
"However, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_EqualOperator_02(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Invalid()
result := false
if status1==status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the equal operator (status1==status2) to return false.\n" +
"However, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_EqualOperator_03(t *testing.T) {
status1 := PathValidStatus.Invalid()
status2 := PathValidStatus.Invalid()
result := false
if status1==status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Invalid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the equal operator (status1==status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_EqualOperator_04(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Invalid()
result := false
if status1==status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the equal operator (status1==status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_EqualOperator_05(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Valid()
result := false
if status1==status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the equal operator (status1==status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_EqualOperator_06(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Valid()
result := false
if status1==status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the equal operator (status1==status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOperator_01(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Unknown()
result := false
if status1 > status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Unknown()\n" +
"Expected the greater than operator (status1 > status2) to return false.\n" +
"However, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOperator_02(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Invalid()
result := false
if status1 > status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the greater than operator (status1 > status2) to return false.\n" +
"However, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOperator_03(t *testing.T) {
status1 := PathValidStatus.Invalid()
status2 := PathValidStatus.Invalid()
result := false
if status1 > status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Invalid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the greater than operator (status1 > status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOperator_04(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Invalid()
result := false
if status1 > status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the greater than operator (status1 > status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOperator_05(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Valid()
result := false
if status1 > status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the greater than operator (status1 > status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOperator_06(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Unknown()
result := false
if status1 > status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Unknown()\n" +
"Expected the equal operator (status1==status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOrEqualOperator_01(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Unknown()
result := false
if status1>=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Unknown()\n" +
"Expected the equal operator (status1>=status2) to return true.\n" +
"However, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOrEqualOperator_02(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Invalid()
result := false
if status1>=status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the equal operator (status1>=status2) to return false.\n" +
"However, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOrEqualOperator_03(t *testing.T) {
status1 := PathValidStatus.Invalid()
status2 := PathValidStatus.Invalid()
result := false
if status1>=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Invalid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the equal operator (status1>=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOrEqualOperator_04(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Invalid()
result := false
if status1>=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the equal operator (status1>=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOrEqualOperator_05(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Valid()
result := false
if status1>=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the equal operator (status1>=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOrEqualOperator_06(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Valid()
result := false
if status1>=status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the equal operator (status1>=status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_GreaterThanOrEqualOperator_07(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Unknown()
result := false
if status1>=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Unknown()\n" +
"Expected the equal operator (status1>=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_Invalid_01(t *testing.T) {
status := PathValidStatus.Invalid()
intStatus := int(status)
if intStatus != 0 {
t.Errorf("Error: Expected PathValidStatus.Invalid()=='0'.\n" +
"Instead PathValidStatus.Invalid()=='%v'\n", intStatus)
}
}
func TestPathValidityStatusCode_Invalid_02(t *testing.T) {
status := PathValidStatus.Invalid()
statusStr := status.String()
if statusStr != "Invalid" {
t.Errorf("Error: For 'PathValidStatus.Invalid()':\n" +
"Expected PathExistsStatus.String()=='Invalid'.\n" +
"Instead PathExistsStatus.String()=='%v'\n", statusStr)
}
}
func TestPathValidityStatusCode_Invalid_03(t *testing.T) {
status := PathValidStatus.Invalid()
statusValue := status.StatusValue()
if int(statusValue) != 0 {
t.Errorf("Error: For 'PathValidStatus.Invalid()':\n" +
"Expected status.Value()=='0'.\n" +
"Instead status.Value()=='%v'\n", int(statusValue))
}
}
func TestPathValidityStatusCode_Invalid_04(t *testing.T) {
statusCode, err :=
PathValidityStatusCode(0).ParseString("Invalid", true)
if err != nil {
t.Errorf("Error returned by PathValidityStatusCode(0)." +
"ParseString(\"Invalid\", true)\n" +
"Error='%v'\n", err.Error())
return
}
if int(statusCode) != 0 {
t.Errorf("Error: For 'PathValidStatus.Invalid()':\n" +
"Expected ParseString()=='0'.\n" +
"Instead ParseString()=='%v'\n", int(statusCode))
}
}
func TestPathValidityStatusCode_Invalid_05(t *testing.T) {
statusCode, err :=
PathValidityStatusCode(0).ParseString("invalid", false)
if err != nil {
t.Errorf("Error returned by PathValidityStatusCode(0)." +
"ParseString(\"invalid\", false)\n" +
"Error='%v'\n", err.Error())
return
}
if int(statusCode) != 0 {
t.Errorf("Error: For 'PathValidStatus.Invalid()':\n" +
"Expected lower case ParseString()=='0'.\n" +
"Instead lower case ParseString()=='%v'\n", int(statusCode))
}
}
func TestPathValidityStatusCode_LessThanOrEqualOperator_01(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Unknown()
result := false
if status1<=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Unknown()\n" +
"Expected the not equal operator (status1<=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_LessThanOrEqualOperator_02(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Invalid()
result := false
if status1<=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the not equal operator (status1<=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_LessThanOrEqualOperator_03(t *testing.T) {
status1 := PathValidStatus.Invalid()
status2 := PathValidStatus.Invalid()
result := false
if status1<=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Invalid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the not equal operator (status1<=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_LessThanOrEqualOperator_04(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Invalid()
result := false
if status1<=status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the not equal operator (status1<=status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_LessThanOrEqualOperator_05(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Valid()
result := false
if status1<=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the not equal operator (status1<=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_LessThanOrEqualOperator_06(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Valid()
result := false
if status1<=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the not equal operator (status1<=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_LessThanOrEqualOperator_07(t *testing.T) {
status1 := PathValidityStatusCode(99)
status2 := PathValidStatus.Valid()
result := false
if status1<=status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidityStatusCode(99) and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the not equal operator (status1<=status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_LessThanOrEqualOperator_08(t *testing.T) {
status1 := PathValidityStatusCode(-99)
status2 := PathValidStatus.Valid()
result := false
if status1<=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidityStatusCode(-99) and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the not equal operator (status1<=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_NotEqualOperator_01(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Unknown()
result := false
if status1!=status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Unknown()\n" +
"Expected the not equal operator (status1!=status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_NotEqualOperator_02(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Invalid()
result := false
if status1!=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the not equal operator (status1!=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_NotEqualOperator_03(t *testing.T) {
status1 := PathValidStatus.Invalid()
status2 := PathValidStatus.Invalid()
result := false
if status1!=status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Invalid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the not equal operator (status1!=status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_NotEqualOperator_04(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Invalid()
result := false
if status1!=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Invalid()\n" +
"Expected the not equal operator (status1!=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_NotEqualOperator_05(t *testing.T) {
status1 := PathValidStatus.Valid()
status2 := PathValidStatus.Valid()
result := false
if status1!=status2 {
result = true
}
if result {
t.Error("Error: For status1=PathValidStatus.Valid() and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the not equal operator (status1!=status2) to return false.\n" +
"Instead, it returned 'true'!\n")
}
}
func TestPathValidityStatusCode_NotEqualOperator_06(t *testing.T) {
status1 := PathValidStatus.Unknown()
status2 := PathValidStatus.Valid()
result := false
if status1!=status2 {
result = true
}
if !result {
t.Error("Error: For status1=PathValidStatus.Unknown() and " +
"status2=PathValidStatus.Valid()\n" +
"Expected the not equal operator (status1!=status2) to return true.\n" +
"Instead, it returned 'false'!\n")
}
}
func TestPathValidityStatusCode_ParseString_01(t *testing.T) {
statusStr := " "
_, err := PathValidityStatusCode(0).ParseString(statusStr, true)
if err == nil {
t.Error("Expected an error return from PathValidityStatusCode(0)." +
"ParseString(statusStr, true)\n" +
"because 'statusStr' is an Empty String!\n" +
"However, NO ERROR WAS RETURNED!!!\n")
}
}
func TestPathValidityStatusCode_ParseString_02(t *testing.T) {
statusStr := "Valid()"
statusCode, err := PathValidityStatusCode(0).ParseString(statusStr, true)
if err != nil {
t.Errorf("Error returned by PathValidityStatusCode(0)." +
"ParseString(statusStr, true)\n" +
"Error='%v'\n", err.Error())
return
}
if statusCode != PathValidStatus.Valid() {
t.Errorf("Expected stausCode='%v'.\n" +
"Instead, statusCode='%v'.\n",
statusCode.String(), PathValidStatus.Valid().String())
}
}
func TestPathValidityStatusCode_ParseString_03(t *testing.T) {
statusStr := "xyz"
_, err := PathValidityStatusCode(0).ParseString(statusStr, true)
if err == nil {
t.Error("Expected an error return from PathValidityStatusCode(0)." +
"ParseString(statusStr, true)\n" +
"because 'statusStr' is Invalid!\n" +
"HOWEVER, NO ERROR WAS RETURNED!!!\n")
}
}
func TestPathValidityStatusCode_StatusIsValid_01(t *testing.T) {
status := PathValidityStatusCode(-99)
err := status.StatusIsValid()
if err == nil {
t.Errorf("Expected an error return from status.StatusIsValid()\n" +
"because status is INVALID.\n" +
"However, NO ERROR WAS RETURNED!!!\n")
}
}
func TestPathValidityStatusCode_StatusIsValid_02(t *testing.T) {
status := PathValidityStatusCode(2)
err := status.StatusIsValid()
if err == nil {
t.Errorf("Expected an error return from status.StatusIsValid()\n" +
"because status is INVALID.\n" +
"However, NO ERROR WAS RETURNED!!!\n")
}
}
func TestPathValidityStatusCode_StatusIsValid_03(t *testing.T) {
status := PathValidityStatusCode(-2)
err := status.StatusIsValid()
if err == nil {
t.Error("Expected an error return from status.StatusIsValid()\n" +
"because status is INVALID.\n" +
"However, NO ERROR WAS RETURNED!!!\n")
}
}
func TestPathValidityStatusCode_StatusIsValid_04(t *testing.T) {
status := PathValidityStatusCode(99)
err := status.StatusIsValid()
if err == nil {
t.Error("Expected an error return from status.StatusIsValid()\n" +
"because status is INVALID.\n" +
"However, NO ERROR WAS RETURNED!!!\n")
}
}
func TestPathValidityStatusCode_StatusIsValid_05(t *testing.T) {
status := PathValidStatus.Valid()
err := status.StatusIsValid()
if err != nil {
t.Errorf("Error returned by status.StatusIsValid()\n" +
"Error='%v'\n", err.Error())
}
}
func TestPathValidityStatusCode_String_01(t *testing.T) {
status := PathValidityStatusCode(-99)
statusStr := status.String()
if statusStr != "" {
t.Errorf("Error: Expected status.String()==\"\"\n" +
"Instead, status.String()=='%v'", statusStr)
}
}
func TestPathValidityStatusCode_Unknown_01(t *testing.T) {
status := PathValidStatus.Unknown()
intStatus := int(status)
if intStatus != -1 {
t.Errorf("Error: Expected PathValidStatus.Unknown()=='-1'.\n" +
"Instead PathValidStatus.Unknown()=='%v'\n", intStatus)
}
}
func TestPathValidityStatusCode_Unknown_02(t *testing.T) {
status := PathValidStatus.Unknown()
statusStr := status.String()
if statusStr != "Unknown" {
t.Errorf("Error: For 'PathValidStatus.Unknown()':\n" +
"Expected PathValidStatus.String()=='Unknown'.\n" +
"Instead PathValidStatus.String()=='%v'\n", statusStr)
}
}
func TestPathValidityStatusCode_Unknown_03(t *testing.T) {
status := PathValidStatus.Unknown()
statusValue := status.StatusValue()
if int(statusValue) != -1 {
t.Errorf("Error: For 'PathValidStatus.Unknown()':\n" +
"Expected status.Value()=='-1'.\n" +
"Instead status.Value()=='%v'\n", int(statusValue))
}
}
func TestPathValidityStatusCode_Unknown_04(t *testing.T) {
statusCode, err :=
PathValidityStatusCode(0).ParseString("Unknown", true)
if err != nil {
t.Errorf("Error returned by PathValidStatusCode(0)." +
"ParseString(\"Unknown\", true)\n" +
"Error='%v'\n", err.Error())
return
}
if int(statusCode) != -1 {
t.Errorf("Error: For 'PathValidStatus.Unknown()':\n" +
"Expected ParseString()=='-1'.\n" +
"Instead ParseString()=='%v'\n", int(statusCode))
}
}
func TestPathValidityStatusCode_Unknown_05(t *testing.T) {
statusCode, err :=
PathValidityStatusCode(0).ParseString("unknown", false)
if err != nil {
t.Errorf("Error returned by PathValidStatusCode(0)." +
"ParseString(\"unknown\", false)\n" +
"Error='%v'\n", err.Error())
return
}
if int(statusCode) != -1 {
t.Errorf("Error: For 'PathValidStatus.Unknown()':\n" +
"Expected lower case ParseString()=='-1'.\n" +
"Instead lower case ParseString()=='%v'\n", int(statusCode))
}
}
func TestPathValidityStatusCode_Valid_01(t *testing.T) {
status := PathValidStatus.Valid()
intStatus := int(status)
if intStatus != 1 {
t.Errorf("Error: Expected PathValidStatus.Valid()=='1'.\n" +
"Instead PathValidStatus.Valid()=='%v'\n", intStatus)
}
}
func TestPathValidityStatusCode_Valid_02(t *testing.T) {
status := PathValidStatus.Valid()
statusStr := status.String()
if statusStr != "Valid" {
t.Errorf("Error: For 'PathValidStatus.Valid()':\n" +
"Expected PathValidStatus.String()=='Valid'.\n" +
"Instead PathValidStatus.String()=='%v'\n", statusStr)
}
}
func TestPathValidityStatusCode_Valid_03(t *testing.T) {
status := PathValidStatus.Valid()
statusValue := status.StatusValue()
if int(statusValue) != 1 {
t.Errorf("Error: For 'PathValidStatus.Valid()':\n" +
"Expected status.Value()=='1'.\n" +
"Instead status.Value()=='%v'\n", int(statusValue))
}
}
func TestPathValidityStatusCode_Valid_04(t *testing.T) {
statusCode, err :=
PathValidityStatusCode(0).ParseString("Valid", true)
if err != nil {
t.Errorf("Error returned by PathValidityStatusCode(0)." +
"ParseString(\"Valid\", true)\n" +
"Error='%v'\n", err.Error())
return
}
if int(statusCode) != 1 {
t.Errorf("Error: For 'PathValidStatus.Valid()':\n" +
"Expected ParseString()=='1'.\n" +
"Instead ParseString()=='%v'\n", int(statusCode))
}
}
func TestPathValidityStatusCode_Valid_05(t *testing.T) {
statusCode, err :=
PathValidityStatusCode(0).ParseString("valid", false)
if err != nil {
t.Errorf("Error returned by PathValidityStatusCode(0)." +
"ParseString(\"valid\", false)\n" +
"Error='%v'\n", err.Error())
return
}
if int(statusCode) != 1 {
t.Errorf("Error: For 'PathValidStatus.Valid()':\n" +
"Expected lower case ParseString()=='1'.\n" +
"Instead lower case ParseString()=='%v'\n", int(statusCode))
}
}
func TestPathValidityStatusCode_Valid_06(t *testing.T) {
_, err :=
PathValidityStatusCode(0).ParseString("valid", true)
if err == nil {
t.Error("Expected an error return from PathValidityStatusCode(0)." +
"ParseString(\"valid\", true)\n" +
"because 'valid' is test as 'case sensitive'." +
"However, NO ERROR WAS RETURNED!!!!\n")
}
}
|
//Package vugufmt provides gofmt-like functionality for vugu files.
package vugufmt
|
package port
import (
"github.com/mirzaakhena/danarisan/domain/repository"
"github.com/mirzaakhena/danarisan/domain/service"
)
// BayarSetoranOutport ...
type BayarSetoranOutport interface {
repository.FindOneTagihanRepo
repository.FindOnePesertaRepo
repository.FindLastSaldoAkunRepo
repository.SaveTagihanRepo
repository.SavePesertaRepo
repository.SaveJurnalRepo
repository.SaveSaldoAkunRepo
service.IDGenerator
service.TransactionDB
}
|
package main
import (
"github.com/gin-gonic/gin"
"github.com/rs/xid"
"log"
)
//跨域访问:cross origin resource share
func CrosHandler() gin.HandlerFunc {
return func(context *gin.Context) {
context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
context.Header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, PATCH, OPTIONS")
context.Header("Access-Control-Allow-Headers", "X-Requested-With, content-type")
context.Header("Access-Control-Max-Age", "172800")
context.Header("Access-Control-Allow-Credentials", "true")
//context.Set("content-type", "application/json") //设置返回格式是json
//处理请求
context.Next()
}
}
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("token")
if token == "" {
id := xid.New()
token = id.String()
log.Println("token ",id.String())
c.Writer.Header().Set("token", token)
}
}
}
|
package middleware
import (
"github.com/dgrijalva/jwt-go"
mdl "github.com/huf0813/pembukuan_tk/entity"
"github.com/huf0813/pembukuan_tk/utils/delivery/customJSON"
"github.com/joho/godotenv"
"net/http"
"os"
"strings"
"time"
)
type TokenMiddleware struct {
Res customJSON.JSONCustom
}
type TokenMiddlewareInterface interface {
ReadSecretENV() (string, error)
GetToken(username string, userTypeID int, userID int) (string, error)
VerifyToken(userToken string) (jwt.Claims, error)
TokenMiddlewareIsUser(next http.Handler) http.Handler
TokenMiddlewareIsAdmin(next http.Handler) http.Handler
}
func (tm *TokenMiddleware) ReadSecretENV() (string, error) {
if err := godotenv.Load(); err != nil {
return "", err
}
return os.Getenv("SECRET"), nil
}
func (tm *TokenMiddleware) GetToken(username string, userTypeID int, userID int) (*mdl.TokenExtract, error) {
secretENV, err := tm.ReadSecretENV()
if err != nil {
return nil, err
}
claims := &mdl.Token{
Username: username,
UserTypeID: userTypeID,
UserID: userID,
}
claims.ExpiresAt = time.Now().Add(time.Hour * 8).Unix()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
result := []byte(secretENV)
tokeString, err := token.SignedString(result)
if err != nil {
return nil, err
}
return &mdl.TokenExtract{
Username: claims.Username,
UserTypeID: claims.UserTypeID,
UserID: claims.UserID,
Token: tokeString,
}, nil
}
func (tm *TokenMiddleware) VerifyToken(userToken string) (jwt.Claims, error) {
secretENV, err := tm.ReadSecretENV()
if err != nil {
return nil, err
}
token, err := jwt.Parse(userToken, func(token *jwt.Token) (interface{}, error) {
result := []byte(secretENV)
return result, nil
})
if err != nil {
return nil, err
}
return token.Claims, nil
}
func (tm *TokenMiddleware) TokenMiddlewareIsUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
if len(tokenString) == 0 {
tm.Res.CustomJSONRes(w, "Content-Type", "application/json",
http.StatusBadRequest, "error", "token is empty", nil)
return
}
tokenString = strings.Replace(tokenString, "Bearer ", "", 1)
claims, err := tm.VerifyToken(tokenString)
if err != nil {
tm.Res.CustomJSONRes(w, "Content-Type", "application/json",
http.StatusUnauthorized, "error", err.Error(), nil)
return
}
claimsResult := claims.(jwt.MapClaims)
if claimsResult["username"] == nil || claimsResult["user_type_id"] == nil || claimsResult["exp"] == nil {
tm.Res.CustomJSONRes(w, "Content-Type", "application/json",
http.StatusUnauthorized, "error", "unauthorized", nil)
return
}
if intUserType := int(claimsResult["user_type_id"].(float64)); intUserType != 2 {
tm.Res.CustomJSONRes(w, "Content-Type", "application/json",
http.StatusUnauthorized, "error", "only registered user allowed", nil)
return
}
next.ServeHTTP(w, r)
})
}
func (tm *TokenMiddleware) TokenMiddlewareIsAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
if len(tokenString) == 0 {
tm.Res.CustomJSONRes(w, "Content-Type", "application/json",
http.StatusBadRequest, "error", "token is empty", nil)
return
}
tokenString = strings.Replace(tokenString, "Bearer ", "", 1)
claims, err := tm.VerifyToken(tokenString)
if err != nil {
tm.Res.CustomJSONRes(w, "Content-Type", "application/json",
http.StatusUnauthorized, "error", err.Error(), nil)
return
}
claimsResult := claims.(jwt.MapClaims)
if claimsResult["username"] == nil || claimsResult["user_type_id"] == nil || claimsResult["exp"] == nil {
tm.Res.CustomJSONRes(w, "Content-Type", "application/json",
http.StatusUnauthorized, "error", "unauthorized", nil)
return
}
if intUserType := int(claimsResult["user_type_id"].(float64)); intUserType != 1 {
tm.Res.CustomJSONRes(w, "Content-Type", "application/json",
http.StatusUnauthorized, "error", "only registered admin allowed", nil)
return
}
next.ServeHTTP(w, r)
})
}
|
// Copyright 2015 Google Inc. All rights reserved.
//
// 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 android
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"github.com/google/blueprint"
"github.com/google/blueprint/bootstrap"
)
func init() {
RegisterAndroidMkBuildComponents(InitRegistrationContext)
}
func RegisterAndroidMkBuildComponents(ctx RegistrationContext) {
ctx.RegisterSingletonType("androidmk", AndroidMkSingleton)
}
// Deprecated: consider using AndroidMkEntriesProvider instead, especially if you're not going to
// use the Custom function.
type AndroidMkDataProvider interface {
AndroidMk() AndroidMkData
BaseModuleName() string
}
type AndroidMkData struct {
Class string
SubName string
DistFile OptionalPath
OutputFile OptionalPath
Disabled bool
Include string
Required []string
Host_required []string
Target_required []string
Custom func(w io.Writer, name, prefix, moduleDir string, data AndroidMkData)
Extra []AndroidMkExtraFunc
preamble bytes.Buffer
}
type AndroidMkExtraFunc func(w io.Writer, outputFile Path)
// Allows modules to customize their Android*.mk output.
type AndroidMkEntriesProvider interface {
AndroidMkEntries() []AndroidMkEntries
BaseModuleName() string
}
type AndroidMkEntries struct {
Class string
SubName string
DistFile OptionalPath
OutputFile OptionalPath
Disabled bool
Include string
Required []string
Host_required []string
Target_required []string
header bytes.Buffer
footer bytes.Buffer
ExtraEntries []AndroidMkExtraEntriesFunc
ExtraFooters []AndroidMkExtraFootersFunc
EntryMap map[string][]string
entryOrder []string
}
type AndroidMkExtraEntriesFunc func(entries *AndroidMkEntries)
type AndroidMkExtraFootersFunc func(w io.Writer, name, prefix, moduleDir string, entries *AndroidMkEntries)
func (a *AndroidMkEntries) SetString(name, value string) {
if _, ok := a.EntryMap[name]; !ok {
a.entryOrder = append(a.entryOrder, name)
}
a.EntryMap[name] = []string{value}
}
func (a *AndroidMkEntries) SetPath(name string, path Path) {
if _, ok := a.EntryMap[name]; !ok {
a.entryOrder = append(a.entryOrder, name)
}
a.EntryMap[name] = []string{path.String()}
}
func (a *AndroidMkEntries) SetOptionalPath(name string, path OptionalPath) {
if path.Valid() {
a.SetPath(name, path.Path())
}
}
func (a *AndroidMkEntries) AddPath(name string, path Path) {
if _, ok := a.EntryMap[name]; !ok {
a.entryOrder = append(a.entryOrder, name)
}
a.EntryMap[name] = append(a.EntryMap[name], path.String())
}
func (a *AndroidMkEntries) AddOptionalPath(name string, path OptionalPath) {
if path.Valid() {
a.AddPath(name, path.Path())
}
}
func (a *AndroidMkEntries) SetBoolIfTrue(name string, flag bool) {
if flag {
if _, ok := a.EntryMap[name]; !ok {
a.entryOrder = append(a.entryOrder, name)
}
a.EntryMap[name] = []string{"true"}
}
}
func (a *AndroidMkEntries) SetBool(name string, flag bool) {
if _, ok := a.EntryMap[name]; !ok {
a.entryOrder = append(a.entryOrder, name)
}
if flag {
a.EntryMap[name] = []string{"true"}
} else {
a.EntryMap[name] = []string{"false"}
}
}
func (a *AndroidMkEntries) AddStrings(name string, value ...string) {
if len(value) == 0 {
return
}
if _, ok := a.EntryMap[name]; !ok {
a.entryOrder = append(a.entryOrder, name)
}
a.EntryMap[name] = append(a.EntryMap[name], value...)
}
func (a *AndroidMkEntries) fillInEntries(config Config, bpPath string, mod blueprint.Module) {
a.EntryMap = make(map[string][]string)
amod := mod.(Module).base()
name := amod.BaseModuleName()
if a.Include == "" {
a.Include = "$(BUILD_PREBUILT)"
}
a.Required = append(a.Required, amod.commonProperties.Required...)
a.Host_required = append(a.Host_required, amod.commonProperties.Host_required...)
a.Target_required = append(a.Target_required, amod.commonProperties.Target_required...)
// Fill in the header part.
if len(amod.commonProperties.Dist.Targets) > 0 {
distFile := a.DistFile
if !distFile.Valid() {
distFile = a.OutputFile
}
if distFile.Valid() {
dest := filepath.Base(distFile.String())
if amod.commonProperties.Dist.Dest != nil {
var err error
if dest, err = validateSafePath(*amod.commonProperties.Dist.Dest); err != nil {
// This was checked in ModuleBase.GenerateBuildActions
panic(err)
}
}
if amod.commonProperties.Dist.Suffix != nil {
ext := filepath.Ext(dest)
suffix := *amod.commonProperties.Dist.Suffix
dest = strings.TrimSuffix(dest, ext) + suffix + ext
}
if amod.commonProperties.Dist.Dir != nil {
var err error
if dest, err = validateSafePath(*amod.commonProperties.Dist.Dir, dest); err != nil {
// This was checked in ModuleBase.GenerateBuildActions
panic(err)
}
}
goals := strings.Join(amod.commonProperties.Dist.Targets, " ")
fmt.Fprintln(&a.header, ".PHONY:", goals)
fmt.Fprintf(&a.header, "$(call dist-for-goals,%s,%s:%s)\n",
goals, distFile.String(), dest)
}
}
fmt.Fprintln(&a.header, "\ninclude $(CLEAR_VARS)")
// Collect make variable assignment entries.
a.SetString("LOCAL_PATH", filepath.Dir(bpPath))
a.SetString("LOCAL_MODULE", name+a.SubName)
a.SetString("LOCAL_MODULE_CLASS", a.Class)
a.SetString("LOCAL_PREBUILT_MODULE_FILE", a.OutputFile.String())
a.AddStrings("LOCAL_REQUIRED_MODULES", a.Required...)
a.AddStrings("LOCAL_HOST_REQUIRED_MODULES", a.Host_required...)
a.AddStrings("LOCAL_TARGET_REQUIRED_MODULES", a.Target_required...)
if am, ok := mod.(ApexModule); ok {
a.SetBoolIfTrue("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", am.NotAvailableForPlatform())
}
archStr := amod.Arch().ArchType.String()
host := false
switch amod.Os().Class {
case Host:
// Make cannot identify LOCAL_MODULE_HOST_ARCH:= common.
if amod.Arch().ArchType != Common {
a.SetString("LOCAL_MODULE_HOST_ARCH", archStr)
}
host = true
case HostCross:
// Make cannot identify LOCAL_MODULE_HOST_CROSS_ARCH:= common.
if amod.Arch().ArchType != Common {
a.SetString("LOCAL_MODULE_HOST_CROSS_ARCH", archStr)
}
host = true
case Device:
// Make cannot identify LOCAL_MODULE_TARGET_ARCH:= common.
if amod.Arch().ArchType != Common {
if amod.Target().NativeBridge {
hostArchStr := amod.Target().NativeBridgeHostArchName
if hostArchStr != "" {
a.SetString("LOCAL_MODULE_TARGET_ARCH", hostArchStr)
}
} else {
a.SetString("LOCAL_MODULE_TARGET_ARCH", archStr)
}
}
a.AddStrings("LOCAL_INIT_RC", amod.commonProperties.Init_rc...)
a.AddStrings("LOCAL_VINTF_FRAGMENTS", amod.commonProperties.Vintf_fragments...)
a.SetBoolIfTrue("LOCAL_PROPRIETARY_MODULE", Bool(amod.commonProperties.Proprietary))
if Bool(amod.commonProperties.Vendor) || Bool(amod.commonProperties.Soc_specific) {
a.SetString("LOCAL_VENDOR_MODULE", "true")
}
a.SetBoolIfTrue("LOCAL_VENDOR_OVERLAY_MODULE", Bool(amod.commonProperties.Vendor_overlay))
a.SetBoolIfTrue("LOCAL_ODM_MODULE", Bool(amod.commonProperties.Device_specific))
a.SetBoolIfTrue("LOCAL_PRODUCT_MODULE", Bool(amod.commonProperties.Product_specific))
a.SetBoolIfTrue("LOCAL_SYSTEM_EXT_MODULE", Bool(amod.commonProperties.System_ext_specific))
if amod.commonProperties.Owner != nil {
a.SetString("LOCAL_MODULE_OWNER", *amod.commonProperties.Owner)
}
}
if amod.noticeFile.Valid() {
a.SetString("LOCAL_NOTICE_FILE", amod.noticeFile.String())
}
if host {
makeOs := amod.Os().String()
if amod.Os() == Linux || amod.Os() == LinuxBionic {
makeOs = "linux"
}
a.SetString("LOCAL_MODULE_HOST_OS", makeOs)
a.SetString("LOCAL_IS_HOST_MODULE", "true")
}
prefix := ""
if amod.ArchSpecific() {
switch amod.Os().Class {
case Host:
prefix = "HOST_"
case HostCross:
prefix = "HOST_CROSS_"
case Device:
prefix = "TARGET_"
}
if amod.Arch().ArchType != config.Targets[amod.Os()][0].Arch.ArchType {
prefix = "2ND_" + prefix
}
}
for _, extra := range a.ExtraEntries {
extra(a)
}
// Write to footer.
fmt.Fprintln(&a.footer, "include "+a.Include)
blueprintDir := filepath.Dir(bpPath)
for _, footerFunc := range a.ExtraFooters {
footerFunc(&a.footer, name, prefix, blueprintDir, a)
}
}
func (a *AndroidMkEntries) write(w io.Writer) {
if a.Disabled {
return
}
if !a.OutputFile.Valid() {
return
}
w.Write(a.header.Bytes())
for _, name := range a.entryOrder {
fmt.Fprintln(w, name+" := "+strings.Join(a.EntryMap[name], " "))
}
w.Write(a.footer.Bytes())
}
func (a *AndroidMkEntries) FooterLinesForTests() []string {
return strings.Split(string(a.footer.Bytes()), "\n")
}
func AndroidMkSingleton() Singleton {
return &androidMkSingleton{}
}
type androidMkSingleton struct{}
func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
if !ctx.Config().EmbeddedInMake() {
return
}
var androidMkModulesList []blueprint.Module
ctx.VisitAllModulesBlueprint(func(module blueprint.Module) {
androidMkModulesList = append(androidMkModulesList, module)
})
sort.SliceStable(androidMkModulesList, func(i, j int) bool {
return ctx.ModuleName(androidMkModulesList[i]) < ctx.ModuleName(androidMkModulesList[j])
})
transMk := PathForOutput(ctx, "Android"+String(ctx.Config().productVariables.Make_suffix)+".mk")
if ctx.Failed() {
return
}
err := translateAndroidMk(ctx, absolutePath(transMk.String()), androidMkModulesList)
if err != nil {
ctx.Errorf(err.Error())
}
ctx.Build(pctx, BuildParams{
Rule: blueprint.Phony,
Output: transMk,
})
}
func translateAndroidMk(ctx SingletonContext, mkFile string, mods []blueprint.Module) error {
buf := &bytes.Buffer{}
fmt.Fprintln(buf, "LOCAL_MODULE_MAKEFILE := $(lastword $(MAKEFILE_LIST))")
type_stats := make(map[string]int)
for _, mod := range mods {
err := translateAndroidMkModule(ctx, buf, mod)
if err != nil {
os.Remove(mkFile)
return err
}
if amod, ok := mod.(Module); ok && ctx.PrimaryModule(amod) == amod {
type_stats[ctx.ModuleType(amod)] += 1
}
}
keys := []string{}
fmt.Fprintln(buf, "\nSTATS.SOONG_MODULE_TYPE :=")
for k := range type_stats {
keys = append(keys, k)
}
sort.Strings(keys)
for _, mod_type := range keys {
fmt.Fprintln(buf, "STATS.SOONG_MODULE_TYPE +=", mod_type)
fmt.Fprintf(buf, "STATS.SOONG_MODULE_TYPE.%s := %d\n", mod_type, type_stats[mod_type])
}
// Don't write to the file if it hasn't changed
if _, err := os.Stat(absolutePath(mkFile)); !os.IsNotExist(err) {
if data, err := ioutil.ReadFile(absolutePath(mkFile)); err == nil {
matches := buf.Len() == len(data)
if matches {
for i, value := range buf.Bytes() {
if value != data[i] {
matches = false
break
}
}
}
if matches {
return nil
}
}
}
return ioutil.WriteFile(absolutePath(mkFile), buf.Bytes(), 0666)
}
func translateAndroidMkModule(ctx SingletonContext, w io.Writer, mod blueprint.Module) error {
defer func() {
if r := recover(); r != nil {
panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
}
}()
switch x := mod.(type) {
case AndroidMkDataProvider:
return translateAndroidModule(ctx, w, mod, x)
case bootstrap.GoBinaryTool:
return translateGoBinaryModule(ctx, w, mod, x)
case AndroidMkEntriesProvider:
return translateAndroidMkEntriesModule(ctx, w, mod, x)
default:
return nil
}
}
func translateGoBinaryModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
goBinary bootstrap.GoBinaryTool) error {
name := ctx.ModuleName(mod)
fmt.Fprintln(w, ".PHONY:", name)
fmt.Fprintln(w, name+":", goBinary.InstallPath())
fmt.Fprintln(w, "")
return nil
}
func (data *AndroidMkData) fillInData(config Config, bpPath string, mod blueprint.Module) {
// Get the preamble content through AndroidMkEntries logic.
entries := AndroidMkEntries{
Class: data.Class,
SubName: data.SubName,
DistFile: data.DistFile,
OutputFile: data.OutputFile,
Disabled: data.Disabled,
Include: data.Include,
Required: data.Required,
Host_required: data.Host_required,
Target_required: data.Target_required,
}
entries.fillInEntries(config, bpPath, mod)
// preamble doesn't need the footer content.
entries.footer = bytes.Buffer{}
entries.write(&data.preamble)
// copy entries back to data since it is used in Custom
data.Required = entries.Required
data.Host_required = entries.Host_required
data.Target_required = entries.Target_required
}
func translateAndroidModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
provider AndroidMkDataProvider) error {
amod := mod.(Module).base()
if shouldSkipAndroidMkProcessing(amod) {
return nil
}
data := provider.AndroidMk()
if data.Include == "" {
data.Include = "$(BUILD_PREBUILT)"
}
data.fillInData(ctx.Config(), ctx.BlueprintFile(mod), mod)
prefix := ""
if amod.ArchSpecific() {
switch amod.Os().Class {
case Host:
prefix = "HOST_"
case HostCross:
prefix = "HOST_CROSS_"
case Device:
prefix = "TARGET_"
}
if amod.Arch().ArchType != ctx.Config().Targets[amod.Os()][0].Arch.ArchType {
prefix = "2ND_" + prefix
}
}
name := provider.BaseModuleName()
blueprintDir := filepath.Dir(ctx.BlueprintFile(mod))
if data.Custom != nil {
data.Custom(w, name, prefix, blueprintDir, data)
} else {
WriteAndroidMkData(w, data)
}
return nil
}
func WriteAndroidMkData(w io.Writer, data AndroidMkData) {
if data.Disabled {
return
}
if !data.OutputFile.Valid() {
return
}
w.Write(data.preamble.Bytes())
for _, extra := range data.Extra {
extra(w, data.OutputFile.Path())
}
fmt.Fprintln(w, "include "+data.Include)
}
func translateAndroidMkEntriesModule(ctx SingletonContext, w io.Writer, mod blueprint.Module,
provider AndroidMkEntriesProvider) error {
if shouldSkipAndroidMkProcessing(mod.(Module).base()) {
return nil
}
for _, entries := range provider.AndroidMkEntries() {
entries.fillInEntries(ctx.Config(), ctx.BlueprintFile(mod), mod)
entries.write(w)
}
return nil
}
func shouldSkipAndroidMkProcessing(module *ModuleBase) bool {
if !module.commonProperties.NamespaceExportedToMake {
// TODO(jeffrygaston) do we want to validate that there are no modules being
// exported to Kati that depend on this module?
return true
}
return !module.Enabled() ||
module.commonProperties.SkipInstall ||
// Make does not understand LinuxBionic
module.Os() == LinuxBionic
}
|
package binance
import (
"testing"
"github.com/stretchr/testify/suite"
)
type marginOrderServiceTestSuite struct {
baseOrderTestSuite
}
func TestMarginOrderService(t *testing.T) {
suite.Run(t, new(marginOrderServiceTestSuite))
}
func (s *marginOrderServiceTestSuite) TestCreateOrder() {
data := []byte(`{
"symbol": "LTCBTC",
"orderId": 1,
"clientOrderId": "myOrder1",
"transactTime": 1499827319559,
"price": "0.0001",
"origQty": "12.00",
"executedQty": "10.00",
"cummulativeQuoteQty": "10.00",
"status": "FILLED",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "BUY"
}`)
s.mockDo(data, nil)
defer s.assertDo()
symbol := "LTCBTC"
side := SideTypeBuy
orderType := OrderTypeLimit
timeInForce := TimeInForceTypeGTC
quantity := "12.00"
quoteOrderQty := "10.00"
price := "0.0001"
newClientOrderID := "myOrder1"
s.assertReq(func(r *request) {
e := newSignedRequest().setFormParams(params{
"symbol": symbol,
"side": side,
"type": orderType,
"timeInForce": timeInForce,
"quantity": quantity,
"quoteOrderQty": quoteOrderQty,
"price": price,
"newClientOrderId": newClientOrderID,
"sideEffectType": SideEffectTypeNoSideEffect,
})
s.assertRequestEqual(e, r)
})
res, err := s.client.NewCreateMarginOrderService().Symbol(symbol).Side(side).
Type(orderType).TimeInForce(timeInForce).Quantity(quantity).QuoteOrderQty(quoteOrderQty).
Price(price).NewClientOrderID(newClientOrderID).SideEffectType(SideEffectTypeNoSideEffect).
Do(newContext())
s.r().NoError(err)
e := &CreateOrderResponse{
Symbol: "LTCBTC",
OrderID: 1,
ClientOrderID: "myOrder1",
TransactTime: 1499827319559,
Price: "0.0001",
OrigQuantity: "12.00",
ExecutedQuantity: "10.00",
CummulativeQuoteQuantity: "10.00",
Status: OrderStatusTypeFilled,
TimeInForce: TimeInForceTypeGTC,
Type: OrderTypeLimit,
Side: SideTypeBuy,
}
s.assertCreateOrderResponseEqual(e, res)
}
func (s *marginOrderServiceTestSuite) TestCreateOrderFull() {
data := []byte(`{
"symbol": "LTCBTC",
"orderId": 1,
"clientOrderId": "myOrder1",
"transactTime": 1499827319559,
"price": "0.0001",
"origQty": "12.00",
"executedQty": "10.00",
"cummulativeQuoteQty": "10.00",
"status": "FILLED",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "BUY",
"fills": [
{
"price":"0.00002991",
"qty":"344.00000000",
"commission":"0.00332384",
"commissionAsset":"BNB",
"tradeId":1566397
}
]
}`)
s.mockDo(data, nil)
defer s.assertDo()
symbol := "LTCBTC"
side := SideTypeBuy
orderType := OrderTypeLimit
timeInForce := TimeInForceTypeGTC
quantity := "12.00"
quoteOrderQty := "10.00"
price := "0.0001"
newClientOrderID := "myOrder1"
newOrderRespType := NewOrderRespTypeFULL
s.assertReq(func(r *request) {
e := newSignedRequest().setFormParams(params{
"symbol": symbol,
"side": side,
"type": orderType,
"timeInForce": timeInForce,
"quantity": quantity,
"quoteOrderQty": quoteOrderQty,
"price": price,
"newClientOrderId": newClientOrderID,
"newOrderRespType": newOrderRespType,
})
s.assertRequestEqual(e, r)
})
res, err := s.client.NewCreateMarginOrderService().Symbol(symbol).Side(side).
Type(orderType).TimeInForce(timeInForce).Quantity(quantity).QuoteOrderQty(quoteOrderQty).
Price(price).NewClientOrderID(newClientOrderID).
NewOrderRespType(newOrderRespType).Do(newContext())
s.r().NoError(err)
e := &CreateOrderResponse{
Symbol: "LTCBTC",
OrderID: 1,
ClientOrderID: "myOrder1",
TransactTime: 1499827319559,
Price: "0.0001",
OrigQuantity: "12.00",
ExecutedQuantity: "10.00",
CummulativeQuoteQuantity: "10.00",
Status: OrderStatusTypeFilled,
TimeInForce: TimeInForceTypeGTC,
Type: OrderTypeLimit,
Side: SideTypeBuy,
Fills: []*Fill{
{
Price: "0.00002991",
Quantity: "344.00000000",
Commission: "0.00332384",
CommissionAsset: "BNB",
},
},
}
s.assertCreateOrderResponseEqual(e, res)
}
func (s *marginOrderServiceTestSuite) TestCancelOrder() {
data := []byte(`{
"symbol": "LTCBTC",
"orderId": "28",
"origClientOrderId": "myOrder1",
"clientOrderId": "cancelMyOrder1",
"transactTime": 1507725176595,
"price": "1.00000000",
"origQty": "10.00000000",
"executedQty": "8.00000000",
"cummulativeQuoteQty": "8.00000000",
"status": "CANCELED",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "SELL"
}`)
s.mockDo(data, nil)
defer s.assertDo()
symbol := "LTCBTC"
orderID := int64(28)
origClientOrderID := "myOrder1"
newClientOrderID := "cancelMyOrder1"
s.assertReq(func(r *request) {
e := newSignedRequest().setFormParams(params{
"symbol": symbol,
"orderId": orderID,
"origClientOrderId": origClientOrderID,
"newClientOrderId": newClientOrderID,
})
s.assertRequestEqual(e, r)
})
res, err := s.client.NewCancelMarginOrderService().Symbol(symbol).
OrderID(orderID).OrigClientOrderID(origClientOrderID).
NewClientOrderID(newClientOrderID).Do(newContext())
r := s.r()
r.NoError(err)
e := &CancelMarginOrderResponse{
Symbol: "LTCBTC",
OrderID: "28",
OrigClientOrderID: "myOrder1",
ClientOrderID: "cancelMyOrder1",
TransactTime: 1507725176595,
Price: "1.00000000",
OrigQuantity: "10.00000000",
ExecutedQuantity: "8.00000000",
CummulativeQuoteQuantity: "8.00000000",
Status: OrderStatusTypeCanceled,
TimeInForce: TimeInForceTypeGTC,
Type: OrderTypeLimit,
Side: SideTypeSell,
}
s.assertCancelMarginOrderResponseEqual(e, res)
}
func (s *marginOrderServiceTestSuite) TestGetOrder() {
data := []byte(`{
"symbol": "LTCBTC",
"orderId": 1,
"clientOrderId": "myOrder1",
"price": "0.1",
"origQty": "1.0",
"executedQty": "0.0",
"cummulativeQuoteQty": "0.0",
"status": "NEW",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "BUY",
"stopPrice": "0.0",
"icebergQty": "0.0",
"time": 1499827319559,
"updateTime": 1499827319559,
"isWorking": true
}`)
s.mockDo(data, nil)
defer s.assertDo()
symbol := "LTCBTC"
orderID := int64(1)
origClientOrderID := "myOrder1"
s.assertReq(func(r *request) {
e := newSignedRequest().setParams(params{
"symbol": symbol,
"orderId": orderID,
"origClientOrderId": origClientOrderID,
})
s.assertRequestEqual(e, r)
})
order, err := s.client.NewGetMarginOrderService().Symbol(symbol).
OrderID(orderID).OrigClientOrderID(origClientOrderID).Do(newContext())
r := s.r()
r.NoError(err)
e := &Order{
Symbol: "LTCBTC",
OrderID: 1,
ClientOrderID: "myOrder1",
Price: "0.1",
OrigQuantity: "1.0",
ExecutedQuantity: "0.0",
CummulativeQuoteQuantity: "0.0",
Status: OrderStatusTypeNew,
TimeInForce: TimeInForceTypeGTC,
Type: OrderTypeLimit,
Side: SideTypeBuy,
StopPrice: "0.0",
IcebergQuantity: "0.0",
Time: 1499827319559,
UpdateTime: 1499827319559,
IsWorking: true,
}
s.assertOrderEqual(e, order)
}
func (s *marginOrderServiceTestSuite) TestListMarginOpenOrders() {
data := []byte(`[
{
"clientOrderId": "qhcZw71gAkCCTv0t0k8LUK",
"cummulativeQuoteQty": "0.00000000",
"executedQty": "0.00000000",
"icebergQty": "0.00000000",
"isWorking": true,
"orderId": 211842552,
"origQty": "0.30000000",
"price": "0.00475010",
"side": "SELL",
"status": "NEW",
"stopPrice": "0.00000000",
"symbol": "BNBBTC",
"time": 1562040170089,
"timeInForce": "GTC",
"type": "LIMIT",
"updateTime": 1562040170089
}
]`)
s.mockDo(data, nil)
defer s.assertDo()
symbol := "BNBBTC"
recvWindow := int64(1000)
s.assertReq(func(r *request) {
e := newSignedRequest().setParams(params{
"symbol": symbol,
"recvWindow": recvWindow,
})
s.assertRequestEqual(e, r)
})
orders, err := s.client.NewListMarginOpenOrdersService().Symbol(symbol).
Do(newContext(), WithRecvWindow(recvWindow))
r := s.r()
r.NoError(err)
r.Len(orders, 1)
e := &Order{
Symbol: "BNBBTC",
OrderID: 211842552,
ClientOrderID: "qhcZw71gAkCCTv0t0k8LUK",
CummulativeQuoteQuantity: "0.00000000",
Price: "0.00475010",
OrigQuantity: "0.30000000",
ExecutedQuantity: "0.00000000",
Status: OrderStatusTypeNew,
TimeInForce: TimeInForceTypeGTC,
Type: OrderTypeLimit,
Side: SideTypeSell,
StopPrice: "0.00000000",
IcebergQuantity: "0.00000000",
Time: 1562040170089,
UpdateTime: 1562040170089,
IsWorking: true,
}
s.assertOrderEqual(e, orders[0])
}
func (s *marginOrderServiceTestSuite) TestListMarginOrders() {
data := []byte(`[
{
"orderId": 43123876,
"price": "0.00395740",
"origQty": "4.06000000",
"cummulativeQuoteQty": "0.01606704",
"symbol": "BNBBTC",
"time": 1556089977693
},
{
"orderId": 43123877,
"price": "0.00395740",
"origQty": "0.77000000",
"cummulativeQuoteQty": "0.00304719",
"symbol": "BNBBTC",
"time": 1556089977693
},
{
"orderId": 43253549,
"price": "0.00428930",
"origQty": "23.30000000",
"cummulativeQuoteQty": "0.09994069",
"symbol": "BNBBTC",
"time": 1556163963504
}
]`)
s.mockDo(data, nil)
defer s.assertDo()
symbol := "BNBBTC"
limit := 3
startTime := int64(1556089977693)
endTime := int64(1556163963504)
s.assertReq(func(r *request) {
e := newSignedRequest().setParams(params{
"symbol": symbol,
"startTime": startTime,
"endTime": endTime,
"limit": limit,
})
s.assertRequestEqual(e, r)
})
orders, err := s.client.NewListMarginOrdersService().Symbol(symbol).
StartTime(startTime).EndTime(endTime).
Limit(limit).Do(newContext())
r := s.r()
r.NoError(err)
r.Len(orders, 3)
e := []*Order{
{
OrderID: 43123876,
Price: "0.00395740",
OrigQuantity: "4.06000000",
CummulativeQuoteQuantity: "0.01606704",
Symbol: "BNBBTC",
Time: 1556089977693,
},
{
OrderID: 43123877,
Price: "0.00395740",
OrigQuantity: "0.77000000",
CummulativeQuoteQuantity: "0.00304719",
Symbol: "BNBBTC",
Time: 1556089977693,
},
{
OrderID: 43253549,
Price: "0.00428930",
OrigQuantity: "23.30000000",
CummulativeQuoteQuantity: "0.09994069",
Symbol: "BNBBTC",
Time: 1556163963504,
},
}
s.r().Len(orders, len(e))
for i := 0; i < len(orders); i++ {
s.assertMarginAllOrderEqual(e[i], orders[i])
}
}
func (s *marginOrderServiceTestSuite) assertMarginAllOrderEqual(e, a *Order) {
r := s.r()
r.Equal(e.OrderID, a.OrderID, "OrderID")
r.Equal(e.Price, a.Price, "Price")
r.Equal(e.OrigQuantity, a.OrigQuantity, "OrigQuantity")
r.Equal(e.CummulativeQuoteQuantity, a.CummulativeQuoteQuantity, "CummulativeQuoteQuantity")
r.Equal(e.Symbol, a.Symbol, "Symbol")
r.Equal(e.Time, a.Time, "Time")
}
func (s *marginOrderServiceTestSuite) assertCancelMarginOrderResponseEqual(e, a *CancelMarginOrderResponse) {
r := s.r()
r.Equal(e.Symbol, a.Symbol, "Symbol")
r.Equal(e.OrderID, a.OrderID, "OrderID")
r.Equal(e.OrigClientOrderID, a.OrigClientOrderID, "OrigClientOrderID")
r.Equal(e.ClientOrderID, a.ClientOrderID, "ClientOrderID")
r.Equal(e.TransactTime, a.TransactTime, "TransactTime")
r.Equal(e.Price, a.Price, "Price")
r.Equal(e.OrigQuantity, a.OrigQuantity, "OrigQuantity")
r.Equal(e.ExecutedQuantity, a.ExecutedQuantity, "ExecutedQuantity")
r.Equal(e.CummulativeQuoteQuantity, a.CummulativeQuoteQuantity, "CummulativeQuoteQuantity")
r.Equal(e.Status, a.Status, "Status")
r.Equal(e.TimeInForce, a.TimeInForce, "TimeInForce")
r.Equal(e.Type, a.Type, "Type")
r.Equal(e.Side, a.Side, "Side")
}
func (s *marginOrderServiceTestSuite) TestCreateOCO() {
data := []byte(`{
"orderListId": 0,
"contingencyType": "OCO",
"listStatusType": "EXEC_STARTED",
"listOrderStatus": "EXECUTING",
"listClientOrderId": "C3wyj4WVEktd7u9aVBRXcN",
"transactionTime": 1574040868128,
"symbol": "LTCBTC",
"marginBuyBorrowAmount": "5",
"marginBuyBorrowAsset": "BTC",
"isIsolated": true,
"orders": [
{
"symbol": "LTCBTC",
"orderId": 2,
"clientOrderId": "pO9ufTiFGg3nw2fOdgeOXa"
},
{
"symbol": "LTCBTC",
"orderId": 3,
"clientOrderId": "TXOvglzXuaubXAaENpaRCB"
}
],
"orderReports": [
{
"symbol": "LTCBTC",
"orderId": 2,
"orderListId": 0,
"clientOrderId": "unfWT8ig8i0uj6lPuYLez6",
"transactTime": 1563417480525,
"price": "1.00000000",
"origQty": "10.00000000",
"executedQty": "0.00000000",
"cummulativeQuoteQty": "0.00000000",
"status": "NEW",
"timeInForce": "GTC",
"type": "STOP_LOSS",
"side": "SELL",
"stopPrice": "1.00000000"
},
{
"symbol": "LTCBTC",
"orderId": 3,
"orderListId": 0,
"clientOrderId": "unfWT8ig8i0uj6lPuYLez6",
"transactTime": 1563417480525,
"price": "3.00000000",
"origQty": "10.00000000",
"executedQty": "0.00000000",
"cummulativeQuoteQty": "0.00000000",
"status": "NEW",
"timeInForce": "GTC",
"type": "LIMIT_MAKER",
"side": "SELL"
}
]
}`)
s.mockDo(data, nil)
defer s.assertDo()
symbol := "LTCBTC"
isIsolated := true
side := SideTypeBuy
timeInForce := TimeInForceTypeGTC
quantity := "10"
price := "3"
stopPrice := "3.1"
stopLimitPrice := "3.2"
limitClientOrderID := "myOrder1"
newOrderRespType := NewOrderRespTypeFULL
sideEffectType := SideEffectTypeMarginBuy
s.assertReq(func(r *request) {
e := newSignedRequest().setFormParams(params{
"symbol": symbol,
"isIsolated": "TRUE",
"side": side,
"quantity": quantity,
"price": price,
"stopPrice": stopPrice,
"stopLimitPrice": stopLimitPrice,
"stopLimitTimeInForce": timeInForce,
"limitClientOrderId": limitClientOrderID,
"newOrderRespType": newOrderRespType,
"sideEffectType": sideEffectType,
})
s.assertRequestEqual(e, r)
})
res, err := s.client.NewCreateMarginOCOService().
Symbol(symbol).
IsIsolated(isIsolated).
Side(side).
Quantity(quantity).
Price(price).
StopPrice(stopPrice).
StopLimitPrice(stopLimitPrice).
StopLimitTimeInForce(timeInForce).
LimitClientOrderID(limitClientOrderID).
NewOrderRespType(newOrderRespType).
SideEffectType(sideEffectType).
Do(newContext())
s.r().NoError(err)
e := &CreateMarginOCOResponse{
OrderListID: 0,
ContingencyType: "OCO",
ListStatusType: "EXEC_STARTED",
ListOrderStatus: "EXECUTING",
ListClientOrderID: "C3wyj4WVEktd7u9aVBRXcN",
TransactionTime: 1574040868128,
Symbol: "LTCBTC",
MarginBuyBorrowAmount: "5",
MarginBuyBorrowAsset: "BTC",
IsIsolated: true,
Orders: []*MarginOCOOrder{
&MarginOCOOrder{
Symbol: "LTCBTC",
OrderID: 2,
ClientOrderID: "pO9ufTiFGg3nw2fOdgeOXa",
},
&MarginOCOOrder{
Symbol: "LTCBTC",
OrderID: 3,
ClientOrderID: "TXOvglzXuaubXAaENpaRCB",
},
},
OrderReports: []*MarginOCOOrderReport{
&MarginOCOOrderReport{
Symbol: "LTCBTC",
OrderID: 2,
OrderListID: 0,
ClientOrderID: "unfWT8ig8i0uj6lPuYLez6",
Price: "1.00000000",
OrigQuantity: "10.00000000",
ExecutedQuantity: "0.00000000",
CummulativeQuoteQuantity: "0.00000000",
Status: OrderStatusTypeNew,
TimeInForce: TimeInForceTypeGTC,
Type: OrderTypeStopLoss,
Side: SideTypeSell,
StopPrice: "1.00000000",
},
&MarginOCOOrderReport{
Symbol: "LTCBTC",
OrderID: 3,
OrderListID: 0,
ClientOrderID: "unfWT8ig8i0uj6lPuYLez6",
Price: "3.00000000",
OrigQuantity: "10.00000000",
ExecutedQuantity: "0.00000000",
CummulativeQuoteQuantity: "0.00000000",
Status: OrderStatusTypeNew,
TimeInForce: TimeInForceTypeGTC,
Type: OrderTypeLimitMaker,
Side: SideTypeSell,
},
},
}
s.assertCreateMarginOCOResponseEqual(e, res)
}
func (s *marginOrderServiceTestSuite) assertCreateMarginOCOResponseEqual(e, a *CreateMarginOCOResponse) {
r := s.r()
r.Equal(e.ContingencyType, a.ContingencyType, "ContingencyType")
r.Equal(e.ListClientOrderID, a.ListClientOrderID, "ListClientOrderID")
r.Equal(e.ListOrderStatus, a.ListOrderStatus, "ListOrderStatus")
r.Equal(e.ListStatusType, a.ListStatusType, "ListStatusType")
r.Equal(e.OrderListID, a.OrderListID, "OrderListID")
r.Equal(e.TransactionTime, a.TransactionTime, "TransactionTime")
r.Equal(e.Symbol, a.Symbol, "Symbol")
r.Equal(e.MarginBuyBorrowAmount, a.MarginBuyBorrowAmount, "MarginBuyBorrowAmount")
r.Equal(e.MarginBuyBorrowAsset, a.MarginBuyBorrowAsset, "MarginBuyBorrowAsset")
r.Equal(e.IsIsolated, a.IsIsolated, "IsIsolated")
r.Len(a.OrderReports, len(e.OrderReports))
for idx, orderReport := range e.OrderReports {
s.assertMarginOCOOrderReportEqual(orderReport, a.OrderReports[idx])
}
r.Len(a.Orders, len(e.Orders))
for idx, order := range e.Orders {
s.assertMarginOCOOrderEqual(order, a.Orders[idx])
}
}
func (s *marginOrderServiceTestSuite) assertMarginOCOOrderReportEqual(e, a *MarginOCOOrderReport) {
r := s.r()
r.Equal(e.ClientOrderID, a.ClientOrderID, "ClientOrderID")
r.Equal(e.CummulativeQuoteQuantity, a.CummulativeQuoteQuantity, "CummulativeQuoteQuantity")
r.Equal(e.ExecutedQuantity, a.ExecutedQuantity, "ExecutedQuantity")
r.Equal(e.OrderID, a.OrderID, "OrderID")
r.Equal(e.OrderListID, a.OrderListID, "OrderListID")
r.Equal(e.OrigQuantity, a.OrigQuantity, "OrigQuantity")
r.Equal(e.Price, a.Price, "Price")
r.Equal(e.Side, a.Side, "Side")
r.Equal(e.Status, a.Status, "Status")
r.Equal(e.Symbol, a.Symbol, "Symbol")
// r.Equal(e.TimeInForce, a.TimeInForce, "TimeInForce")
r.Equal(e.TransactionTime, a.TransactionTime, "TransactionTime")
}
func (s *marginOrderServiceTestSuite) assertMarginOCOOrderEqual(e, a *MarginOCOOrder) {
r := s.r()
r.Equal(e.ClientOrderID, a.ClientOrderID, "ClientOrderID")
r.Equal(e.OrderID, a.OrderID, "OrderID")
r.Equal(e.Symbol, a.Symbol, "Symbol")
}
func (s *marginOrderServiceTestSuite) TestCancelOCO() {
data := []byte(`{
"orderListId":1000,
"contingencyType":"OCO",
"listStatusType":"ALL_DONE",
"listOrderStatus":"ALL_DONE",
"listClientOrderId":"C3wyj4WVEktd7u9aVBRXcN",
"transactionTime":1614272133000,
"symbol":"LTCBTC",
"isIsolated":true,
"orders":[
{
"symbol":"LTCBTC",
"orderId":1100,
"clientOrderId":"pO9ufTiFGg3nw2fOdgeOXa"
},
{
"symbol":"LTCBTC",
"orderId":1010,
"clientOrderId":"TXOvglzXuaubXAaENpaRCB"
}
],
"orderReports":[
{
"symbol":"LTCBTC",
"origClientOrderId":"pO9ufTiFGg3nw2fOdgeOXa",
"orderId":1100,
"orderListId":1000,
"clientOrderId":"unfWT8ig8i0uj6lPuYLez6",
"price":"50000.00000000",
"origQty":"0.00030000",
"executedQty":"0.00000000",
"cummulativeQuoteQty":"0.00000000",
"status":"CANCELED",
"timeInForce":"GTC",
"type":"STOP_LOSS_LIMIT",
"side":"SELL",
"stopPrice":"50000.00000000"
},
{
"symbol":"LTCBTC",
"origClientOrderId":"TXOvglzXuaubXAaENpaRCB",
"orderId":1010,
"orderListId":1000,
"clientOrderId":"unfWT8ig8i0uj6lPuYLez6",
"price":"52000.00000000",
"origQty":"0.00030000",
"executedQty":"0.00000000",
"cummulativeQuoteQty":"0.00000000",
"status":"CANCELED",
"timeInForce":"GTC",
"type":"LIMIT_MAKER",
"side":"SELL"
}
]
}`)
s.mockDo(data, nil)
defer s.assertDo()
symbol := "LTCBTC"
listClientOrderID := "C3wyj4WVEktd7u9aVBRXcN"
s.assertReq(func(r *request) {
e := newSignedRequest().setFormParams(params{
"symbol": symbol,
"listClientOrderId": listClientOrderID,
})
s.assertRequestEqual(e, r)
})
res, err := s.client.
NewCancelMarginOCOService().
Symbol(symbol).
ListClientOrderID(listClientOrderID).
Do(newContext())
r := s.r()
r.NoError(err)
e := &CancelMarginOCOResponse{
OrderListID: 1000,
ContingencyType: "OCO",
ListStatusType: "ALL_DONE",
ListOrderStatus: "ALL_DONE",
ListClientOrderID: "C3wyj4WVEktd7u9aVBRXcN",
TransactionTime: 1614272133000,
Symbol: "LTCBTC",
IsIsolated: true,
Orders: []*MarginOCOOrder{
{Symbol: "LTCBTC", OrderID: 1100, ClientOrderID: "pO9ufTiFGg3nw2fOdgeOXa"},
{Symbol: "LTCBTC", OrderID: 1010, ClientOrderID: "TXOvglzXuaubXAaENpaRCB"},
},
OrderReports: []*MarginOCOOrderReport{
{
Symbol: "LTCBTC",
OrderID: 1100,
OrderListID: 1000,
ClientOrderID: "unfWT8ig8i0uj6lPuYLez6",
Price: "50000.00000000",
OrigQuantity: "0.00030000",
ExecutedQuantity: "0.00000000",
CummulativeQuoteQuantity: "0.00000000",
Status: OrderStatusTypeCanceled,
TimeInForce: TimeInForceTypeGTC,
Type: OrderTypeStopLossLimit,
Side: SideTypeSell,
StopPrice: "50000.00000000",
},
{
Symbol: "LTCBTC",
OrderID: 1010,
OrderListID: 1000,
ClientOrderID: "unfWT8ig8i0uj6lPuYLez6",
Price: "52000.00000000",
OrigQuantity: "0.00030000",
ExecutedQuantity: "0.00000000",
CummulativeQuoteQuantity: "0.00000000",
Status: OrderStatusTypeCanceled,
TimeInForce: TimeInForceTypeGTC,
Type: OrderTypeLimitMaker,
Side: SideTypeSell,
},
},
}
s.assertCancelMarginOCOResponseEqual(e, res)
}
func (s *marginOrderServiceTestSuite) assertCancelMarginOCOResponseEqual(e, a *CancelMarginOCOResponse) {
r := s.r()
r.Equal(e.OrderListID, a.OrderListID, "OrderListID")
r.Equal(e.ContingencyType, a.ContingencyType, "ContingencyType")
r.Equal(e.ListStatusType, a.ListStatusType, "ListStatusType")
r.Equal(e.ListOrderStatus, a.ListOrderStatus, "ListOrderStatus")
r.Equal(e.ListClientOrderID, a.ListClientOrderID, "ListClientOrderID")
r.Equal(e.TransactionTime, a.TransactionTime, "TransactionTime")
r.Equal(e.Symbol, a.Symbol, "Symbol")
r.Equal(e.IsIsolated, a.IsIsolated, "IsIsolated")
r.Len(a.OrderReports, len(e.OrderReports))
for idx, orderReport := range e.OrderReports {
s.assertMarginOCOOrderReportEqual(orderReport, a.OrderReports[idx])
}
r.Len(a.Orders, len(e.Orders))
for idx, order := range e.Orders {
s.assertMarginOCOOrderEqual(order, a.Orders[idx])
}
}
|
package main
import "math"
//Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var last = -math.MaxFloat64
func isValidBST(root *TreeNode) bool {
if root == nil {
return true
}
if isValidBST(root.Left) {
if last < root.Val {
last = root.Val
return isValidBST(root.Right)
}
}
return false
}
|
use std::str::FromStr;
use metalog::{set_logger, Log, LogLevelFilter, LogMetadata, LogRecord,
MaxLogLevelFilter};
struct Logger { max_log_level: MaxLogLevelFilter }
impl Log for Logger {
fn enabled(&self, metadata: &LogMetadata) -> bool {
metadata.level() <= self.max_log_level.get()
}
fn log(&self, record: &LogRecord) {
if self.enabled(record.metadata()) {
println!("{}: {}", record.level(), record.args());
}
}
}
pub fn init(log_level: &str) {
set_logger(|max_ll| {
max_ll.set(LogLevelFilter::from_str(log_level)
.unwrap_or(LogLevelFilter::Error));
Box::new(Logger { max_log_level: max_ll })
}).unwrap();
}
|
package aoc2015
import (
"testing"
aoc "github.com/janreggie/aoc/internal"
"github.com/stretchr/testify/assert"
)
func TestDay17(t *testing.T) {
assert := assert.New(t)
testCases := []aoc.TestCase{
{Details: "Y2019D17 sample input",
Input: day17myInput,
Result1: "654",
Result2: "57"},
}
for _, tt := range testCases {
tt.Test(Day17, assert)
}
}
func BenchmarkDay17(b *testing.B) {
aoc.Benchmark(Day17, b, day17myInput)
}
|
package nsm
import (
nsmv1alpha1 "github.com/acmenezes/nsm-operator/pkg/apis/nsm/v1alpha1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
func (r *ReconcileNSM) serviceForWebhook(nsm *nsmv1alpha1.NSM) *corev1.Service {
service := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: webhookServiceName,
Namespace: nsm.Namespace,
Labels: labelsForNSMAdmissionWebhook(nsm.Name),
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{Name: webhookName + "-port", Port: webhookServicePort, TargetPort: intstr.FromInt(webhookServiceTargetPort)},
},
Selector: map[string]string{"app": webhookName},
},
}
// Set NSM instance as the owner and controller
controllerutil.SetControllerReference(nsm, service, r.scheme)
return service
}
|
package main
import (
. "foo"
)
func 界() {
return
}
func main() {
Bla(1)
界()
}
|
package middleware
import (
"context"
"encoding/json"
"net/http"
"strconv"
"github.com/lokichoggio/gateway/internal/types"
"github.com/tal-tech/go-zero/core/metric"
"github.com/tal-tech/go-zero/core/trace/tracespec"
)
const (
SuccessCode = 0
)
// A WithBodyResponseWriter is a helper to delay sealing a http.ResponseWriter on writing body.
type WithBodyResponseWriter struct {
Writer http.ResponseWriter
Body []byte
}
// Header returns the http header.
func (w *WithBodyResponseWriter) Header() http.Header {
return w.Writer.Header()
}
// Write writes bytes into w.
func (w *WithBodyResponseWriter) Write(bytes []byte) (int, error) {
w.Body = bytes
return w.Writer.Write(bytes)
}
// WriteHeader writes code into w, and not sealing the writer.
func (w *WithBodyResponseWriter) WriteHeader(code int) {
w.Writer.WriteHeader(code)
}
const serverNamespace = "http_server"
var metricServiceCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
Namespace: serverNamespace,
Subsystem: "requests",
Name: "service_code_total",
Help: "http server requests status code count.",
Labels: []string{"path", "code", "trace"},
})
func traceIdFromContext(ctx context.Context) string {
t, ok := ctx.Value(tracespec.TracingKey).(tracespec.Trace)
if !ok {
return ""
}
return t.TraceId()
}
func ServiceMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
bw := &WithBodyResponseWriter{Writer: w}
defer func() {
resp := types.BaseResp{}
_ = json.Unmarshal(bw.Body, &resp)
metricServiceCodeTotal.Inc(r.URL.Path, strconv.FormatInt(resp.ErrCode, 10), traceIdFromContext(r.Context()))
}()
next.ServeHTTP(bw, r)
}
}
|
package model
//User is a structure with user's data
type User struct {
Email string
Password string
EncryptedPassword string
}
|
package drivers
import (
"testing"
"github.com/volatiletech/strmangle"
)
type testMockDriver struct{}
func (m testMockDriver) TranslateColumnType(c Column) Column { return c }
func (m testMockDriver) UseLastInsertID() bool { return false }
func (m testMockDriver) UseTopClause() bool { return false }
func (m testMockDriver) Open() error { return nil }
func (m testMockDriver) Close() {}
func (m testMockDriver) TableNames(schema string, whitelist, blacklist []string) ([]string, error) {
if len(whitelist) > 0 {
return whitelist, nil
}
tables := []string{"pilots", "jets", "airports", "licenses", "hangars", "languages", "pilot_languages"}
return strmangle.SetComplement(tables, blacklist), nil
}
// Columns returns a list of mock columns
func (m testMockDriver) Columns(schema, tableName string, whitelist, blacklist []string) ([]Column, error) {
return map[string][]Column{
"pilots": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "name", Type: "string", DBType: "character"},
},
"airports": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "size", Type: "null.Int", DBType: "integer", Nullable: true},
},
"jets": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "pilot_id", Type: "int", DBType: "integer", Nullable: true, Unique: true},
{Name: "airport_id", Type: "int", DBType: "integer"},
{Name: "name", Type: "string", DBType: "character", Nullable: false},
{Name: "color", Type: "null.String", DBType: "character", Nullable: true},
{Name: "uuid", Type: "string", DBType: "uuid", Nullable: true},
{Name: "identifier", Type: "string", DBType: "uuid", Nullable: false},
{Name: "cargo", Type: "[]byte", DBType: "bytea", Nullable: false},
{Name: "manifest", Type: "[]byte", DBType: "bytea", Nullable: true, Unique: true},
},
"licenses": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "pilot_id", Type: "int", DBType: "integer"},
},
"hangars": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "name", Type: "string", DBType: "character", Nullable: true, Unique: true},
{Name: "hangar_id", Type: "int", DBType: "integer", Nullable: true},
},
"languages": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "language", Type: "string", DBType: "character", Nullable: false, Unique: true},
},
"pilot_languages": {
{Name: "pilot_id", Type: "int", DBType: "integer"},
{Name: "language_id", Type: "int", DBType: "integer"},
},
}[tableName], nil
}
// ForeignKeyInfo returns a list of mock foreignkeys
func (m testMockDriver) ForeignKeyInfo(schema, tableName string) ([]ForeignKey, error) {
return map[string][]ForeignKey{
"jets": {
{Table: "jets", Name: "jets_pilot_id_fk", Column: "pilot_id", ForeignTable: "pilots", ForeignColumn: "id", ForeignColumnUnique: true},
{Table: "jets", Name: "jets_airport_id_fk", Column: "airport_id", ForeignTable: "airports", ForeignColumn: "id"},
},
"licenses": {
{Table: "licenses", Name: "licenses_pilot_id_fk", Column: "pilot_id", ForeignTable: "pilots", ForeignColumn: "id"},
},
"pilot_languages": {
{Table: "pilot_languages", Name: "pilot_id_fk", Column: "pilot_id", ForeignTable: "pilots", ForeignColumn: "id"},
{Table: "pilot_languages", Name: "jet_id_fk", Column: "language_id", ForeignTable: "languages", ForeignColumn: "id"},
},
"hangars": {
{Table: "hangars", Name: "hangar_fk_id", Column: "hangar_id", ForeignTable: "hangars", ForeignColumn: "id"},
},
}[tableName], nil
}
// PrimaryKeyInfo returns mock primary key info for the passed in table name
func (m testMockDriver) PrimaryKeyInfo(schema, tableName string) (*PrimaryKey, error) {
return map[string]*PrimaryKey{
"pilots": {Name: "pilot_id_pkey", Columns: []string{"id"}},
"airports": {Name: "airport_id_pkey", Columns: []string{"id"}},
"jets": {Name: "jet_id_pkey", Columns: []string{"id"}},
"licenses": {Name: "license_id_pkey", Columns: []string{"id"}},
"hangars": {Name: "hangar_id_pkey", Columns: []string{"id"}},
"languages": {Name: "language_id_pkey", Columns: []string{"id"}},
"pilot_languages": {Name: "pilot_languages_pkey", Columns: []string{"pilot_id", "language_id"}},
}[tableName], nil
}
// RightQuote is the quoting character for the right side of the identifier
func (m testMockDriver) RightQuote() byte {
return '"'
}
// LeftQuote is the quoting character for the left side of the identifier
func (m testMockDriver) LeftQuote() byte {
return '"'
}
// UseIndexPlaceholders returns true to indicate fake support of indexed placeholders
func (m testMockDriver) UseIndexPlaceholders() bool {
return false
}
func TestTables(t *testing.T) {
t.Parallel()
tables, err := TablesConcurrently(testMockDriver{}, "public", nil, nil, 1)
if err != nil {
t.Error(err)
}
if len(tables) != 7 {
t.Errorf("Expected len 7, got: %d\n", len(tables))
}
prev := ""
for i := range tables {
if prev >= tables[i].Name {
t.Error("tables are not sorted")
}
prev = tables[i].Name
}
pilots := GetTable(tables, "pilots")
if len(pilots.Columns) != 2 {
t.Error()
}
if pilots.ToOneRelationships[0].ForeignTable != "jets" {
t.Error("want a to many to jets")
}
if pilots.ToManyRelationships[0].ForeignTable != "licenses" {
t.Error("want a to many to languages")
}
if pilots.ToManyRelationships[1].ForeignTable != "languages" {
t.Error("want a to many to languages")
}
jets := GetTable(tables, "jets")
if len(jets.ToManyRelationships) != 0 {
t.Error("want no to many relationships")
}
languages := GetTable(tables, "pilot_languages")
if !languages.IsJoinTable {
t.Error("languages is a join table")
}
hangars := GetTable(tables, "hangars")
if len(hangars.ToManyRelationships) != 1 || hangars.ToManyRelationships[0].ForeignTable != "hangars" {
t.Error("want 1 to many relationships")
}
if len(hangars.FKeys) != 1 || hangars.FKeys[0].ForeignTable != "hangars" {
t.Error("want one hangar foreign key to itself")
}
}
func TestFilterForeignKeys(t *testing.T) {
t.Parallel()
tables := []Table{
{
Name: "one",
Columns: []Column{
{Name: "id"},
{Name: "two_id"},
{Name: "three_id"},
{Name: "four_id"},
},
FKeys: []ForeignKey{
{Table: "one", Column: "two_id", ForeignTable: "two", ForeignColumn: "id"},
{Table: "one", Column: "three_id", ForeignTable: "three", ForeignColumn: "id"},
{Table: "one", Column: "four_id", ForeignTable: "four", ForeignColumn: "id"},
},
},
{
Name: "two",
Columns: []Column{
{Name: "id"},
},
},
{
Name: "three",
Columns: []Column{
{Name: "id"},
},
},
{
Name: "four",
Columns: []Column{
{Name: "id"},
},
},
}
tests := []struct {
Whitelist []string
Blacklist []string
ExpectFkNum int
}{
{[]string{}, []string{}, 3},
{[]string{"one", "two", "three"}, []string{}, 2},
{[]string{"one.two_id", "two"}, []string{}, 1},
{[]string{"*.two_id", "two"}, []string{}, 1},
{[]string{}, []string{"three", "four"}, 1},
{[]string{}, []string{"three.id"}, 2},
{[]string{}, []string{"one.two_id"}, 2},
{[]string{}, []string{"*.two_id"}, 2},
{[]string{"one", "two"}, []string{"two"}, 0},
}
for i, test := range tests {
table := tables[0]
filterForeignKeys(&table, test.Whitelist, test.Blacklist)
if fkNum := len(table.FKeys); fkNum != test.ExpectFkNum {
t.Errorf("%d) want: %d, got: %d\nTest: %#v", i, test.ExpectFkNum, fkNum, test)
}
}
}
func TestKnownColumn(t *testing.T) {
tests := []struct {
table string
column string
whitelist []string
blacklist []string
expected bool
}{
{"one", "id", []string{"one"}, []string{}, true},
{"one", "id", []string{}, []string{"one"}, false},
{"one", "id", []string{"one.id"}, []string{}, true},
{"one", "id", []string{"one.id"}, []string{"one"}, false},
{"one", "id", []string{"two"}, []string{}, false},
{"one", "id", []string{"two"}, []string{"one"}, false},
{"one", "id", []string{"two.id"}, []string{}, false},
{"one", "id", []string{"*.id"}, []string{}, true},
{"one", "id", []string{"*.id"}, []string{"*.id"}, false},
}
for i, test := range tests {
known := knownColumn(test.table, test.column, test.whitelist, test.blacklist)
if known != test.expected {
t.Errorf("%d) want: %t, got: %t\nTest: %#v", i, test.expected, known, test)
}
}
}
func TestSetIsJoinTable(t *testing.T) {
t.Parallel()
tests := []struct {
Pkey []string
Fkey []string
Should bool
}{
{Pkey: []string{"one", "two"}, Fkey: []string{"one", "two"}, Should: true},
{Pkey: []string{"two", "one"}, Fkey: []string{"one", "two"}, Should: true},
{Pkey: []string{"one"}, Fkey: []string{"one"}, Should: false},
{Pkey: []string{"one", "two", "three"}, Fkey: []string{"one", "two"}, Should: false},
{Pkey: []string{"one", "two", "three"}, Fkey: []string{"one", "two", "three"}, Should: false},
{Pkey: []string{"one"}, Fkey: []string{"one", "two"}, Should: false},
{Pkey: []string{"one", "two"}, Fkey: []string{"one"}, Should: false},
}
for i, test := range tests {
var table Table
table.PKey = &PrimaryKey{Columns: test.Pkey}
for _, k := range test.Fkey {
table.FKeys = append(table.FKeys, ForeignKey{Column: k})
}
setIsJoinTable(&table)
if is := table.IsJoinTable; is != test.Should {
t.Errorf("%d) want: %t, got: %t\nTest: %#v", i, test.Should, is, test)
}
}
}
func TestSetForeignKeyConstraints(t *testing.T) {
t.Parallel()
tables := []Table{
{
Name: "one",
Columns: []Column{
{Name: "id1", Type: "string", Nullable: false, Unique: false},
{Name: "id2", Type: "string", Nullable: true, Unique: true},
},
},
{
Name: "other",
Columns: []Column{
{Name: "one_id_1", Type: "string", Nullable: false, Unique: false},
{Name: "one_id_2", Type: "string", Nullable: true, Unique: true},
},
FKeys: []ForeignKey{
{Column: "one_id_1", ForeignTable: "one", ForeignColumn: "id1"},
{Column: "one_id_2", ForeignTable: "one", ForeignColumn: "id2"},
},
},
}
setForeignKeyConstraints(&tables[0], tables)
setForeignKeyConstraints(&tables[1], tables)
first := tables[1].FKeys[0]
second := tables[1].FKeys[1]
if first.Nullable {
t.Error("should not be nullable")
}
if first.Unique {
t.Error("should not be unique")
}
if first.ForeignColumnNullable {
t.Error("should be nullable")
}
if first.ForeignColumnUnique {
t.Error("should be unique")
}
if !second.Nullable {
t.Error("should be nullable")
}
if !second.Unique {
t.Error("should be unique")
}
if !second.ForeignColumnNullable {
t.Error("should be nullable")
}
if !second.ForeignColumnUnique {
t.Error("should be unique")
}
}
func TestSetRelationships(t *testing.T) {
t.Parallel()
tables := []Table{
{
Name: "one",
Columns: []Column{
{Name: "id", Type: "string"},
},
},
{
Name: "other",
Columns: []Column{
{Name: "other_id", Type: "string"},
},
FKeys: []ForeignKey{{Column: "other_id", ForeignTable: "one", ForeignColumn: "id", Nullable: true}},
},
}
setRelationships(&tables[0], tables)
setRelationships(&tables[1], tables)
if got := len(tables[0].ToManyRelationships); got != 1 {
t.Error("should have a relationship:", got)
}
if got := len(tables[1].ToManyRelationships); got != 0 {
t.Error("should have no to many relationships:", got)
}
rel := tables[0].ToManyRelationships[0]
if rel.Column != "id" {
t.Error("wrong column:", rel.Column)
}
if rel.ForeignTable != "other" {
t.Error("wrong table:", rel.ForeignTable)
}
if rel.ForeignColumn != "other_id" {
t.Error("wrong column:", rel.ForeignColumn)
}
if rel.ToJoinTable {
t.Error("should not be a join table")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.