Compare commits

...

587 Commits

Author SHA1 Message Date
Jeff Regan
51ba54ad82 Revert "helm values on inflator config" 2020-12-07 12:52:31 -08:00
Jeff Regan
4144775a3b Merge pull request #3316 from epcim/helmValuesOnInflatorConfigSpec
helm values on inflator config
2020-12-07 12:51:42 -08:00
Jeff Regan
ff9b215ae7 Update taggedmodule.go 2020-12-07 12:09:09 -08:00
Jeff Regan
cd5ae17335 Merge pull request #3322 from monopole/fixModNames
Fix some plugin module names.
2020-12-07 12:08:14 -08:00
jregan
e3d022325b Fix some plugin module names. 2020-12-07 11:59:13 -08:00
Kubernetes Prow Robot
e6dc03bea4 Merge pull request #3315 from monopole/hoserface
Add more tests
2020-12-07 10:31:11 -08:00
jregan
d08b9c30ee What is this? 2020-12-07 10:16:30 -08:00
Petr Michalec
f6e5eedee2 helm values on inflator config spec. 2020-12-07 13:49:30 +01:00
Jeff Regan
212b2cff12 Merge pull request #3312 from monopole/conflicting
Extract conflict detection to its own interface.
2020-12-06 09:00:41 -08:00
jregan
f66e5bb923 Extract conflict detection to it's own interface.
This PR
 - defines a patch conflict detector interface,
 - extracts implementations of the interface from the
   merginator code, making the merginator code
   independent of --enable_kyaml.
 - injects those implementations into kustomize
   as a function of --enable_kyaml.

So, instead of using different merginators to combine
resmaps, this pr allows the use of a single patch merge
code path that uses different conflict detectors.

So instead of debating how to merge, we're now only
considering whether to warn on conflict detection
in one transformer.

This PR is in service of #3304, eliminating seven
instances where --enable_kyaml was consulted.  These
were cases where conflict detection wasn't an issue
(but merging patches was).
2020-12-06 08:38:45 -08:00
Kubernetes Prow Robot
23bc91f233 Merge pull request #3311 from drewwells/patch-1
absolute path to entrypoint
2020-12-04 18:05:25 -08:00
Drew Wells
9c421c7410 absolute path to entrypoint
Make the kustomize container tolerant of alternative working directory. 
Mounting my project and making it the working directory will now work.

ie. docker run -w /pkg -v $(shell pwd):/pkg kustomize version
2020-12-04 18:27:57 -06:00
Jeff Regan
c63dfd6772 Merge pull request #3310 from monopole/nits
Spelling nits.
2020-12-04 12:30:36 -08:00
jregan
1a5aa63d54 Spelling nits. 2020-12-04 12:29:39 -08:00
Jeff Regan
1583cef8d9 Merge pull request #3309 from monopole/autoUpdate
Automated doc update.
2020-12-04 10:51:54 -08:00
jregan
a7c91c37e9 Automated doc update. 2020-12-04 10:51:22 -08:00
Kubernetes Prow Robot
c1dca7fdb5 Merge pull request #3302 from natasha41575/TestGvknChange
tests for gvkn changing
2020-12-04 10:29:59 -08:00
Natasha Sarkar
724bbe9452 connected allowresourcesidchanges bool to allow_id_changes flag 2020-12-02 18:03:09 -08:00
Natasha Sarkar
deb2b21cbe added allowresourceidchanges bool to options struct 2020-12-02 18:02:09 -08:00
Kubernetes Prow Robot
709f499b44 Merge pull request #3305 from monopole/moreHacking
In PatchStrategicMergeTransformer's test, highlight remaining work
2020-12-02 10:38:50 -08:00
jregan
dbaa2d6092 hacking 2020-12-02 10:23:13 -08:00
Jeff Regan
19ff1b307e Merge pull request #3301 from rumstead/master
[Docs] Fixing README link to kubectl book.
2020-12-01 16:56:25 -08:00
Jeff Regan
55f44a29c6 Update README.md 2020-12-01 16:48:41 -08:00
Jeff Regan
1f1873a6ed Merge pull request #3299 from monopole/demoteReplacementTransformer
Move ReplacementTransformer plugin to untested folder
2020-12-01 12:45:53 -08:00
rumstead
6e3c4ecc72 Update README.md 2020-12-01 13:18:59 -05:00
jregan
c37c7b6b2c Move ReplacementTransformer plugin to untested. 2020-12-01 10:04:00 -08:00
Jeff Regan
42acdcc1d0 Merge pull request #3298 from monopole/makeUntestedPluginDir
Start directory for 'untested' plugins.
2020-12-01 09:52:59 -08:00
jregan
67db23b24b Start directory for 'untested' plugins. 2020-12-01 07:32:44 -08:00
Kubernetes Prow Robot
35a19fb8a9 Merge pull request #3296 from monopole/secretGeneratorTestKYaml
Adjust SecretGeneratorTest to pass with --enable_kyaml
2020-11-30 19:50:57 -08:00
Kubernetes Prow Robot
a6c2e982f9 Merge pull request #3292 from Shell32-Natsu/helm-extra-args
Add field extraArgs to helm generator
2020-11-30 19:50:49 -08:00
Kubernetes Prow Robot
a053ff6907 Merge pull request #3295 from monopole/addSmPatchTests
Add more tests for reswrangler ApplySmPatch
2020-11-30 19:24:50 -08:00
jregan
64201c8352 Adjust SecretGeneratorTest to pass with --enable_kyaml 2020-11-30 19:17:15 -08:00
jregan
d5ce26e423 Patchtransformers - drop copied code, improve deletion handling. 2020-11-30 18:43:35 -08:00
Kubernetes Prow Robot
09497f0830 Merge pull request #3294 from monopole/goSumCatchup
Automated go.sum updates.
2020-11-30 18:42:50 -08:00
jregan
32dd194aca Automated go.sum updates. 2020-11-30 18:16:23 -08:00
Jeff Regan
4122787bd8 Merge pull request #3293 from natasha41575/FixOpenApiInfoSpacing
Made output of `kustomize openapi info` command more readable
2020-11-30 18:15:16 -08:00
Natasha Sarkar
2ccb73a2a3 made output of kustomize openapi info command more readable 2020-11-30 14:56:20 -08:00
Kubernetes Prow Robot
83377cf597 Merge pull request #3291 from monopole/thrashing
Patchtransformers - drop copied code, improve deletion handling.
2020-11-30 14:26:50 -08:00
Donny Xia
2bf73c60c3 Add field extraArgs to helm generator 2020-11-30 14:22:25 -08:00
jregan
4a55a07c14 Patchtransformers - drop copied code, improve deletion handling. 2020-11-30 11:58:43 -08:00
Kubernetes Prow Robot
5279ad904b Merge pull request #3282 from pwittrock/main
Fn framework utilities for parsing templates from directories
2020-11-30 08:42:50 -08:00
Phillip Wittrock
736f110f04 Fn framework template and process options
- Refactor framework code to be simpler
- Add TemplatesFn feature
- Add PreProcessFilters feature
- Add PostProcessFilters features
- Add TemplatesFromDir
- Add PatchTemplatesFromDir
- Add PatchContainerTemplatesFromDir
2020-11-30 08:23:34 -08:00
Jeff Regan
c9ab1270fa Merge pull request #3290 from monopole/idSet
Add resource id set.
2020-11-30 05:42:26 -08:00
jregan
bb5fc9086b Add resource id set. 2020-11-30 05:37:53 -08:00
Kubernetes Prow Robot
e8c85456cc Merge pull request #3279 from monopole/addGeneratedCode
Add label and annotation selector code.
2020-11-28 22:36:48 -08:00
jregan
aa9a397808 Kyaml: disable generation on each build. 2020-11-28 05:55:16 -08:00
jregan
60ea8de5f1 Complete WNode implementation. 2020-11-26 14:48:00 -08:00
jregan
56c8df7b85 Add RNode implementation of label and annotation selectors. 2020-11-26 14:47:23 -08:00
Jeff Regan
a51e4234c4 Merge pull request #3283 from Shell32-Natsu/docker
Add git and openssh in docker image
2020-11-26 08:18:44 -08:00
Jeff Regan
50cd01e5f7 Update Makefile 2020-11-26 07:00:13 -08:00
Jeff Regan
42b082a6b1 Merge pull request #3285 from monopole/improveSelectTest
Add labels to selector test.
2020-11-26 06:57:14 -08:00
jregan
c3cdd15769 Clean up selector test. 2020-11-26 06:36:24 -08:00
Donny Xia
c3a8b6f359 Add git and openssh in docker image 2020-11-25 15:02:47 -08:00
Jeff Regan
4af4483e12 Merge pull request #3281 from Shell32-Natsu/update-go-version
update Go version to 1.15
2020-11-25 14:05:24 -08:00
Donny Xia
8f7bcb9b16 update Go version to 1.15 2020-11-25 12:41:20 -08:00
Jeff Regan
f54d904766 Merge pull request #3277 from monopole/moreRNodeSetters
More RNode setters and WNode delegation
2020-11-25 10:20:06 -08:00
Jeff Regan
ba91b6f79f Merge pull request #3278 from SyamSundarKirubakaran/doc-site-changes
Remove `zh` site contents and redirect to new site
2020-11-25 09:09:07 -08:00
Syam Sundar K
851acafe32 generate site 2020-11-25 21:42:09 +05:30
Syam Sundar K
14eac6020f remove duplicate contents and redirect 2020-11-25 21:41:27 +05:30
Jeff Regan
e45d667b4d Delete .gitattributes
Didn't work as desired.
2020-11-25 07:59:58 -08:00
Jeff Regan
cbdf4a0e43 Update .gitattributes 2020-11-25 07:53:35 -08:00
jregan
aed7e5aaf9 Delegate more from WNode to RNode.
The implementations in WNode are supposed to be thin,
as it will be removed once #2506 closes.

The change also makes some addjustments for the
upcoming flip of the enable_kyaml flag, pointing to
issue #3271.
2020-11-25 07:11:06 -08:00
jregan
ec64ef705b Add metadata getters and setters to RNode.
These setters completely remove the field if the argument
is empty, rather than setting the field to an empty value,
mimicing apimachinery behavior.
2020-11-25 07:03:12 -08:00
Jeff Regan
1e0eb58bc9 Merge pull request #3273 from Shell32-Natsu/reenable-multi-module-check
Re-enable multi-module check
2020-11-24 19:18:16 -08:00
Jeff Regan
fd2fe35863 Merge pull request #3275 from monopole/tryGitAttributes
Start a gitattributes file.
2020-11-24 19:12:23 -08:00
jregan
ebdbd81ed8 Start a gitattributes file. 2020-11-24 18:50:46 -08:00
Donny Xia
c9d2ae6b49 Re-enable multi-module check 2020-11-24 16:29:01 -08:00
Kubernetes Prow Robot
e8c212a10f Merge pull request #3272 from monopole/moreTests
Add more tests around yaml parsing.
2020-11-24 14:34:39 -08:00
jregan
1eb378254a Add more tests around yaml parsing. 2020-11-24 14:15:45 -08:00
Kubernetes Prow Robot
0d030e3095 Merge pull request #3270 from pwittrock/main
Improved fn framework support for patching
2020-11-24 12:22:39 -08:00
Phillip Wittrock
f2706dce68 Improved fn framework support for patching
- Generate patches with a func
- Generate patches for containers
2020-11-24 12:02:55 -08:00
Jeff Regan
f8194bd3c2 Merge pull request #3267 from monopole/generatedCode
Add generated code.
2020-11-23 16:51:41 -08:00
jregan
eb5227680e Add generated code. 2020-11-23 16:47:00 -08:00
Jeff Regan
27e89f271f Merge pull request #3266 from monopole/modsToMakefile
Consistently prefix make targets with clean, generate, build.
2020-11-23 16:37:34 -08:00
jregan
626f2f9d1d Another cleaning target in Makefile. 2020-11-23 16:14:47 -08:00
Jeff Regan
ffda124ca5 Update Makefile 2020-11-23 06:48:53 -08:00
Jeff Regan
fd677f635e Update README.md 2020-11-22 21:01:28 -08:00
Jeff Regan
14b1388c6a Merge pull request #3263 from monopole/useLessReflectionInTests
In some tests, replace reflection with yaml compare.
2020-11-22 20:34:38 -08:00
jregan
5248fd0cd9 In some tests, replace reflection with yaml compare. 2020-11-22 18:48:32 -08:00
Jeff Regan
b6ae9f80d3 Merge pull request #3257 from monopole/binaryData
Secrets and ConfigMaps with binary data in kyaml
2020-11-21 15:11:29 -08:00
Jeff Regan
2ad502d5a8 Merge pull request #3261 from monopole/depProviderInjection
Use DepProvider in tests to access kyaml impls.
2020-11-21 15:07:45 -08:00
jregan
a5f3d5c823 Use DepProvider in tests to access kyaml impls. 2020-11-21 14:49:44 -08:00
Jeff Regan
c65875cacc Merge pull request #3259 from pwittrock/main
fn/framework support for reading from stdin in standalone
2020-11-21 14:44:54 -08:00
Phillip Wittrock
82b2d83ede fn/framework support for reading from stdin in standalone
- speficy '-' to read from stdin when running standalone
2020-11-21 09:17:26 -08:00
Jeff Regan
7e01aec5a4 Update Makefile 2020-11-21 07:14:04 -08:00
Jeff Regan
9e8a84c5ff Merge pull request #3251 from Shell32-Natsu/krm-function-converter
[KRM function converter] Get plugin config from data field
2020-11-21 06:25:42 -08:00
Jeff Regan
849d5c4a8d Merge branch 'master' into krm-function-converter 2020-11-21 06:10:25 -08:00
Jeff Regan
00352cbc58 Merge pull request #3256 from Shell32-Natsu/pluginator-api-version
update module api version in wrapper
2020-11-21 06:09:04 -08:00
jregan
b88e770b1d binary data nope 2020-11-20 17:55:20 -08:00
Jeff Regan
eda7a9f8d6 Merge pull request #3258 from monopole/goSumAutomated
Automated go.sum change.
2020-11-20 17:55:01 -08:00
jregan
114b3f4b00 Automated go.sum change. 2020-11-20 17:18:14 -08:00
Donny Xia
6cb339142d update module api version in wrapper 2020-11-20 16:28:38 -08:00
Kubernetes Prow Robot
052a6b4e96 Merge pull request #3255 from Shell32-Natsu/rnode-format
fix rnode string format converted from resmap
2020-11-20 15:07:33 -08:00
Donny Xia
4add7eccd0 fix rnode string format converted from resmap 2020-11-20 14:34:11 -08:00
Kubernetes Prow Robot
a0a89e1adc Merge pull request #3250 from pwittrock/main
Function framework support for patching containers
2020-11-20 12:42:51 -08:00
Donny Xia
10fd4b4bbe Merge pull request #3252 from runewake2/notes
Update release notes generation
2020-11-20 10:24:03 -08:00
Donny Xia
e15ede037d Merge pull request #3253 from yujunz/remote-build
Fix test against examples
2020-11-20 09:47:47 -08:00
Yujun Zhang
32a2f5ffa9 Fix test against examples
Tests in examples.remoteBuild.md were skipped unexpectedly
2020-11-20 20:10:07 +08:00
Sam Wronski
4f74203f6c Fix variable name: "currentTag" -> "fullTag" 2020-11-19 15:37:39 -08:00
Sam Wronski
5b0cbcb5fb Update release notes generation
- Notes use tags instead commit sha
2020-11-19 14:28:05 -08:00
Donny Xia
2f4c35347e Get plugin config from data field 2020-11-19 13:11:47 -08:00
Phillip Wittrock
be5db09db1 Function framework support for patching containers 2020-11-19 10:01:12 -08:00
Jeff Regan
a6833bc4c0 Merge pull request #3211 from Shell32-Natsu/krm-plugin-tool
modify pluginator to support convert builtin plugin to krm function
2020-11-18 15:59:29 -08:00
Donny Xia
2ae323bb26 move files into internal 2020-11-18 12:21:59 -08:00
Donny Xia
7e74271071 fix script name 2020-11-18 12:21:59 -08:00
Donny Xia
260e093547 modify pluginator to add support for krm function 2020-11-18 12:21:59 -08:00
Jeff Regan
47b12fa3dc Merge pull request #3240 from Shell32-Natsu/list-builtin
Add command to list builtin plugins
2020-11-18 11:13:39 -08:00
Jeff Regan
38801cd966 Merge pull request #3238 from Shell32-Natsu/managed-by-label
fix invalid managed-by label value
2020-11-18 11:09:28 -08:00
Jeff Regan
c49e177b9c Merge pull request #3247 from monopole/secretsAndMaps
Secrets and ConfigMaps with string data in kyaml
2020-11-18 10:00:38 -08:00
jregan
486be07e22 Add WNodeFactory.MakeConfigMap,MakeSecret 2020-11-18 09:45:43 -08:00
Donny Xia
a12db91a10 mark the list-builtin command alpha 2020-11-18 09:38:03 -08:00
jregan
f7613631d1 Add some kyaml filters for k8s metadata. 2020-11-18 08:57:13 -08:00
Kubernetes Prow Robot
8a77494c7d Merge pull request #3239 from pwittrock/framework
Function framework features
2020-11-17 17:58:04 -08:00
Kubernetes Prow Robot
af25469c8b Merge pull request #3219 from phanimarupaka/RefactorOpenAPI
Refactor open api
2020-11-17 11:26:04 -08:00
Phillip Wittrock
8c4841c28f Support for framework.Selector substitutions 2020-11-17 08:52:34 -08:00
Phani Teja Marupaka
b6a4dd446a Refactor openAPI
Refactor global openapi
2020-11-16 23:03:56 -08:00
Jeff Regan
606654756d Update kfns.go 2020-11-16 21:38:25 -08:00
Jeff Regan
97c18518ea Update rnode.go 2020-11-16 21:37:28 -08:00
Jeff Regan
2dca4ab987 Merge pull request #3242 from monopole/useConst
Gather and use some of the kyaml constants.
2020-11-16 21:31:13 -08:00
jregan
712276176c Gather and use some of the kyaml constants. 2020-11-16 21:26:18 -08:00
Donny Xia
c610e3a364 Add command to list builtin plugins 2020-11-16 17:18:56 -08:00
Phillip Wittrock
02e7589323 Function framework testutil support for functions which refer to local files
Some functions may read local files using relative paths.  Update the test
framework to `cd` into the directory containing the config.yaml before
running the function.
2020-11-16 16:35:07 -08:00
Kubernetes Prow Robot
2ae180ca23 Merge pull request #3235 from pwittrock/framework
fn framework TemplatePatch support
2020-11-16 14:14:05 -08:00
Donny Xia
98900c43f7 fix invalid managed-by label value 2020-11-16 14:05:21 -08:00
Phillip Wittrock
02b14d919b fn framework -- add support for patch templates 2020-11-16 14:01:08 -08:00
Phillip Wittrock
bd0a699ff6 Refactor fn/framework tests to use a common library. 2020-11-16 14:00:55 -08:00
Jeff Regan
02b4b56c60 Merge pull request #3233 from monopole/sliceFromBytes
Implement WNodeFactory.SliceFromBytes
2020-11-16 11:57:09 -08:00
jregan
0cac05448b Implement WNodeFactory.SliceFromBytes and FromMap 2020-11-16 11:33:04 -08:00
jregan
e1c3caeba6 Introduce some RNode validation methods. 2020-11-16 11:32:23 -08:00
Jeff Regan
a25429ae3b Merge pull request #3236 from runewake2/mergeless-releases
Remove merge commits from release notes
2020-11-16 11:22:01 -08:00
Kubernetes Prow Robot
e557677fed Merge pull request #3229 from Shell32-Natsu/krm-plugin-tool-helpers
Add methods to convert ResMap to and from RNodes
2020-11-16 11:12:06 -08:00
Donny Xia
59e0b593cf Merge pull request #3232 from justinsb/hint_about_bytereader
Expand rnode function comments to point to multi-object options.
2020-11-16 10:12:54 -08:00
Sam Wronski
3fa906505c Remove merge commits from release notes 2020-11-16 09:47:57 -08:00
Justin SB
a823f3043f Expand rnode function comments to point to multi-object options.
The rnode Parse and ReadFile functions only return a single object;
suggest kio.ByteReader for the case of parsing multiple objects.
2020-11-15 13:07:28 -05:00
Jeff Regan
b2ba82a0bd Merge pull request #3231 from monopole/fromMap
Add RNode FromMap factory method.
2020-11-14 13:33:12 -08:00
jregan
a4f22cb84f Add RNode fromMap method. 2020-11-14 13:10:53 -08:00
Jeff Regan
22f41c789a Merge pull request #3230 from monopole/fmtFix
Fix go fmt.
2020-11-14 11:03:59 -08:00
jregan
966d0a054c Fix go fmt. 2020-11-14 11:02:44 -08:00
Kubernetes Prow Robot
97f3ac2da1 Merge pull request #3185 from aodinokov/streamline-fn-plugin-kyaml-part
Allowing RunFns not to stop on empty result
2020-11-13 13:47:04 -08:00
Donny Xia
536b69e5dc add methods to convert resmap to&from rnodes 2020-11-13 13:41:34 -08:00
Kubernetes Prow Robot
c7aaa18d0c Merge pull request #3227 from radTuti/master
update kustomize download script
2020-11-13 11:39:05 -08:00
tuti
a45523bb95 dry release_url 2020-11-13 11:25:35 -08:00
Kubernetes Prow Robot
376f59f0f6 Merge pull request #3222 from natasha41575/EditSetLabel
added kustomize edit set label
2020-11-13 11:15:04 -08:00
tuti
34863346b0 include arch type in grep string 2020-11-13 11:09:56 -08:00
Kubernetes Prow Robot
9569ca93d9 Merge pull request #3220 from natasha41575/OpenApiVersionField
Add multiple versions of OpenAPI schema to kyaml
2020-11-13 10:39:05 -08:00
Kubernetes Prow Robot
09377ac19c Merge pull request #3223 from sylr/azure-file
Add namereference for PersistentVolume
2020-11-13 10:25:04 -08:00
Jeff Regan
a25300dfd6 Merge pull request #3225 from Shell32-Natsu/inline-transformer
support inline transformer and generator
2020-11-13 10:05:43 -08:00
Kubernetes Prow Robot
50e9e90b17 Merge pull request #3226 from phanimarupaka/DeprecateV1Setters
Delete v1 setters code
2020-11-13 09:21:06 -08:00
tuti
e3ad472933 allow downloading older releases 2020-11-12 18:19:02 -08:00
tuti
154f894774 fix latest release download failure 2020-11-12 18:17:47 -08:00
Natasha Sarkar
4d7600d4ef updated comments and readme 2020-11-12 18:02:11 -08:00
tuti
0a0a0ccddc Merge branch 'master' from kubernetes-sigs/kustomize 2020-11-12 17:59:53 -08:00
Phani Teja Marupaka
2278e01b7f Delete v1 setters code 2020-11-12 15:29:07 -08:00
Donny Xia
abc88c56c4 support inline transformer and generator 2020-11-12 15:19:14 -08:00
Kubernetes Prow Robot
eddd872eca Merge pull request #3221 from pwittrock/framework
Function framework standalone feature
2020-11-12 13:52:25 -08:00
Sylvain Rabot
febede115e Add namereference for PersistentVolume
Signed-off-by: Sylvain Rabot <sylvain@abstraction.fr>
2020-11-12 22:47:33 +01:00
Natasha Sarkar
a2087f07d4 added kustomize edit set label 2020-11-12 13:26:52 -08:00
Phillip Wittrock
8b9d8a266d Support standalone mode for framework functions 2020-11-12 11:54:58 -08:00
Phillip Wittrock
5557e1ff3c Retain element ordering when merge resources 2020-11-12 08:54:16 -08:00
Phillip Wittrock
1c009ca217 More control over bytereadwriter options
- Override wrapping
- Override function config
2020-11-12 08:54:16 -08:00
Natasha Sarkar
bdb59d2cd2 updated releasing readme 2020-11-11 18:09:41 -08:00
Natasha Sarkar
b61a115e76 added support for multiple kubernetes openapi schemas 2020-11-11 18:09:41 -08:00
Jeff Regan
66221d17d4 Merge pull request #3217 from Shell32-Natsu/image
remove a tag from image
2020-11-11 16:22:51 -08:00
Kubernetes Prow Robot
c83f256dbe Merge pull request #3218 from monopole/unpinEverything
Unpin everything post v3.8.7 release
2020-11-11 15:58:52 -08:00
jregan
fa3caaacee Unpin everything post v3.8.7 release 2020-11-11 15:45:09 -08:00
Kubernetes Prow Robot
0a0a2ed586 Merge pull request #3209 from pwittrock/main
Remove duplicate docs content
2020-11-11 15:44:52 -08:00
Donny Xia
aff1db13e0 remove a tag from image 2020-11-11 15:41:32 -08:00
Kubernetes Prow Robot
ad092cc7a9 Merge pull request #3216 from monopole/pin_api_v0.6.5
Pin to api_v0.6.5
2020-11-11 15:08:50 -08:00
jregan
0a9fc6c8cb Pin to api_v0.6.5 2020-11-11 14:56:25 -08:00
Kubernetes Prow Robot
881d33ac5c Merge pull request #3214 from monopole/pin_cmd_config_v0.8.5
Pin to cmd/config/v0.8.5
2020-11-11 14:48:50 -08:00
jregan
842e4f5dc5 Pin to cmd/config/v0.8.5 2020-11-11 14:34:30 -08:00
Kubernetes Prow Robot
ef612286e4 Merge pull request #3213 from monopole/pinToCli-utils_v0.21.1
Pin to cli-utils_v0.21.1 kyaml_v0.9.4
2020-11-11 13:40:50 -08:00
jregan
636c9fcddf Pin to cli-utils_v0.21.1 kyaml_v0.9.4 2020-11-11 13:26:05 -08:00
Kubernetes Prow Robot
333945d361 Merge pull request #3207 from runewake2/local-presubmit
Skip multi-mod check if PULL_NUMBER unset
2020-11-11 08:34:29 -08:00
Phillip Wittrock
afff3ce5ab update docs site 2020-11-11 08:30:00 -08:00
Phillip Wittrock
71b763888c Remove duplicate kustomize docs content 2020-11-11 08:29:43 -08:00
Jeff Regan
c5cd539b01 Merge pull request #3118 from brianpursley/kustomize-2893
Implement WNode methods
2020-11-11 08:15:29 -08:00
Sam Wronski
4b89c2afa2 Skip multi-mod check if PULL_NUMBER unset 2020-11-10 16:22:48 -08:00
Kubernetes Prow Robot
630fc9b973 Merge pull request #3206 from monopole/disableHelmTests
Disable helm inflator tests.
2020-11-10 16:12:42 -08:00
jregan
a468743b81 Disable helm inflator tests. 2020-11-10 15:22:25 -08:00
Kubernetes Prow Robot
e9a74b87e3 Merge pull request #3203 from Shell32-Natsu/fix-helm
fix helm chart inflation generator
2020-11-10 10:36:41 -08:00
Donny Xia
64f8d2ae38 add one more test 2020-11-10 10:25:05 -08:00
Donny Xia
5ab320c216 fix helm chart inflation generator 2020-11-10 10:03:26 -08:00
Kubernetes Prow Robot
6131f86d23 Merge pull request #3197 from Shell32-Natsu/doc
add link for component reference
2020-11-10 09:14:40 -08:00
Jeff Regan
e7609559ce Merge pull request #3201 from monopole/tmpRemoveCheck
Temporarily remove cross-module PR check.
2020-11-10 08:23:12 -08:00
Donny Xia
c2bdac7a6b Merge pull request #3200 from natasha41575/CleanTestComments
cleaned comments
2020-11-09 21:30:35 -08:00
Jeffrey Regan
4cc2c4f623 Temporarily remove cross-module PR check. 2020-11-09 20:47:06 -08:00
Natasha Sarkar
155c42679c cleaned comments 2020-11-09 20:17:51 -08:00
Donny Xia
88239445ce add link for component reference 2020-11-09 12:05:06 -08:00
Kubernetes Prow Robot
d66fc462ec Merge pull request #3159 from natasha41575/MergeKeyList
use merge key list instead of a single merge key
2020-11-09 11:51:58 -08:00
Natasha Sarkar
6788af083b updated tests for multiple merge keys 2020-11-09 11:35:37 -08:00
Natasha Sarkar
df0576a270 use merge key tuple instead of single merge key 2020-11-09 11:34:31 -08:00
Jeff Regan
f4d8ebb1da Merge pull request #3182 from pwittrock/master
Redirect kustomize site to the unified site
2020-11-07 08:59:07 -08:00
Kubernetes Prow Robot
0acac39640 Merge pull request #3192 from Shell32-Natsu/multierror
Improve the readability for multiple errors in kusttarget
2020-11-06 17:21:38 -08:00
Donny Xia
65db82df0c Merge pull request #3177 from Shell32-Natsu/json-patch
Improve json patch plugin
2020-11-06 16:17:24 -08:00
Donny Xia
68951bb37e format 2020-11-06 15:38:33 -08:00
Donny Xia
b18910aa6d format 2020-11-06 15:38:18 -08:00
Donny Xia
f780f7a3c2 update go.sum 2020-11-06 15:18:41 -08:00
Donny Xia
7966386615 improve format 2020-11-06 15:17:56 -08:00
Donny Xia
2130ba72cc improve format 2020-11-06 15:17:43 -08:00
Donny Xia
94d26ba53a improve the readability for multiple errors 2020-11-06 15:16:48 -08:00
Jeff Regan
c53f31ca4f Merge pull request #3169 from Shell32-Natsu/patch-target
support regex in GVK selection
2020-11-06 15:15:40 -08:00
Jeff Regan
b58075cbc3 Merge pull request #3176 from natasha41575/ElementSetterList
add ElementSetterList and ElementMatcherList to fns.go
2020-11-06 13:40:48 -08:00
Jeff Regan
b3e82a2fe7 Merge pull request #3187 from runewake2/multi-module-golang
Run multi-module check during presubmit
2020-11-06 13:33:29 -08:00
Donny Xia
78c26f55b5 support regex in GVK selection 2020-11-06 13:23:55 -08:00
Jeff Regan
ec2a6e4e4b Update Makefile 2020-11-06 13:15:43 -08:00
Natasha Sarkar
886f73aa0f added test case for no values 2020-11-06 13:14:25 -08:00
Natasha Sarkar
73d91dda6e changed handling of empty values 2020-11-06 11:42:17 -08:00
Natasha Sarkar
9f06376ab2 updated associative sequence 2020-11-05 17:22:54 -08:00
Natasha Sarkar
e785bab474 updated matchelementlist 2020-11-05 17:03:52 -08:00
Natasha Sarkar
8f80a898b6 removed elementsetterlist and updated elementsetter 2020-11-05 16:50:18 -08:00
Sam Wronski
fe84d119d6 Use gomodule when running prchecker 2020-11-05 16:03:36 -08:00
Sam Wronski
03b847a749 Use PULL_NUMBER env from prow 2020-11-05 15:44:40 -08:00
Sam Wronski
9d2f257acf Install dependencies from go module 2020-11-05 15:28:37 -08:00
Jeff Regan
129b25ceff Merge pull request #3167 from Shell32-Natsu/patch-test
re-enable test for edit patch add
2020-11-05 15:07:14 -08:00
Jeff Regan
57f4ea5354 Merge pull request #3166 from phanimarupaka/DeferOpenAPICleanup
Defer openAPI cleanup
2020-11-05 14:48:00 -08:00
Phani Teja Marupaka
ec2cc2d421 Defer openAPI cleanup 2020-11-05 13:49:43 -08:00
Sam Wronski
712eb6d276 Refactor changeset spanning function naming 2020-11-05 12:23:45 -08:00
Natasha Sarkar
a04e3a575c added test case for different length keys/values 2020-11-05 12:19:54 -08:00
Natasha Sarkar
03e2fed925 checked array length 2020-11-05 12:16:17 -08:00
Jeff Regan
c37b3b2525 Merge pull request #3170 from natasha41575/MultipleMergeKeyTests
added tests for merge key tuple behavior
2020-11-05 12:12:59 -08:00
Donny Xia
ceeba8764f update Makefile 2020-11-05 12:06:06 -08:00
Donny Xia
04d133a66f re-enable test for edit patch add 2020-11-05 12:06:06 -08:00
Natasha Sarkar
99aaa80e1d updated stale comments 2020-11-05 11:40:36 -08:00
Natasha Sarkar
1f806b0aa2 add elementsetterlist and elementmatcherlist to fns.go 2020-11-05 11:37:45 -08:00
Sam Wronski
1f697e3792 Run multi-module check during presubmit 2020-11-05 11:21:15 -08:00
Alexey Odinokov
28cdcc2e46 Allowing RunFns not to stop on empty result
Introducing the additional flag
ContinueOnEmptyResult that is false by default
to keep compatibility with the previous behavior.
Based on [1]

[1]
https://github.com/kubernetes-sigs/kustomize/pull/3112
2020-11-05 07:19:20 +00:00
Natasha Sarkar
c0ecd1d1ad added more tests 2020-11-04 19:07:58 -08:00
Natasha Sarkar
3923c63182 added some tests to merge3/element_test.go 2020-11-04 19:07:58 -08:00
Natasha Sarkar
9943e74187 updated comments 2020-11-04 19:07:58 -08:00
Natasha Sarkar
3b504fa3e5 added StringList set 2020-11-04 19:07:58 -08:00
Kubernetes Prow Robot
9fb25fc5a7 Merge pull request #3139 from runewake2/multi-module-golang
Update Multi Module Check to Scan Commits
2020-11-04 12:14:52 -08:00
Phillip Wittrock
4d99217a7c Build kustomize docs site with redirects to new unified at cli-experimental 2020-11-04 11:18:56 -08:00
Phillip Wittrock
0834e152b2 Redirect kustomize docs to the new unified site. 2020-11-04 11:15:40 -08:00
Donny Xia
ff276af317 use same logic with path transformer 2020-11-03 17:14:08 -08:00
Donny Xia
3b79944190 improve target in JSON6902 transformer 2020-11-03 17:13:43 -08:00
Kubernetes Prow Robot
d8d57eae29 Merge pull request #3174 from Shell32-Natsu/elementsetter-test
add tests for ElementSetter
2020-11-03 15:42:04 -08:00
Donny Xia
c803ca83a4 fix linter error 2020-11-03 15:29:01 -08:00
Donny Xia
6bed275234 add more tests for ElementSetter 2020-11-03 15:23:34 -08:00
Jeff Regan
8e5df26e4c Merge pull request #3173 from natasha41575/StringListSet
added StringList set
2020-11-03 13:34:56 -08:00
Donny Xia
3fed68b694 clarify the comments 2020-11-03 13:09:12 -08:00
Natasha Sarkar
0e59c36d03 added StringList set 2020-11-03 12:42:37 -08:00
Jeff Regan
00fdf71dc3 Merge pull request #2951 from dearchap/cm_merge
Add ability to specify behavior adding configmap
2020-11-03 12:02:45 -08:00
Donny Xia
be327e7443 add tests for ElementSetter 2020-11-03 11:54:44 -08:00
Donny Xia
be8d2fe016 Merge pull request #3161 from mikebz/mb_remove_travis
removing travis references
2020-11-03 11:15:58 -08:00
Mike Borozdin
072ae36fe6 removing travis references 2020-11-03 10:04:42 -08:00
Naveen Gogineni
b5d8b8d258 Add ability to specify behavior when running "kustomize edit add configmap" command 2020-11-02 16:09:51 -05:00
Jeff Regan
e6b21174f1 Merge pull request #3143 from Shell32-Natsu/helm-inflator-builtin
Convert helminflator to builtin plugin HelmChartGenerator
2020-11-02 12:30:02 -08:00
Donny Xia
49094cf999 Merge pull request #3164 from Shell32-Natsu/cloudbuild
fix version in releasing/cloudbuild_kustomize_image.yaml
2020-11-02 11:12:11 -08:00
Donny Xia
d2c7db6ca0 update chart examples 2020-11-02 11:03:31 -08:00
Donny Xia
d141f9b973 fix version 2020-11-02 10:52:04 -08:00
Sam Wronski
877da8da6d Update module span to check commits
- Use regex to detect if check should run
- Update scan to be per-commit
2020-11-02 10:29:40 -08:00
Kubernetes Prow Robot
8596e63203 Merge pull request #3163 from Shell32-Natsu/cloudbuild
update version in image creation
2020-11-02 10:16:15 -08:00
Donny Xia
b2df55e9d7 update version in image creation 2020-11-02 09:55:06 -08:00
Donny Xia
6daf8f8820 Merge pull request #3160 from Shell32-Natsu/cloudbuild
update cloudbuild for image pushing job
2020-11-02 09:39:48 -08:00
Donny Xia
e75d4fc87d convert helm inflator to builtin plugin 2020-10-30 23:18:54 -07:00
Donny Xia
9ae07634f2 update cloudbuild for image pushing job 2020-10-30 12:19:17 -07:00
Donny Xia
981959ffcf Merge pull request #3155 from radTuti/master
fix binary install script
2020-10-29 22:01:18 -07:00
tuti
dc31321b05 fix binary install script 2020-10-29 17:51:54 -07:00
Kubernetes Prow Robot
64dc3e14ff Merge pull request #3153 from Shell32-Natsu/master
unpin modules
2020-10-29 16:32:05 -07:00
Donny Xia
da0893bac0 unpin modules 2020-10-29 16:17:45 -07:00
Kubernetes Prow Robot
c1747439cd Merge pull request #3152 from Shell32-Natsu/master
Pin to api 0.6.4
2020-10-29 16:06:05 -07:00
Donny Xia
f68986827b Pin to api 0.6.4 2020-10-29 15:53:34 -07:00
Kubernetes Prow Robot
b736b81167 Merge pull request #3151 from Shell32-Natsu/master
Pin to cmd/config 0.8.4
2020-10-29 15:24:06 -07:00
Donny Xia
0a04b1bb78 Pin to cmd/config 0.8.4 2020-10-29 15:11:09 -07:00
Kubernetes Prow Robot
f7ebaae39e Merge pull request #3150 from Shell32-Natsu/master
Pin to kyaml v0.9.3
2020-10-29 15:04:06 -07:00
Donny Xia
08099f0cea Pin to kyaml v0.9.3 2020-10-29 14:47:52 -07:00
Kubernetes Prow Robot
6fd04dd253 Merge pull request #3146 from ilyakaznacheev/fix-configmap-doc
Add better configMap cleanup description.
2020-10-28 17:38:59 -07:00
Ilya Kaznacheev
9ac97ef91f Add better configMap cleanup descripion 2020-10-29 01:50:45 +03:00
Jeff Regan
cfbf426174 Merge pull request #3129 from Shell32-Natsu/patches-command
Update edit patch command
2020-10-28 12:47:13 -07:00
Donny Xia
9aafc61c5b disable edit add patch command tests temporarily 2020-10-28 12:24:51 -07:00
Donny Xia
cd2ebd3046 code review 2020-10-27 15:10:29 -07:00
Jeff Regan
b20e5d7f84 Merge pull request #3135 from Shell32-Natsu/cleanup-namespace-transformer
cleanup namespace transformer
2020-10-27 09:54:28 -07:00
Jeff Regan
13c9a2873e Update comments in multi-transformer 2020-10-27 07:17:14 -07:00
Kubernetes Prow Robot
fc06283905 Merge pull request #3140 from teruyam/patch-1
Fix broken link to release page
2020-10-26 12:37:02 -07:00
Jeff Regan
119d7cadf5 Merge pull request #3136 from natasha41575/NamespaceabilityFromOpenAPI
removed hardcoded list of namespaceable resources
2020-10-26 12:22:36 -07:00
Masashi Teruya
cdc6d1fc28 Fix broken link to release page 2020-10-24 11:18:33 +09:00
Natasha Sarkar
49dced2e01 removed hardcoded list of namespaceable resources 2020-10-23 11:47:29 -07:00
Donny Xia
76a8f034cb Merge pull request #3133 from robinbraemer/patch-2
Add Ingress tls secretName to Secret builtin nameref
2020-10-23 11:20:11 -07:00
Donny Xia
52060ac480 Merge pull request #3132 from robinbraemer/patch-1
Add Ingress v1 support to builtin name references
2020-10-23 11:19:51 -07:00
Donny Xia
719532e4df Merge pull request #3123 from AlphaWong/patch-1
doc: add varReference example
2020-10-22 14:42:05 -07:00
Donny Xia
70dcc79bf4 cleanup namespace transformer 2020-10-22 13:18:20 -07:00
Kubernetes Prow Robot
55b4448862 Merge pull request #3134 from phanimarupaka/OptionallySuppressIsSet
Make isSet a parameter
2020-10-22 11:43:37 -07:00
Phani Teja Marupaka
bcaac6f8c1 Make isSet a parameter 2020-10-22 11:31:30 -07:00
Jeff Regan
ba4b44db6b Merge pull request #3126 from monopole/mechanical
Generated go.sum/mod and docs.go changes.
2020-10-22 10:30:52 -07:00
Robin Brämer
fd280d0c0b Add Ingress tls secretName to Secret builtin nameref 2020-10-22 17:00:10 +02:00
Robin Brämer
1dbf490146 Add IngressClass kind
Adds IngressClass kind and Ingress fieldSpecs path spec/ingressClassName
2020-10-22 16:11:44 +02:00
Robin Brämer
62e4df72d3 Add Service name references for Ingress v1
Since Kubernetes v1.19, Ingress networking.k8s.io/v1 has two more Server name references.
- https://kubernetes.io/docs/concepts/services-networking/ingress/#the-ingress-resource
- https://kubernetes.io/docs/setup/release/notes/
2020-10-22 15:59:22 +02:00
Donny Xia
bb77a7c86d refactor edit remove patch 2020-10-21 18:48:53 -07:00
Donny Xia
41abeb85be refactor edit add patch command 2020-10-21 14:56:20 -07:00
Jeff Regan
3c86d37148 Merge pull request #3122 from Shell32-Natsu/ref-target
check Gvk in roleRef when update name reference
2020-10-21 11:19:20 -07:00
Kubernetes Prow Robot
287b38cc87 Merge pull request #3106 from Shell32-Natsu/array-index
support array index in PathGetter
2020-10-21 11:16:20 -07:00
jregan
d8d727b1ca Generated go.sum/mod and docs.go changes. 2020-10-20 17:22:48 -07:00
Jeff Regan
a81a3d40ce Merge pull request #3087 from etefera/add-isSet-to-list-setters
Add isSet to ListSetters cmd.
2020-10-20 16:52:13 -07:00
Eyob Tefera
52e682489c Merge branch 'add-isSet-to-list-setters' of https://github.com/etefera/kustomize into add-isSet-to-list-setters 2020-10-20 23:24:11 +00:00
Eyob Tefera
8714ca5a58 Move "Is Set" column to after "Required" 2020-10-20 23:17:54 +00:00
Eyob Tefera
0490ca163f Fix list_setters test. 2020-10-20 23:17:54 +00:00
Eyob Tefera
b4947fe8a0 Add isSet to ListSetters cmd. 2020-10-20 23:17:54 +00:00
Donny Xia
9c7b4fddf9 code review 2020-10-20 12:39:50 -07:00
Alpha
5d5b1c2c38 doc: simplify the language for understanding 2020-10-20 13:13:13 +08:00
Alpha
cf1aafb121 doc: add description for new user about vars 2020-10-20 13:06:31 +08:00
Alpha
2d4e406a86 doc: add varReference example 2020-10-20 12:56:43 +08:00
Jeff Regan
2a8edd2859 Merge pull request #3110 from aude/completion
Use Cobra for shell completion
2020-10-19 18:03:06 -07:00
Kubernetes Prow Robot
a3bc13847c Merge pull request #3119 from phanimarupaka/MakeRecurseLogicPublic
Make recurse logic public
2020-10-19 17:28:07 -07:00
Kubernetes Prow Robot
944b19ff7c Merge pull request #3114 from monopole/hideOpenapi
Hide openapi top-level command
2020-10-19 17:14:07 -07:00
Jeff Regan
f75274bae7 Merge pull request #3085 from mikeyrcamp/feat/add-edit-transformer
Add kustomize edit add/remove transformer command #3053
2020-10-19 15:04:12 -07:00
Donny Xia
62a8a8c57d check Gvk in roleRef when update name reference 2020-10-19 14:01:13 -07:00
Kubernetes Prow Robot
9514f9cd3a Merge pull request #3121 from natasha41575/regenerateSwagger
regenerated swagger.go files and updated asset name
2020-10-19 13:39:18 -07:00
Natasha Sarkar
c1c2725360 regenerated swagger.go files and updated asset name 2020-10-19 13:04:56 -07:00
Phani Teja Marupaka
e9ff26bb1b Make recurse logic public 2020-10-19 12:26:15 -07:00
Kubernetes Prow Robot
14dc3dfb81 Merge pull request #3112 from KnVerey/pipeline_continue
[kyaml] Option to continue pipeline processing when filter returns empty result
2020-10-19 10:46:14 -07:00
Katrina Verey
44619d5ca2 Option to continue pipeline processing when filter returns empty result 2020-10-19 10:34:28 -07:00
brianpursley
027b7d61ea Implemented the following WNode methods:
* GetFieldValue
* GetSlice
* GetString
* Map
* SetAnnotations
* SetGvk
* SetLabels
* SetName
* SetNamespace
2020-10-18 20:09:42 -04:00
Kubernetes Prow Robot
a458ed84f9 Merge pull request #3113 from etefera/add-isSet-to-setter-struct
Add IsSet to SetterDefinition for kyaml release.
2020-10-18 11:26:13 -07:00
Kubernetes Prow Robot
108f44377d Merge pull request #3115 from monopole/refactorOpenapiMakefile
Refactor making of openapi generated files.
2020-10-16 19:24:12 -07:00
jregan
dc8439fbfa Refactor making of openapi generated files. 2020-10-16 19:03:33 -07:00
Jeff Regan
f5353fafa1 Update info.go 2020-10-16 18:00:18 -07:00
jregan
3d1376bbbc oopsHideProperCommand 2020-10-16 17:57:25 -07:00
Eyob Tefera
b1ea25e86a Add IsSet to SetterDefinition for kyaml release. 2020-10-17 00:46:30 +00:00
Jeff Regan
495f6df973 Merge pull request #3107 from natasha41575/reportOpenAPIinfo
Created a "kustomize openapi info" command
2020-10-16 14:33:21 -07:00
Natasha Sarkar
a4f1f0841e added a hidden openapi info command 2020-10-16 13:55:37 -07:00
Asbjørn Apeland
9d0fba81f0 Use Cobra for shell completion 2020-10-16 18:55:54 +02:00
Donny Xia
92826c6a1e support array index in PathGetter 2020-10-15 16:28:09 -07:00
Kubernetes Prow Robot
7e04be9ec6 Merge pull request #3105 from Shell32-Natsu/unpinKyaml
Unpin kyaml
2020-10-15 14:23:25 -07:00
Donny Xia
d954c39ef7 Unpin kyaml 2020-10-15 14:05:31 -07:00
Jeff Regan
176ac5b4fa Merge pull request #3104 from Shell32-Natsu/pinToKyaml0.9.2
Pin to kyaml v0.9.2
2020-10-15 14:02:47 -07:00
Donny Xia
dd696b5cb4 Pin to kyaml v0.9.2 2020-10-15 13:55:30 -07:00
Jeff Regan
501404e403 Merge pull request #3103 from monopole/prchecker
Move multi-module-span.go to cmd/prchecker
2020-10-15 13:39:48 -07:00
Jeff Regan
ddf94175ee Merge pull request #3102 from natasha41575/rollbackPortMergeKey
changed port merge key back to containerPort
2020-10-15 12:06:51 -07:00
Jeff Regan
232da9e12b Update Makefile 2020-10-15 11:58:50 -07:00
jregan
8b9ce8eacb Move multi-module-span.go to cmd/prchecker 2020-10-15 11:46:27 -07:00
Natasha Sarkar
ee9a4f2526 changed port merge key back to containerport 2020-10-15 11:43:14 -07:00
Kubernetes Prow Robot
006ce72b2d Merge pull request #3099 from umangachapagain/patch-1
Updated description for commonannotations
2020-10-15 11:35:25 -07:00
Jeff Regan
a80bd15bda Merge pull request #3096 from runewake2/multi-module-golang
Add Support for Paginated Pull Request Responses to Multi-Module Check
2020-10-15 11:23:30 -07:00
Sam Wronski
6c63bb2727 Revert Makefile changes 2020-10-15 10:29:38 -07:00
Jeff Regan
a7ba93b1d8 Merge pull request #3101 from monopole/cleanUpMakeTargets
Cleanup Makefile.
2020-10-15 10:03:37 -07:00
jregan
4a78cd6579 Cleanup Makefile. 2020-10-15 10:02:15 -07:00
Jeff Regan
b2b8c12203 Update README.md 2020-10-15 09:46:35 -07:00
Jeff Regan
8cc281fad6 Merge pull request #3100 from monopole/movePluginatorToCmd
Move pluginator to cmd dir.
2020-10-15 09:43:46 -07:00
jregan
7346813b8d Move pluginator to cmd dir. 2020-10-15 09:22:29 -07:00
Umanga Chapagain
52f3aca22d Updated description for commonannotations 2020-10-15 09:13:39 +05:30
Mike Camp
a6a061215f Add kustomize edit add/remove transformer command #3053
Similar to edit add/remove patch these commands
add the ability to add or remove a transformer file path
from the kustomization.yaml.

Refactored the "remove resource" and new "remove transformer"
tests into a common testRemoveCommand function to prevent
code duplication.
2020-10-14 22:24:08 -04:00
Kubernetes Prow Robot
7464d8ac8f Merge pull request #3097 from Shell32-Natsu/as-current-user
add --as-current-user flag to fn run
2020-10-14 18:09:51 -07:00
Donny Xia
64fda38e2d add --as-current-user flag to fn run 2020-10-14 17:07:03 -07:00
Sam Wronski
4cefb62d41 Add multi-module check to prow-presubmit-check 2020-10-14 15:34:52 -07:00
Eyob Tefera
ccca424234 Move "Is Set" column to after "Required" 2020-10-14 19:38:47 +00:00
Jeff Regan
ca45907af0 Merge pull request #3083 from stuartpb/patch-1
Group regex within anchoring
2020-10-14 08:34:28 -07:00
Jeff Regan
dcf43c7f2b Merge pull request #3076 from natasha41575/fetchOpenAPIdata
Fetch openAPI data
2020-10-14 08:20:27 -07:00
Natasha Sarkar
1386ec3850 edited kpt target 2020-10-13 17:19:03 -07:00
Natasha Sarkar
de8e16df15 added script for installing kpt 2020-10-13 17:11:00 -07:00
Natasha Sarkar
222b2d4485 added MYGOBIN variable for kind 2020-10-13 16:25:29 -07:00
Natasha Sarkar
e107020bd2 edited make schema for kyaml 2020-10-13 13:53:25 -07:00
Natasha Sarkar
430665e984 version -> api_version 2020-10-13 13:21:19 -07:00
Kubernetes Prow Robot
017d5673ba Merge pull request #3088 from Shell32-Natsu/arm-build
add arm build
2020-10-12 15:33:22 -07:00
Donny Xia
f346b9803e add arm build 2020-10-12 13:41:24 -07:00
Eyob Tefera
58092bf66d Fix list_setters test. 2020-10-12 20:23:53 +00:00
Eyob Tefera
747323efce Add isSet to ListSetters cmd. 2020-10-12 20:14:25 +00:00
Jeff Regan
7428e08f93 Merge pull request #3081 from Shell32-Natsu/release-container
files for building image when release kustomize
2020-10-12 11:18:09 -07:00
Stuart P. Bentley
3c8e6d7151 Group regex within anchoring
This ensures that anchoring will apply to the entire anchored expression, eg. a pattern like `foo|bar` will only match the strings "foo" and "bar" (`^(?:foo|bar)$`), instead of matching any string that begins with "foo" or ends with "bar" (`^foo|bar$`).
2020-10-10 15:47:38 -07:00
Donny Xia
43bd2f4cdb files for building image when release kustomize 2020-10-09 14:35:17 -07:00
Natasha Sarkar
1dfc9a88a8 moved openapi instructions to top of readme 2020-10-09 12:31:14 -07:00
Natasha Sarkar
01beba8697 formatting documentation: 2020-10-09 12:29:06 -07:00
Natasha Sarkar
b1e01b238b updated documentation 2020-10-09 12:29:06 -07:00
Natasha Sarkar
1f595da9ad updated way to fetch go-bindata 2020-10-09 12:29:06 -07:00
Natasha Sarkar
1cf876927d minor makefile fix 2020-10-09 12:29:06 -07:00
Natasha Sarkar
a422c935d8 added make target to fetch new openapi schema 2020-10-09 12:29:06 -07:00
Jeff Regan
1971816663 Update README.md 2020-10-09 09:45:19 -07:00
Kubernetes Prow Robot
3d1eab872b Merge pull request #3071 from monopole/unpinAll
Unpin api,cmd/config,kyaml
2020-10-08 13:03:06 -07:00
Jeff Regan
10c1b0c5fa Update README.md 2020-10-08 11:34:07 -07:00
Jeff Regan
4d95cd3630 Merge pull request #3072 from monopole/gorepomod
Replace bash release helper scripts with Go progam
2020-10-08 11:10:57 -07:00
jregan
0c169e96e5 Replace bash release helper scripts with Go progam 2020-10-08 10:54:14 -07:00
jregan
5baea8400f Unpin api,cmd/config,kyaml 2020-10-08 09:39:49 -07:00
Jeff Regan
4052cd4fd8 Merge pull request #3069 from monopole/pinToCmdConfigV0.8.2
Pin to cmd/config/v0.8.2,  api/v0.6.3
2020-10-07 19:40:12 -07:00
jregan
21ac400d49 Pin to cmd/config/v0.8.2 2020-10-07 19:21:23 -07:00
Jeff Regan
351a4a48e4 Merge pull request #3068 from monopole/pinToKyamlv0.9.1_cliUtilsv0.20.4
Pin to kyaml/v0.9.1 and cli-utils/v0.20.4
2020-10-07 16:43:04 -07:00
jregan
b3cf475024 Pin to kyaml/v0.9.1 and cli-utils/v0.20.4 2020-10-07 16:23:13 -07:00
Jeff Regan
ded25075b1 Update README.md 2020-10-07 16:17:26 -07:00
Jeff Regan
05b8671d17 Update README.md 2020-10-07 14:35:44 -07:00
Jeff Regan
1bfcc81f08 Merge pull request #3027 from gochist/windows-exec
Support exec plugin on Windows
2020-10-07 14:18:14 -07:00
Jeff Regan
3d058830b9 Merge pull request #2918 from sunny0826/zh-patches
update zh doc api-reference/kustomization/patches
2020-10-07 14:04:53 -07:00
Jeff Regan
bdb53fca9e Merge pull request #3067 from Shell32-Natsu/file-name
make file name more readable when no group
2020-10-07 13:50:28 -07:00
Donny Xia
b7265440f8 make file name more readable when no group 2020-10-07 12:44:45 -07:00
Kubernetes Prow Robot
72e1a27177 Merge pull request #3064 from Shell32-Natsu/comma
remove ',' separator in edit add label/annotation
2020-10-07 10:18:18 -07:00
Kubernetes Prow Robot
0a1fde1e41 Merge pull request #3066 from phanimarupaka/ImproveSetOutputMessage
Improve setter output message
2020-10-06 21:12:42 -07:00
Jeff Regan
ae4618d327 Merge pull request #3065 from natasha41575/updateSchemaForPorts
updated schema to fix port merging issue
2020-10-06 18:00:15 -07:00
Natasha Sarkar
aee6ccb05c added documentation comments 2020-10-06 17:20:18 -07:00
Natasha Sarkar
3cd2a0a2f7 removed comments documenting broken test 2020-10-06 14:48:49 -07:00
Phani Teja Marupaka
c96fa7c347 Improve setter output message 2020-10-06 14:41:14 -07:00
Natasha Sarkar
ad01d8d34e updated schema to fix port merging issue 2020-10-06 14:30:30 -07:00
Donny Xia
b214fa7d5a remove ',' separator in edit add label/annotation 2020-10-06 11:49:39 -07:00
Jeff Regan
68f67c183e Merge pull request #3060 from Shell32-Natsu/doc
Remove the lines about config save command
2020-10-06 09:54:23 -07:00
Jeff Regan
fe5c3a291f Merge pull request #3059 from Shell32-Natsu/metadata
Add metadata field to kustomization file
2020-10-05 15:18:42 -07:00
Donny Xia
f38cc4446b Remove the lines about config save command 2020-10-05 11:29:02 -07:00
Donny Xia
e695b0534d Add metadata field to kustomization file 2020-10-05 11:20:41 -07:00
June Yi
51ecca8f2f Add a comment about the behavior in Windows 2020-10-03 09:49:56 +09:00
Jeff Regan
460c54064c Update README.md 2020-10-02 16:51:13 -07:00
Jeff Regan
50c0200429 Merge pull request #3056 from monopole/mechanicalGoSum
Update generated go.sum files.
2020-10-02 15:25:57 -07:00
jregan
b1b5a95466 Update generated go.sum files. 2020-10-02 14:51:17 -07:00
Jeff Regan
3f71c671df Merge pull request #2948 from dearchap/patch-1
Update _index.md
2020-10-02 14:22:31 -07:00
Jeff Regan
2ce9c02ada Merge pull request #3055 from phanimarupaka/CleanupCfgCommandOutput
Cleanup Cfg/Grep Command Output
2020-10-02 14:22:00 -07:00
Jeff Regan
3ffc13dd6e Merge pull request #3054 from Shell32-Natsu/isnamespaceable
refactor Gkv.isNamespaceableKind
2020-10-02 14:03:08 -07:00
Jeff Regan
2fb8603b2a Merge pull request #3050 from Shell32-Natsu/deployment-annotation
support var ref in deployment template annotations
2020-10-02 14:01:32 -07:00
Jeff Regan
1d4b3fa36c Merge pull request #3048 from Shell32-Natsu/merge-prepend
add option to choose prepend/append patch items to list in merge
2020-10-02 11:53:22 -07:00
Donny Xia
03ea8f3615 update tests 2020-10-02 10:10:05 -07:00
Donny Xia
74d0d7960e add option to choose prepend/append in merge 2020-10-02 09:56:59 -07:00
Phani Teja Marupaka
ffed4c95b3 Cleanup Cfg/Grep Command Output 2020-10-01 16:51:13 -07:00
Donny Xia
c59b393fa4 refactor Gkv.isNamespaceableKind 2020-10-01 11:28:58 -07:00
Jeff Regan
fafe24c9df Merge pull request #3038 from Shell32-Natsu/patch-list
support merge strategy directive in list
2020-10-01 10:53:13 -07:00
Jeff Regan
d62d8dcade Merge pull request #3003 from runewake2/multi-module-golang
Adds a directory spanning check script
2020-09-30 13:39:21 -07:00
Kubernetes Prow Robot
ae7f984c71 Merge pull request #3052 from natasha41575/addIsEmptyToResource
added IsEmpty() method
2020-09-30 13:26:54 -07:00
Natasha Sarkar
7c8c827a88 added IsEmpty() method 2020-09-30 12:17:14 -07:00
Donny Xia
ff927fd11a support merge strategy in list 2020-09-30 10:52:47 -07:00
Donny Xia
a4f6fee6c8 support var ref in deployment template annotations 2020-09-30 10:21:03 -07:00
Jeff Regan
dd8edb1b01 Merge pull request #3040 from natasha41575/fixIssue2896
fixed issue 2896
2020-09-29 17:55:08 -07:00
Kubernetes Prow Robot
bb42d8aa1b Merge pull request #3044 from Shell32-Natsu/element-getter
add GetElementByKey
2020-09-29 17:53:24 -07:00
Donny Xia
bb60c29672 add GetElementByKey 2020-09-29 17:36:07 -07:00
Natasha Sarkar
c93274c224 changed way to test for empty resource 2020-09-29 17:33:12 -07:00
Natasha Sarkar
f5feffbd23 fix for the patchdelete test 2020-09-28 13:28:06 -07:00
Natasha Sarkar
e17bab7e55 updated to include namespace 2020-09-28 11:01:01 -07:00
Natasha Sarkar
bd534441ce fixed issue 2896 2020-09-28 11:01:01 -07:00
June Yi
85f79edc97 Add testcase for ErrIfNotExecutable 2020-09-26 18:01:39 +09:00
Kubernetes Prow Robot
4c48a4ff83 Merge pull request #3033 from Shell32-Natsu/3021
fix multiple match issue in rolebinding
2020-09-25 17:22:48 -07:00
Jeff Regan
eb6c715bc3 Merge pull request #3032 from Shell32-Natsu/default-branch
remove default master branch in cloner
2020-09-25 17:01:54 -07:00
Jeff Regan
1320e0c3dc Merge pull request #2999 from aodinokov/fixenv
Added list of env variables for fn-plugins
2020-09-25 17:00:28 -07:00
Jeff Regan
df0022c985 Merge pull request #2949 from dearchap/cmdline
Chore: docs : Add basic structure for command line options
2020-09-25 16:44:04 -07:00
Jeff Regan
15fc341a13 Merge pull request #2992 from Shell32-Natsu/as-current-user
add as-current-user for fn run
2020-09-25 16:42:49 -07:00
Jeff Regan
dd90c41f85 Merge pull request #2994 from PascalBourdier/patch-1
fix typo
2020-09-25 16:35:11 -07:00
Jeff Regan
3a5951563d Merge pull request #3037 from mortent/RemoveDepOnCliUtils
Remove dependency from cmd/config on cli-utils
2020-09-24 12:59:21 -07:00
Donny Xia
acdfd9a920 remove error from NewContainer 2020-09-24 11:37:49 -07:00
Donny Xia
52016b22dd test without system call 2020-09-24 11:37:48 -07:00
Donny Xia
11049fa0bb add as-current-user for fn run 2020-09-24 11:37:48 -07:00
Morten Torkildsen
db6c825c05 Remove dependency from cmd/config on cli-utils 2020-09-24 11:16:41 -07:00
Jeff Regan
cb7974cf45 Merge pull request #3024 from Shell32-Natsu/master
Add issue templates
2020-09-23 21:46:44 -07:00
Jeff Regan
00111846d3 Merge pull request #3023 from TIKI-Institut/master
Enable the installation of specific versions with the "install_kustomize.sh" script (#3022)
2020-09-23 21:44:53 -07:00
Kubernetes Prow Robot
eafa37810b Merge pull request #3034 from Shell32-Natsu/cfg-tree-kustomization
add Kustomization to cfg tree
2020-09-23 21:44:04 -07:00
Donny Xia
0c0cb9aaba add Kustomization to cfg tree 2020-09-23 13:35:45 -07:00
Donny Xia
b51e09d5fe fix multiple match issue in rolebinding 2020-09-23 13:03:12 -07:00
Donny Xia
c8cd5e55fc Add bug filing link 2020-09-23 11:33:03 -07:00
Kubernetes Prow Robot
103d1461a1 Merge pull request #3029 from phanimarupaka/SetAllSetterDefsOpenAPI
Sync openAPI setter values with schema
2020-09-22 19:26:09 -07:00
Donny Xia
f02af7a48b remove default master branch in cloner 2020-09-22 15:57:50 -07:00
Phani Teja Marupaka
eba9edd7a6 Sync openAPI setter values with schema 2020-09-22 14:05:05 -07:00
Kubernetes Prow Robot
cf38166bd6 Merge pull request #3030 from mortent/FixDotGitFiles
copyutil should not ignore files that just happen to start with .git
2020-09-22 13:42:09 -07:00
Morten Torkildsen
03498b46b8 copyutil should not ignore files that just happen to start with .git 2020-09-22 12:32:06 -07:00
Donny Xia
9fa9c6c30c Update issue templates 2020-09-22 12:08:50 -07:00
Donny Xia
884e35b4c8 issue template 2020-09-22 12:08:50 -07:00
Kubernetes Prow Robot
28787396b2 Merge pull request #3026 from mortent/RenameGetIgnoreFileNameFunc
Drop the get prefix from GetIgnoreFileName function
2020-09-22 10:56:42 -07:00
Jeff Regan
e3cf8987e1 Merge pull request #3025 from seans3/live-command-fix
Small change to live commands retrieval
2020-09-22 09:19:27 -07:00
June Yi
551841b789 Support exec plugin on Windows 2020-09-22 22:42:18 +09:00
Morten Torkildsen
66740dfad6 Drop the get prefix from GetIgnoreFileName function 2020-09-21 20:54:57 -07:00
Kubernetes Prow Robot
537ff024dd Merge pull request #2981 from mortent/SimplifyCmdConfigExt
Simplify the cmd/config ext package
2020-09-21 17:56:47 -07:00
Morten Torkildsen
cfab28a5ff Simplify the cmd/config ext package 2020-09-21 17:30:36 -07:00
Sean Sullivan
471d5ccf84 Small change to live commands retrieval 2020-09-21 16:41:48 -07:00
Timo Walter
6a9e75ee0d Improve the "install_kustomize.sh" script
- fix formatting
- remove unnecessary echo statements
2020-09-21 23:09:16 +02:00
Kubernetes Prow Robot
7500764cbf Merge pull request #3000 from Shell32-Natsu/res-select
fix namespace will match all empty namespace
2020-09-21 13:07:52 -07:00
Donny Xia
544fc60bfe add another test 2020-09-21 12:24:47 -07:00
Jeff Regan
0850eae0b9 Merge pull request #3001 from Shell32-Natsu/patch-delete
handle the "$patch: delete" in patch transformer
2020-09-21 12:03:40 -07:00
Jeff Regan
3818cebe33 Merge pull request #3011 from natasha41575/issue2896test
test for issue 2896
2020-09-21 11:59:51 -07:00
Donny Xia
31b395a33f handle the "$patch: delete" in patch transformer 2020-09-21 11:46:39 -07:00
Natasha Sarkar
ce0dba9217 fixed bug in base test 2020-09-21 11:32:26 -07:00
Natasha Sarkar
9abd0119e1 test for issue 2896 2020-09-21 11:25:54 -07:00
Jeff Regan
b6c6cfa7ac Update README.md 2020-09-21 10:24:08 -07:00
Timo Walter
0c5fc5e694 Extend the install_kustomize.sh to enable the installation of specific versions 2020-09-21 15:16:57 +02:00
Alexey Odinokov
64cbfbe56d added test for env vars 2020-09-21 06:14:09 +00:00
Jeff Regan
6a94eb873f Merge pull request #3018 from monopole/unpinEverything
Unpin api, kyaml and cmd/config
2020-09-20 08:46:55 -07:00
jregan
0bfec6b39b Unpin kyaml, cmd/config and api. 2020-09-20 08:07:32 -07:00
Jeff Regan
9002c338cb Merge pull request #3019 from monopole/installGh
Install gh cli tool via make
2020-09-20 07:39:52 -07:00
jregan
f86cb6479e Install gh cli tool via make 2020-09-20 07:39:16 -07:00
Jeff Regan
8285af8cf1 Merge pull request #3017 from monopole/updateREADME
Update release instructions.
2020-09-19 08:33:25 -07:00
Jeffrey Regan
5fa1282dcb Update release instructions. 2020-09-19 08:32:53 -07:00
Jeff Regan
5a0abc8b12 Merge pull request #3016 from monopole/pinToApiV0.6.2
Pin to api v0.6.2
2020-09-19 08:22:13 -07:00
Jeffrey Regan
3f2508fa94 Pin to api v0.6.2 2020-09-19 07:48:07 -07:00
Jeff Regan
9d992aae68 Merge pull request #3015 from monopole/pinToCmdConfigV0.8.1
Pin to cmd/config/v0.8.1
2020-09-19 07:42:05 -07:00
Jeffrey Regan
8c906b804f Pin to cmd/config/v0.8.1 2020-09-19 07:12:13 -07:00
Jeff Regan
4ff4940fa7 Update README.md 2020-09-18 18:28:42 -07:00
Jeff Regan
09aec5694a Merge pull request #3013 from monopole/generated
Generated pin to cli-utils v0.20.2 hash
2020-09-18 18:26:25 -07:00
Jeffrey Regan
1f917c0499 Generated pin to cli-utils v0.20.2 hash 2020-09-18 17:52:33 -07:00
Kubernetes Prow Robot
225ffc7cd8 Merge pull request #3012 from Shell32-Natsu/remove-network-name
remove --network-name flag from kpt fn run
2020-09-18 16:48:27 -07:00
Kubernetes Prow Robot
eb638cc312 Merge pull request #3009 from Shell32-Natsu/endpoint-service
put endpoints before service
2020-09-18 14:20:28 -07:00
Jeff Regan
7dfb96425e Merge pull request #3010 from monopole/pinToCliUtils_v0.20.2
Pin to cli-utils/v0.20.2
2020-09-18 13:35:02 -07:00
Jeff Regan
6d4c6127c8 Update README.md 2020-09-18 13:18:54 -07:00
Jeff Regan
6aa72b66ef Update README.md 2020-09-18 13:15:52 -07:00
Jeff Regan
f03fdc09cb Update README.md 2020-09-18 13:10:19 -07:00
Jeffrey Regan
30b6eeb460 Pin to cli-utils/v0.20.2 2020-09-18 13:08:53 -07:00
Jeff Regan
bf67fcb6d6 Update README.md 2020-09-18 12:55:59 -07:00
Jeff Regan
4ae420cce1 Merge pull request #3008 from monopole/pinToKyamlv_0_8_1
Pin to kyaml v0.8.1
2020-09-18 12:40:02 -07:00
Donny Xia
87d2187436 remove --network-name flag from kpt fn run 2020-09-18 12:39:49 -07:00
Donny Xia
f1dabbd4fc put endpoints before service 2020-09-18 12:21:03 -07:00
Jeffrey Regan
747e05f2a4 Pin to kyaml v0.8.1 2020-09-18 12:11:03 -07:00
Jeff Regan
3514317b3d Merge pull request #3007 from monopole/unpin
Unpin the dependencies post release.
2020-09-18 11:19:42 -07:00
Jeff Regan
9299821571 Merge pull request #2998 from Shell32-Natsu/network
Change network to a boolean in kpt fn run
2020-09-18 11:12:26 -07:00
Jeffrey Regan
d91f313137 Unpin the dependencies post release. 2020-09-18 09:51:05 -07:00
Jeff Regan
161af9d99c Merge pull request #3002 from monopole/pinToApiV0_6_1
Pin to api/v0.6.1
2020-09-17 17:18:11 -07:00
jregan
b115c95ea1 Pin to api/v0.6.1 2020-09-17 16:27:08 -07:00
Sam Wronski
4c75dac10a Adds a directory spanning check script 2020-09-17 16:18:17 -07:00
Donny Xia
2f8a376ae4 fix namespace will match all empty namespace 2020-09-17 12:46:18 -07:00
Jeff Regan
20cd4bfef9 Merge pull request #2997 from kubernetes-sigs/removeReplaceDir
Update go.mod
2020-09-17 11:02:08 -07:00
Alexey Odinokov
b314ca185f Added list of env variables for fn-plugins
KRM-functions should be able get env variables.
Reflecting in `build` cmd args added in [1]
for `fn run` cmd.

[1]
https://github.com/kubernetes-sigs/kustomize/pull/2988/
2020-09-17 03:41:36 +00:00
Donny Xia
f6c06b58ef Change network to a boolean 2020-09-16 16:20:50 -07:00
Jeff Regan
c45e05b7bd Update go.mod 2020-09-16 12:53:39 -07:00
Kubernetes Prow Robot
76bae738a0 Merge pull request #2932 from mstrYoda/master
add DisableNameSuffixHash parameter to edit Secret & ConfigMap
2020-09-16 10:29:20 -07:00
Pascal Bourdier
98c88805c3 fix typo
typo
2020-09-16 15:36:36 +02:00
Jeff Regan
0770661b2a Merge pull request #2991 from monopole/goSumUpdates
Go sum updates
2020-09-15 17:34:23 -07:00
jregan
67d5871e87 Go sum updates 2020-09-15 17:02:40 -07:00
Jeff Regan
f98c683915 Merge pull request #2983 from Shell32-Natsu/allow-null
ignore null value in fieldspec
2020-09-15 17:02:20 -07:00
Jeff Regan
ffe9c9d947 Merge pull request #2990 from monopole/pinToKyamlv0_8_0
Pin to kyaml v0.8.0
2020-09-15 15:51:08 -07:00
jregan
4d42ffc7f8 Pin to kyaml v0.8.0 2020-09-15 15:26:29 -07:00
Jeff Regan
d7dc7d911e Merge pull request #2989 from monopole/minorFix
Generated changes.
2020-09-15 14:56:16 -07:00
jregan
04404ff61b Generated changes. 2020-09-15 14:55:08 -07:00
Jeff Regan
f864e15c68 Merge pull request #2974 from Shell32-Natsu/function-definition
remove not used args & use const string instead of literal
2020-09-15 14:34:25 -07:00
Jeff Regan
29a444fffc Merge pull request #2988 from Shell32-Natsu/env-flag
Add --env/-e flag to fn run
2020-09-15 14:31:40 -07:00
Donny Xia
327035a43a Add --env/-e flag 2020-09-15 11:49:26 -07:00
Kubernetes Prow Robot
ad7fed061e Merge pull request #2984 from phanimarupaka/FixCmdCfgIssues
Do not print package info in grep
2020-09-15 09:40:07 -07:00
Phani Teja Marupaka
cea2986574 Don not pring package info in grep 2020-09-15 00:15:52 -07:00
Kubernetes Prow Robot
00f0fd7109 Merge pull request #2978 from mortent/NamespaceabilityFromSchema
Determine namespaceability of resources from openapi schema
2020-09-14 21:10:06 -07:00
Kubernetes Prow Robot
1c6481d011 Merge pull request #2982 from mortent/UpdateCliUtils
Update cmd/config to use latest version of cli-utils
2020-09-14 13:27:24 -07:00
Donny Xia
f0bc926640 ignore null value in fieldspec 2020-09-14 13:20:20 -07:00
Morten Torkildsen
11d9ff5690 Update cmd/config to use latest version of cli-utils 2020-09-14 12:08:48 -07:00
Jeff Regan
6a0a909e73 Merge pull request #2976 from monopole/deferLive
Remove live; done testing.  Bring to sig-cli for discussion.
2020-09-14 11:00:48 -07:00
Kubernetes Prow Robot
bd8f0c88e5 Merge pull request #2967 from phanimarupaka/CfgTreeWithSubpackages
Print Krmfile data for cfg tree
2020-09-14 10:42:59 -07:00
Donny Xia
e5809e49cb remove not used args 2020-09-14 10:10:20 -07:00
Phani Teja Marupaka
880009b648 Print Krmfile data for cfg tree 2020-09-14 09:57:18 -07:00
Morten Torkildsen
d083c7f1d0 Determine namespaceability of resources from openapi schema 2020-09-12 15:01:42 -07:00
Jeffrey Regan
684ce141de Defer live testing. 2020-09-11 17:25:25 -07:00
Kubernetes Prow Robot
5c8c7a043a Merge pull request #2973 from phanimarupaka/CfgCommandsStdoutFixes
Format the output of cfg commands
2020-09-11 16:44:57 -07:00
Kubernetes Prow Robot
0fe7f65ef2 Merge pull request #2975 from monopole/addTest
Add test representing 2960
2020-09-11 16:10:57 -07:00
Jeffrey Regan
950c1de46d Add test representing 2960 2020-09-11 15:22:41 -07:00
Phani Teja Marupaka
fc690f14a8 Format the output of cfg commands 2020-09-11 14:49:18 -07:00
Jeff Regan
a6e03e4d11 Merge pull request #2920 from wyyxd2017/hato4
Technical details structure picture
2020-09-11 14:32:19 -07:00
Jeff Regan
60428be5fb Merge pull request #2944 from justinsb/alas_poor_grepfilter
Remove some obsolete references to GrepFilter
2020-09-11 14:16:30 -07:00
Jeff Regan
4d402d4875 Merge pull request #2969 from justinsb/fix_split_docs
Fix comment on SplitIndexNameValue
2020-09-11 14:13:43 -07:00
Jeff Regan
fbddd264be Merge pull request #2971 from etefera/fix-broken-patches-change
Fix unintended patches change in all Kustomization writes.
2020-09-11 13:33:09 -07:00
Eyob Tefera
d3c46d3f7c Move offending Write() tests to tests for fix. 2020-09-11 19:19:54 +00:00
Eyob Tefera
dda3984a8f Move kustomization fixing to before Write step. 2020-09-11 18:57:14 +00:00
Eyob Tefera
f889ca8885 Add set image test with patchesJson6902. 2020-09-11 18:48:48 +00:00
Justin SB
341bacb9a2 Fix comment on SplitIndexNameValue
It was incorrect and suggested some behaviour which isn't present.
Added test to verify the documented behaviour.
2020-09-11 11:39:49 -04:00
Kubernetes Prow Robot
badc1177d9 Merge pull request #2939 from ZhuGongpu/master
Add --log-steps flag
2020-09-09 19:05:44 -07:00
Kubernetes Prow Robot
1680cc72c0 Merge pull request #2953 from easimon/add_namespace_to_namespace_transformer
Add namespace name to namespace transformer defaults
2020-09-09 14:57:44 -07:00
Jeff Regan
2f89de86f8 Merge pull request #2956 from justinsb/fix_language
Replace language with more inclusive & accurate "hard-coded"
2020-09-09 11:33:53 -07:00
Jeff Regan
ab4e9c718b Merge pull request #2943 from Shell32-Natsu/clean-up-temp-dir
remove all temp dir
2020-09-09 11:20:17 -07:00
Kubernetes Prow Robot
288c03ddca Merge pull request #2959 from phanimarupaka/CatWithSubpkgs
Cat with subpackages
2020-09-09 10:49:08 -07:00
Justin SB
5c60285f25 Replace language with more inclusive & accurate "hard-coded"
hard-coded is probably more helpful to understanding the limitations
of the current approach.
2020-09-09 08:41:33 -04:00
Kubernetes Prow Robot
6df0a45368 Merge pull request #2958 from phanimarupaka/GrepWithSubpkgs
Grep with subpackages
2020-09-08 21:09:52 -07:00
Kubernetes Prow Robot
8206987580 Merge pull request #2957 from phanimarupaka/CountWithSubpkgs
Count with Subpackages
2020-09-08 20:53:52 -07:00
Kubernetes Prow Robot
6189ca9798 Merge pull request #2955 from phanimarupaka/FmtWithSubpkgs
Fmt with subpackages
2020-09-08 20:33:52 -07:00
Phani Teja Marupaka
b8c1601a93 Cat with subpackages 2020-09-08 18:42:31 -07:00
Phani Teja Marupaka
34d610a38d Fmt with subpackages 2020-09-08 17:07:55 -07:00
Phani Teja Marupaka
8e4c8464e7 Grep with subpackages 2020-09-08 16:59:23 -07:00
Phani Teja Marupaka
43ab7a8e71 Count with Subpackages 2020-09-08 16:33:00 -07:00
Kubernetes Prow Robot
d2f23a4b8b Merge pull request #2938 from phanimarupaka/OtherCfgCommandsWithSubPkgs
annotate, delete-setter, delete-subst With Subpackages
2020-09-08 16:25:52 -07:00
Phani Teja Marupaka
0dc36a4f7c Annotate With Subpackages
Delete Setters And Subst With Subpkgs
2020-09-08 15:52:57 -07:00
Kubernetes Prow Robot
678ae12115 Merge pull request #2946 from phanimarupaka/RefactorSubPkgsIteration
Refactor subpackages logic
2020-09-08 11:47:52 -07:00
Phani Teja Marupaka
c4d937322f Refactor subpackages logic 2020-09-08 11:23:54 -07:00
Kubernetes Prow Robot
a2adb835b6 Merge pull request #2941 from mortent/FixIgnoreFilesMatcher
Fix issue where ignoreFilesMatcher doesn't work correctly
2020-09-08 10:33:44 -07:00
Markus Dobel
01b5c4e9da Add namespace name to namespace transformer defaults 2020-09-08 11:24:58 +02:00
Naveen Gogineni
5a4e2c2898 Add basic structure for command line options for users to be able to place info into them 2020-09-05 11:36:49 -04:00
dearchap
51719d8089 Update _index.md 2020-09-05 10:28:27 -04:00
Justin SB
eb4c5dc035 Remove some obsolete references to GrepFilter
Looks like GrepFilter was generalized to Filter.
2020-09-04 13:41:16 -04:00
Morten Torkildsen
e976386931 Fix issue where ignoreFilesMatcher doesn't work correctly 2020-09-03 20:14:07 -07:00
Donny Xia
bae9986422 remove all temp dir 2020-09-03 12:03:12 -07:00
Jeff Regan
e7970d82a8 Merge pull request #2942 from Shell32-Natsu/addDonny
add Donny to maintainer
2020-09-03 11:52:14 -07:00
Donny Xia
9bdd489c96 add Donny to maintainer 2020-09-03 10:57:50 -07:00
Kubernetes Prow Robot
0f49fef5ed Merge pull request #2940 from phanimarupaka/FixSettersSubPkgsFriction
Fix setters subpkgs friction
2020-09-03 08:59:41 -07:00
Phani Teja Marupaka
8d74b8c3b5 Fix setters subpkgs friction 2020-09-02 23:06:26 -07:00
Gongpu Zhu
39a8798a87 Add --log-steps flag 2020-09-02 20:47:21 -07:00
Jeff Regan
980f407552 Merge pull request #2931 from Shell32-Natsu/image-tag-legacy
add legacy filter to image tag transformer
2020-09-02 13:02:53 -07:00
Donny Xia
9ca8f4602d add legacy filter to image tag transformer 2020-09-01 13:06:14 -07:00
Kubernetes Prow Robot
ba0f583ee5 Merge pull request #2911 from phanimarupaka/SetWithSubPackages
Setters/substitutions with subpackages
2020-09-01 11:23:51 -07:00
Phani Teja Marupaka
f432f4d75e Setters with subpackages 2020-09-01 10:54:08 -07:00
Jeff Regan
17793abacd Merge pull request #2930 from daniel-hutao/patch-1
fix “chart s” to “charts ”
2020-09-01 10:12:58 -07:00
Jeff Regan
64cd4ec1d5 Merge pull request #2929 from monopole/testExamplesAgainst_v3.8.2
Test examples against v3.8.2
2020-09-01 10:12:18 -07:00
Daniel (ht)
fb822984e3 fix “chart s” to “charts ”
fix “chart s” to “charts ”
2020-09-01 16:24:49 +08:00
jregan
6d2a737c29 Test examples against v3.8.2 2020-08-31 16:48:19 -07:00
Jeff Regan
6e7713281e Merge pull request #2928 from monopole/addGorepomod
Add more release instructions
2020-08-31 13:50:48 -07:00
jregan
6a7bb9e33e Add gorepomod tool to install list 2020-08-31 13:28:19 -07:00
Jeff Regan
0e9428c8b0 Merge pull request #2927 from monopole/unpinning
Unpinning after release releases
2020-08-31 12:47:28 -07:00
jregan
c838962432 fix module hashes 2020-08-31 12:08:16 -07:00
jregan
548d10ef08 unpin kyaml 2020-08-31 12:08:16 -07:00
jregan
2db8487f02 unpin cmd/config 2020-08-31 12:08:16 -07:00
jregan
b42f71a20f unpin api 2020-08-31 12:08:16 -07:00
Jeff Regan
e9824aa749 Merge pull request #2926 from monopole/fixAGoMod
Repair a go module spec.
2020-08-31 12:08:06 -07:00
jregan
92cc9fc5e1 Repair a go module spec. 2020-08-31 11:35:32 -07:00
wangyeyu
e53b4c9884 Technical details structure picture 2020-08-31 10:01:19 +08:00
guoxudong
d4503dfd1e update zh doc patches 2020-08-31 09:38:59 +08:00
Jeff Regan
e2973f6ecc Merge pull request #2915 from monopole/pinToKustomizeApiv_0_6_0
Pin to kustomize api v0.6.0
2020-08-29 09:42:26 -07:00
jregan
2bf9fc816d Pin to kustomize api v0.6.0 2020-08-29 08:55:29 -07:00
mstrYoda
257707d839 Merge branch 'master' of https://github.com/kubernetes-sigs/kustomize 2020-08-26 13:24:04 +03:00
mstrYoda
c1cd872df6 add DisableNameSuffixHash for secret and configmap 2020-08-26 13:22:26 +03:00
783 changed files with 481089 additions and 47252 deletions

8
.dockerignore Normal file
View File

@@ -0,0 +1,8 @@
.github
docs
examples
functions
hack
site
travis
*.md

68
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,68 @@
---
name: Bug report
about: Create a report to help us improve
title: ""
labels:
- kind/bug
assignees: ""
---
<!--
Please read this page: https://kubernetes-sigs.github.io/kustomize/contributing/bugs/ before
filing a bug
-->
<!-- Feel free to skip the sections if they are not applicable. -->
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
**Files that can reproduce the issue**
<!--
We cannot figure out or fix the issue if we don't know how to reproduce. Please
provide a minimum set of files that can reproduce the issue. You can paste the
file contents here or provide a link to a tarball or git repo.
Example:
kustomization.yaml
```
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
...
```
resources.yaml
```
apiVersion: v1
kind: Deployment
...
```
...
-->
**Expected output**
<!-- What's the expected output? -->
**Actual output**
<!-- What's the actual output? -->
**Kustomize version**
<!-- Please use the latest version when it's possible. -->
**Platform**
<!-- Linux/macOS/Windows? -->
**Additional context**
<!-- Add any other context about the problem here. -->

1
.github/ISSUE_TEMPLATE/config.yaml vendored Normal file
View File

@@ -0,0 +1 @@
blank_issues_enabled: true

View File

@@ -0,0 +1,26 @@
---
name: Feature request
about: Suggest an idea for this project
title: ""
labels:
- kind/feature
assignees: ""
---
<!-- Feel free to skip the sections if they are not applicable. -->
**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->
**Describe alternatives you've considered**
<!-- A clear and concise description of any alternative solutions or features you've considered. -->
**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->

9
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View File

@@ -0,0 +1,9 @@
---
name: Question
about: Ask a question about the kustomize
title: "[Question]"
labels: ""
assignees: ""
---
<!-- Please describe your question here -->

View File

@@ -23,7 +23,7 @@ jobs:
uses: actions/checkout@v2
- name: Lint
run: ./travis/kyaml-pre-commit.sh
run: ./scripts/kyaml-pre-commit.sh
env:
KUSTOMIZE_DOCKER_E2E: false # don't need to do e2e tests for linting

125
Makefile
View File

@@ -6,6 +6,17 @@
MYGOBIN := $(shell go env GOPATH)/bin
SHELL := /bin/bash
export PATH := $(MYGOBIN):$(PATH)
MODULES := '"cmd/config" "api/" "kustomize/" "kyaml/"'
# Provide defaults for REPO_OWNER and REPO_NAME if not present.
# Typically these values would be provided by Prow.
ifndef REPO_OWNER
REPO_OWNER := "kubernetes-sigs"
endif
ifndef REPO_NAME
REPO_NAME := "kustomize"
endif
.PHONY: all
all: verify-kustomize
@@ -15,18 +26,19 @@ verify-kustomize: \
lint-kustomize \
test-unit-kustomize-all \
test-examples-kustomize-against-HEAD \
test-examples-kustomize-against-3.8.0
test-examples-kustomize-against-3.8.6
# The following target referenced by a file in
# https://github.com/kubernetes/test-infra/tree/master/config/jobs/kubernetes-sigs/kustomize
.PHONY: prow-presubmit-check
prow-presubmit-check: \
lint-kustomize \
test-multi-module \
test-unit-kustomize-all \
test-unit-cmd-all \
test-go-mod \
test-examples-kustomize-against-HEAD \
test-examples-kustomize-against-3.8.0
test-examples-kustomize-against-3.8.6
.PHONY: verify-kustomize-e2e
verify-kustomize-e2e: test-examples-e2e-kustomize
@@ -45,34 +57,37 @@ $(MYGOBIN)/golangci-lint-kustomize:
GO111MODULE=on go build -tags=tools -o $(MYGOBIN)/golangci-lint-kustomize github.com/golangci/golangci-lint/cmd/golangci-lint; \
)
# Version pinned by api/go.mod
# Install from version specified in api/go.mod.
$(MYGOBIN)/mdrip:
cd api; \
go install github.com/monopole/mdrip
# Version pinned by api/go.mod
# Install from version specified in api/go.mod.
$(MYGOBIN)/stringer:
cd api; \
go install golang.org/x/tools/cmd/stringer
# Version pinned by api/go.mod
# Install from version specified in api/go.mod.
$(MYGOBIN)/goimports:
cd api; \
go install golang.org/x/tools/cmd/goimports
# Install resource from whatever is checked out.
$(MYGOBIN)/resource:
cd cmd/resource; \
# Build from local source.
$(MYGOBIN)/gorepomod:
cd cmd/gorepomod; \
go install .
# To pin pluginator, use this recipe instead:
# cd api;
# go install sigs.k8s.io/kustomize/pluginator/v2
# Build from local source.
$(MYGOBIN)/pluginator:
cd pluginator; \
cd cmd/pluginator; \
go install .
# Install kustomize from whatever is checked out.
# Build from local source.
$(MYGOBIN)/prchecker:
cd cmd/prchecker; \
go install .
# Build from local source.
$(MYGOBIN)/kustomize:
cd kustomize; \
go install .
@@ -81,9 +96,13 @@ $(MYGOBIN)/kustomize:
install-tools: \
$(MYGOBIN)/goimports \
$(MYGOBIN)/golangci-lint-kustomize \
$(MYGOBIN)/gh \
$(MYGOBIN)/gorepomod \
$(MYGOBIN)/mdrip \
$(MYGOBIN)/pluginator \
$(MYGOBIN)/stringer
$(MYGOBIN)/prchecker \
$(MYGOBIN)/stringer \
$(MYGOBIN)/helm
### Begin kustomize plugin rules.
#
@@ -125,7 +144,8 @@ _builtinplugins = \
PrefixSuffixTransformer.go \
ReplicaCountTransformer.go \
SecretGenerator.go \
ValueAddTransformer.go
ValueAddTransformer.go \
HelmChartInflationGenerator.go
# Maintaining this explicit list of generated files, and
# adding it as a dependency to a few targets, to assure
@@ -151,6 +171,7 @@ $(pGen)/PrefixSuffixTransformer.go: $(pSrc)/prefixsuffixtransformer/PrefixSuffix
$(pGen)/ReplicaCountTransformer.go: $(pSrc)/replicacounttransformer/ReplicaCountTransformer.go
$(pGen)/SecretGenerator.go: $(pSrc)/secretgenerator/SecretGenerator.go
$(pGen)/ValueAddTransformer.go: $(pSrc)/valueaddtransformer/ValueAddTransformer.go
$(pGen)/HelmChartInflationGenerator.go: $(pSrc)/helmchartinflationgenerator/HelmChartInflationGenerator.go
# The (verbose but portable) Makefile way to convert to lowercase.
toLowerCase = $(subst A,a,$(subst B,b,$(subst C,c,$(subst D,d,$(subst E,e,$(subst F,f,$(subst G,g,$(subst H,h,$(subst I,i,$(subst J,j,$(subst K,k,$(subst L,l,$(subst M,m,$(subst N,n,$(subst O,o,$(subst P,p,$(subst Q,q,$(subst R,r,$(subst S,s,$(subst T,t,$(subst U,u,$(subst V,v,$(subst W,w,$(subst X,x,$(subst Y,y,$(subst Z,z,$1))))))))))))))))))))))))))
@@ -169,24 +190,27 @@ $(pGen)/%.go: $(MYGOBIN)/pluginator
.PHONY: generate-kustomize-builtin-plugins
generate-kustomize-builtin-plugins: $(builtinplugins)
.PHONY: kustomize-external-go-plugin-build
kustomize-external-go-plugin-build:
.PHONY: build-kustomize-external-go-plugin
build-kustomize-external-go-plugin:
./hack/buildExternalGoPlugins.sh ./plugin
.PHONY: kustomize-external-go-plugin-clean
kustomize-external-go-plugin-clean:
.PHONY: clean-kustomize-external-go-plugin
clean-kustomize-external-go-plugin:
./hack/buildExternalGoPlugins.sh ./plugin clean
### End kustomize plugin rules.
.PHONY: lint-kustomize
lint-kustomize: install-tools $(builtinplugins)
cd api; \
$(MYGOBIN)/golangci-lint-kustomize -c ../.golangci-kustomize.yml run ./...
cd kustomize; \
$(MYGOBIN)/golangci-lint-kustomize -c ../.golangci-kustomize.yml run ./...
cd pluginator; \
$(MYGOBIN)/golangci-lint-kustomize -c ../.golangci-kustomize.yml run ./...
cd api; $(MYGOBIN)/golangci-lint-kustomize \
-c ../.golangci-kustomize.yml \
run ./...
cd kustomize; $(MYGOBIN)/golangci-lint-kustomize \
-c ../.golangci-kustomize.yml \
run ./...
cd cmd/pluginator; $(MYGOBIN)/golangci-lint-kustomize \
-c ../../.golangci-kustomize.yml \
run ./...
# Used to add non-default compilation flags when experimenting with
# plugin-to-api compatibility checks.
@@ -194,6 +218,10 @@ lint-kustomize: install-tools $(builtinplugins)
build-kustomize-api: $(builtinplugins)
cd api; go build ./...
.PHONY: generate-kustomize-api
generate-kustomize-api:
cd api; go generate ./...
.PHONY: test-unit-kustomize-api
test-unit-kustomize-api: build-kustomize-api
cd api; go test ./... -ldflags "-X sigs.k8s.io/kustomize/api/provenance.version=v444.333.222"
@@ -213,10 +241,23 @@ test-unit-kustomize-all: \
test-unit-kustomize-plugins
test-unit-cmd-all:
./travis/kyaml-pre-commit.sh
./scripts/kyaml-pre-commit.sh
test-go-mod:
./travis/check-go-mod.sh
./scripts/check-go-mod.sh
# Environment variables are defined at
# https://github.com/kubernetes/test-infra/blob/master/prow/jobs.md#job-environment-variables
.PHONY: test-multi-module
test-multi-module: $(MYGOBIN)/prchecker
( \
export MYGOBIN=$(MYGOBIN); \
export REPO_OWNER=$(REPO_OWNER); \
export REPO_NAME=$(REPO_NAME); \
export PULL_NUMBER=$(PULL_NUMBER); \
export MODULES=$(MODULES); \
./scripts/check-multi-module.sh; \
)
.PHONY:
test-examples-e2e-kustomize: $(MYGOBIN)/mdrip $(MYGOBIN)/kind
@@ -233,10 +274,10 @@ test-examples-kustomize-against-HEAD: $(MYGOBIN)/kustomize $(MYGOBIN)/mdrip
./hack/testExamplesAgainstKustomize.sh HEAD
.PHONY:
test-examples-kustomize-against-3.8.0: $(MYGOBIN)/mdrip
test-examples-kustomize-against-3.8.6: $(MYGOBIN)/mdrip
( \
set -e; \
tag=v3.8.0; \
tag=v3.8.6; \
/bin/rm -f $(MYGOBIN)/kustomize; \
echo "Installing kustomize $$tag."; \
GO111MODULE=on go get sigs.k8s.io/kustomize/kustomize/v3@$${tag}; \
@@ -283,16 +324,16 @@ $(MYGOBIN)/helmV3:
( \
set -e; \
d=$(shell mktemp -d); cd $$d; \
tgzFile=helm-v3.2.0-rc.1-linux-amd64.tar.gz; \
tgzFile=helm-v3.4.0-linux-amd64.tar.gz; \
wget https://get.helm.sh/$$tgzFile; \
tar -xvzf $$tgzFile; \
mv linux-amd64/helm $(MYGOBIN)/helmV3; \
rm -rf $$d \
)
# Default version of helm is v2 for the time being.
$(MYGOBIN)/helm: $(MYGOBIN)/helmV2
ln -s $(MYGOBIN)/helmV2 $(MYGOBIN)/helm
# Default version of helm is v3.
$(MYGOBIN)/helm: $(MYGOBIN)/helmV3
ln -s $(MYGOBIN)/helmV3 $(MYGOBIN)/helm
$(MYGOBIN)/kind:
( \
@@ -304,14 +345,28 @@ $(MYGOBIN)/kind:
rm -rf $$d; \
)
# linux only.
$(MYGOBIN)/gh:
( \
set -e; \
d=$(shell mktemp -d); cd $$d; \
tgzFile=gh_1.0.0_linux_amd64.tar.gz; \
wget https://github.com/cli/cli/releases/download/v1.0.0/$$tgzFile; \
tar -xvzf $$tgzFile; \
mv gh_1.0.0_linux_amd64/bin/gh $(MYGOBIN)/gh; \
rm -rf $$d \
)
.PHONY: clean
clean: kustomize-external-go-plugin-clean
clean: clean-kustomize-external-go-plugin
go clean --cache
rm -f $(builtinplugins)
rm -f $(MYGOBIN)/pluginator
rm -f $(MYGOBIN)/kustomize
rm -f $(MYGOBIN)/golangci-lint-kustomize
# Handle pluginator manually.
# rm -f $(MYGOBIN)/pluginator
# Nuke the site from orbit. It's the only way to be sure.
.PHONY: nuke
nuke: clean

View File

@@ -11,3 +11,4 @@ aliases:
- pwittrock
- mortent
- phanimarupaka
- Shell32-Natsu

View File

@@ -20,15 +20,20 @@ This tool is sponsored by [sig-cli] ([KEP]).
## kubectl integration
Since [v1.14][kubectl announcement] the kustomize build system has been included in kubectl.
The kustomize build flow at [v2.0.3] was added
to [kubectl v1.14][kubectl announcement]. The kustomize
flow in kubectl has remained frozen at v2.0.3 while work
to extract kubectl from the k/k repo, and work to remove
kustomize's dependence on core k/k code ([#2506]) has proceeded.
The reintegration effort is tracked in [#1500] (and its blocking
issues).
| kubectl version | kustomize version |
|---------|--------|
| v1.16.0 | [v2.0.3](/../../tree/v2.0.3) |
| v1.15.x | [v2.0.3](/../../tree/v2.0.3) |
| v1.14.x | [v2.0.3](/../../tree/v2.0.3) |
[v2.0.3]: /../../tree/v2.0.3
[#2506]: https://github.com/kubernetes-sigs/kustomize/issues/2506
[#1500]: https://github.com/kubernetes-sigs/kustomize/issues/1500
For examples and guides for using the kubectl integration please see the [kubectl book] or the [kubernetes documentation].
For examples and guides for using the kubectl integration please
see the [kubectl book] or the [kubernetes documentation].
## Usage
@@ -148,7 +153,7 @@ is governed by the [Kubernetes Code of Conduct].
[imageBase]: docs/images/base.jpg
[imageOverlay]: docs/images/overlay.jpg
[kubectl announcement]: https://kubernetes.io/blog/2019/03/25/kubernetes-1-14-release-announcement
[kubectl book]: https://kubectl.docs.kubernetes.io/pages/app_customization/introduction.html
[kubectl book]: https://kubectl.docs.kubernetes.io/guides/introduction/kustomize/
[kubernetes documentation]: https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/
[kubernetes style]: https://kubernetes-sigs.github.io/kustomize/api-reference/glossary#kubernetes-style-object
[kustomization]: https://kubernetes-sigs.github.io/kustomize/api-reference/glossary#kustomization

View File

@@ -0,0 +1,179 @@
// Code generated by pluginator on HelmChartInflationGenerator; DO NOT EDIT.
// pluginator {unknown 1970-01-01T00:00:00Z }
package builtins
import (
"bytes"
"fmt"
"os"
"os/exec"
"path"
"regexp"
"strings"
"github.com/pkg/errors"
"sigs.k8s.io/kustomize/api/filesys"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/yaml"
)
// HelmChartInflationGeneratorPlugin is a plugin to generate resources
// from a remote or local helm chart.
type HelmChartInflationGeneratorPlugin struct {
h *resmap.PluginHelpers
types.ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
runHelmCommand func([]string) ([]byte, error)
types.HelmChartArgs
tmpDir string
}
var KustomizePlugin HelmChartInflationGeneratorPlugin
// Config uses the input plugin configurations `config` to setup the generator
// options
func (p *HelmChartInflationGeneratorPlugin) Config(h *resmap.PluginHelpers, config []byte) error {
p.h = h
err := yaml.Unmarshal(config, p)
if err != nil {
return err
}
tmpDir, err := filesys.NewTmpConfirmedDir()
if err != nil {
return err
}
p.tmpDir = string(tmpDir)
if p.ChartName == "" {
return fmt.Errorf("chartName cannot be empty")
}
if p.ChartHome == "" {
p.ChartHome = path.Join(p.tmpDir, "chart")
}
if p.ChartRepoName == "" {
p.ChartRepoName = "stable"
}
if p.HelmBin == "" {
p.HelmBin = "helm"
}
if p.HelmHome == "" {
p.HelmHome = path.Join(p.tmpDir, ".helm")
}
if p.Values == "" {
p.Values = path.Join(p.ChartHome, p.ChartName, "values.yaml")
}
// runHelmCommand will run `helm` command with args provided. Return stdout
// and error if there is any.
p.runHelmCommand = func(args []string) ([]byte, error) {
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
cmd := exec.Command(p.HelmBin, args...)
cmd.Stdout = stdout
cmd.Stderr = stderr
cmd.Env = append(cmd.Env,
fmt.Sprintf("HELM_CONFIG_HOME=%s", p.HelmHome),
fmt.Sprintf("HELM_CACHE_HOME=%s/.cache", p.HelmHome),
fmt.Sprintf("HELM_DATA_HOME=%s/.data", p.HelmHome),
)
err := cmd.Run()
if err != nil {
return stdout.Bytes(),
errors.Wrap(
fmt.Errorf("failed to run command %s %s", p.HelmBin, strings.Join(args, " ")),
stderr.String(),
)
}
return stdout.Bytes(), nil
}
return nil
}
// Generate implements generator
func (p *HelmChartInflationGeneratorPlugin) Generate() (resmap.ResMap, error) {
// cleanup
defer os.RemoveAll(p.tmpDir)
// check helm version. we only support V3
err := p.checkHelmVersion()
if err != nil {
return nil, err
}
// pull the chart
if !p.checkLocalChart() {
_, err := p.runHelmCommand(p.getPullCommandArgs())
if err != nil {
return nil, err
}
}
// render the charts
stdout, err := p.runHelmCommand(p.getTemplateCommandArgs())
if err != nil {
return nil, err
}
return p.h.ResmapFactory().NewResMapFromBytes(stdout)
}
func (p *HelmChartInflationGeneratorPlugin) getTemplateCommandArgs() []string {
args := []string{"template"}
if p.ReleaseName != "" {
args = append(args, p.ReleaseName)
}
args = append(args, path.Join(p.ChartHome, p.ChartName))
if p.ReleaseNamespace != "" {
args = append(args, "--namespace", p.ReleaseNamespace)
}
if p.Values != "" {
args = append(args, "--values", p.Values)
}
args = append(args, p.ExtraArgs...)
return args
}
func (p *HelmChartInflationGeneratorPlugin) getPullCommandArgs() []string {
args := []string{"pull", "--untar", "--untardir", p.ChartHome}
chartName := fmt.Sprintf("%s/%s", p.ChartRepoName, p.ChartName)
if p.ChartVersion != "" {
args = append(args, "--version", p.ChartVersion)
}
if p.ChartRepoURL != "" {
args = append(args, "--repo", p.ChartRepoURL)
chartName = p.ChartName
}
args = append(args, chartName)
return args
}
// checkLocalChart will return true if the chart does exist in
// local chart home.
func (p *HelmChartInflationGeneratorPlugin) checkLocalChart() bool {
path := path.Join(p.ChartHome, p.ChartName)
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
// checkHelmVersion will return an error if the helm version is not V3
func (p *HelmChartInflationGeneratorPlugin) checkHelmVersion() error {
stdout, err := p.runHelmCommand([]string{"version", "-c", "--short"})
if err != nil {
return err
}
r, err := regexp.Compile(`v\d+(\.\d+)+`)
if err != nil {
return err
}
v := string(r.Find(stdout))[1:]
majorVersion := strings.Split(v, ".")[0]
if majorVersion != "3" {
return fmt.Errorf("this plugin requires helm V3 but got v%s", v)
}
return nil
}
func NewHelmChartInflationGeneratorPlugin() resmap.GeneratorPlugin {
return &HelmChartInflationGeneratorPlugin{}
}

View File

@@ -31,14 +31,15 @@ func (p *ImageTagTransformerPlugin) Config(
func (p *ImageTagTransformerPlugin) Transform(m resmap.ResMap) error {
for _, r := range m.Resources() {
// If you're here because someone expected any field containing
// the string "containers" or "initContainers" to get an image
// update (not just spec/template/spec/containers[], etc.) then
// a code change is needed. See api/filters/imagetag/legacy
// for the start of an implementation that won't use an
// allowlist like FsSlice, and instead walks the object looking
// for fields named containers or initContainers.
err := filtersutil.ApplyToJSON(imagetag.Filter{
// traverse all fields at first
err := filtersutil.ApplyToJSON(imagetag.LegacyFilter{
ImageTag: p.ImageTag,
}, r)
if err != nil {
return err
}
// then use user specified field specs
err = filtersutil.ApplyToJSON(imagetag.Filter{
ImageTag: p.ImageTag,
FsSlice: p.FieldSpecs,
}, r)

View File

@@ -7,9 +7,7 @@ import (
"fmt"
"sigs.k8s.io/kustomize/api/filters/namespace"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/filtersutil"
"sigs.k8s.io/yaml"
@@ -33,7 +31,7 @@ func (p *NamespaceTransformerPlugin) Transform(m resmap.ResMap) error {
return nil
}
for _, r := range m.Resources() {
if len(r.Map()) == 0 {
if r.IsEmpty() {
// Don't mutate empty objects?
continue
}
@@ -53,74 +51,6 @@ func (p *NamespaceTransformerPlugin) Transform(m resmap.ResMap) error {
return nil
}
// Special casing metadata.namespace since
// all objects have it, even "ClusterKind" objects
// that don't exist in a namespace (the Namespace
// object itself doesn't live in a namespace).
func (p *NamespaceTransformerPlugin) applicableFieldSpecs(id resid.ResId) []types.FieldSpec {
var res []types.FieldSpec
for _, fs := range p.FieldSpecs {
if id.IsSelected(&fs.Gvk) &&
(fs.Path != types.MetadataNamespacePath ||
(fs.Path == types.MetadataNamespacePath && id.IsNamespaceableKind())) {
res = append(res, fs)
}
}
return res
}
func (p *NamespaceTransformerPlugin) changeNamespace(
_ *resource.Resource) func(in interface{}) (interface{}, error) {
return func(in interface{}) (interface{}, error) {
switch in.(type) {
case string:
// will happen when the metadata/namespace
// value is replaced
return p.Namespace, nil
case []interface{}:
l, _ := in.([]interface{})
for idx, item := range l {
switch item.(type) {
case map[string]interface{}:
// Will happen when mutating the subjects
// field of ClusterRoleBinding and RoleBinding
inMap, _ := item.(map[string]interface{})
if _, ok := inMap["name"]; !ok {
continue
}
name, ok := inMap["name"].(string)
if !ok {
continue
}
// The only case we need to force the namespace
// if for the "service account". "default" is
// kind of hardcoded here for right now.
if name != "default" {
continue
}
inMap["namespace"] = p.Namespace
l[idx] = inMap
default:
// nothing to do for right now
}
}
return in, nil
case map[string]interface{}:
// Will happen if the createField=true
// when the namespace is added to the
// object
inMap := in.(map[string]interface{})
if len(inMap) == 0 {
return p.Namespace, nil
} else {
return in, nil
}
default:
return in, nil
}
}
}
func NewNamespaceTransformerPlugin() resmap.TransformerPlugin {
return &NamespaceTransformerPlugin{}
}

View File

@@ -10,7 +10,6 @@ import (
"github.com/pkg/errors"
"sigs.k8s.io/kustomize/api/filters/patchjson6902"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/filtersutil"
@@ -20,9 +19,9 @@ import (
type PatchJson6902TransformerPlugin struct {
ldr ifc.Loader
decodedPatch jsonpatch.Patch
Target types.PatchTarget `json:"target,omitempty" yaml:"target,omitempty"`
Path string `json:"path,omitempty" yaml:"path,omitempty"`
JsonOp string `json:"jsonOp,omitempty" yaml:"jsonOp,omitempty"`
Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"`
Path string `json:"path,omitempty" yaml:"path,omitempty"`
JsonOp string `json:"jsonOp,omitempty" yaml:"jsonOp,omitempty"`
}
func (p *PatchJson6902TransformerPlugin) Config(
@@ -72,22 +71,22 @@ func (p *PatchJson6902TransformerPlugin) Config(
}
func (p *PatchJson6902TransformerPlugin) Transform(m resmap.ResMap) error {
id := resid.NewResIdWithNamespace(
resid.Gvk{
Group: p.Target.Group,
Version: p.Target.Version,
Kind: p.Target.Kind,
},
p.Target.Name,
p.Target.Namespace,
)
obj, err := m.GetById(id)
if p.Target == nil {
return fmt.Errorf("must specify a target for patch %s", p.JsonOp)
}
resources, err := m.Select(*p.Target)
if err != nil {
return err
}
return filtersutil.ApplyToJSON(patchjson6902.Filter{
Patch: p.JsonOp,
}, obj)
for _, res := range resources {
err = filtersutil.ApplyToJSON(patchjson6902.Filter{
Patch: p.JsonOp,
}, res)
if err != nil {
return err
}
}
return nil
}
func NewPatchJson6902TransformerPlugin() resmap.TransformerPlugin {

View File

@@ -5,14 +5,10 @@ package builtins
import (
"fmt"
"strings"
"github.com/pkg/errors"
"sigs.k8s.io/kustomize/api/filters/patchstrategicmerge"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/filtersutil"
"sigs.k8s.io/yaml"
)
@@ -35,6 +31,11 @@ func (p *PatchStrategicMergeTransformerPlugin) Config(
}
if len(p.Paths) != 0 {
for _, onePath := range p.Paths {
// The following oddly attempts to interpret a path string as an
// actual patch (instead of as a path to a file containing a patch).
// All tests pass if this code is commented out. This code should
// be deleted; the user should use the Patches field which
// exists for this purpose (inline patch declaration).
res, err := p.h.ResmapFactory().RF().SliceFromBytes([]byte(onePath))
if err == nil {
p.loadedPatches = append(p.loadedPatches, res...)
@@ -73,44 +74,10 @@ func (p *PatchStrategicMergeTransformerPlugin) Transform(m resmap.ResMap) error
if err != nil {
return err
}
patchCopy := patch.DeepCopy()
patchCopy.SetName(target.GetName())
patchCopy.SetNamespace(target.GetNamespace())
patchCopy.SetGvk(target.GetGvk())
node, err := filtersutil.GetRNode(patchCopy)
if err != nil {
if err = m.ApplySmPatch(
resource.MakeIdSet([]*resource.Resource{target}), patch); err != nil {
return err
}
err = filtersutil.ApplyToJSON(patchstrategicmerge.Filter{
Patch: node,
}, target)
if err != nil {
// Check for an error string from UnmarshalJSON that's indicative
// of an object that's missing basic KRM fields, and thus may have been
// entirely deleted (an acceptable outcome). This error handling should
// be deleted along with use of ResMap and apimachinery functions like
// UnmarshalJSON.
if !strings.Contains(err.Error(), "Object 'Kind' is missing") {
// Some unknown error, let it through.
return err
}
if len(target.Map()) != 0 {
return errors.Wrapf(
err, "with unexpectedly non-empty object map of size %d",
len(target.Map()))
}
// Fall through to handle deleted object.
}
if len(target.Map()) == 0 {
// This means all fields have been removed from the object.
// This can happen if a patch required deletion of the
// entire resource (not just a part of it). This means
// the overall resmap must shrink by one.
err = m.Remove(target.CurId())
if err != nil {
return err
}
}
}
return nil
}

View File

@@ -9,7 +9,6 @@ import (
jsonpatch "github.com/evanphx/json-patch"
"sigs.k8s.io/kustomize/api/filters/patchjson6902"
"sigs.k8s.io/kustomize/api/filters/patchstrategicmerge"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
@@ -40,7 +39,6 @@ func (p *PatchTransformerPlugin) Config(
return fmt.Errorf(
"patch and path can't be set at the same time\n%s", string(c))
}
if p.Path != "" {
loaded, loadErr := h.Loader().Load(p.Path)
if loadErr != nil {
@@ -87,36 +85,13 @@ func (p *PatchTransformerPlugin) transformStrategicMerge(m resmap.ResMap, patch
if err != nil {
return err
}
return p.applySMPatch(target, patch)
return target.ApplySmPatch(patch)
}
resources, err := m.Select(*p.Target)
selected, err := m.Select(*p.Target)
if err != nil {
return err
}
for _, res := range resources {
patchCopy := patch.DeepCopy()
patchCopy.SetName(res.GetName())
patchCopy.SetNamespace(res.GetNamespace())
patchCopy.SetGvk(res.GetGvk())
err := p.applySMPatch(res, patchCopy)
if err != nil {
return err
}
}
return nil
}
// applySMPatch applies the provided strategic merge patch to the
// given resource.
func (p *PatchTransformerPlugin) applySMPatch(resource, patch *resource.Resource) error {
node, err := filtersutil.GetRNode(patch)
if err != nil {
return err
}
return filtersutil.ApplyToJSON(patchstrategicmerge.Filter{
Patch: node,
}, resource)
return m.ApplySmPatch(resource.MakeIdSet(selected), patch)
}
// transformJson6902 applies the provided json6902 patch

View File

@@ -51,6 +51,9 @@ func (fltr Filter) filter(obj *yaml.RNode) error {
// found the field -- set its value
return fltr.SetValue(obj)
}
if obj.IsTaggedNull() {
return nil
}
switch obj.YNode().Kind {
case yaml.SequenceNode:
return fltr.seq(obj)
@@ -67,7 +70,7 @@ func (fltr Filter) field(obj *yaml.RNode) error {
// lookup the field matching the next path element
var lookupField yaml.Filter
var kind yaml.Kind
tag := "" // TODO: change to yaml.NodeTagEmpty
tag := yaml.NodeTagEmpty
switch {
case !fltr.FieldSpec.CreateIfNotPresent || fltr.CreateKind == 0 || isSeq:
// dont' create the field if we don't find it
@@ -95,9 +98,10 @@ func (fltr Filter) field(obj *yaml.RNode) error {
return errors.WrapPrefixf(err, "fieldName: %s", fieldName)
}
// if the value exists, but is null, then change it to the creation type
// if the value exists, but is null and kind is set,
// then change it to the creation type
// TODO: update yaml.LookupCreate to support this
if field.YNode().Tag == yaml.NodeTagNull {
if field.YNode().Tag == yaml.NodeTagNull && yaml.IsCreate(kind) {
field.YNode().Kind = kind
field.YNode().Tag = tag
}

View File

@@ -433,7 +433,6 @@ spec:
SetValue: filtersutil.SetScalar("bar"),
CreateKind: yaml.ScalarNode,
},
error: "obj '' at path 'spec/containers/image': expected sequence or mapping node",
},
{
name: "filedname with slash '/'",

View File

@@ -1,7 +1,9 @@
package nameref
import (
"encoding/json"
"fmt"
"strings"
"sigs.k8s.io/kustomize/api/filters/fieldspec"
"sigs.k8s.io/kustomize/api/filters/filtersutil"
@@ -9,6 +11,7 @@ import (
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
kyaml_filtersutil "sigs.k8s.io/kustomize/kyaml/filtersutil"
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
@@ -19,6 +22,7 @@ type Filter struct {
Referrer *resource.Resource
Target resid.Gvk
ReferralCandidates resmap.ResMap
isRoleRef bool
}
func (f Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
@@ -37,6 +41,9 @@ func (f Filter) set(node *yaml.RNode) error {
if yaml.IsMissingOrNull(node) {
return nil
}
if strings.HasSuffix(f.FieldSpec.Path, "roleRef/name") {
f.isRoleRef = true
}
switch node.YNode().Kind {
case yaml.ScalarNode:
return f.setScalar(node)
@@ -65,6 +72,7 @@ func (f Filter) setMapping(node *yaml.RNode) error {
f.Referrer,
f.Target,
f.ReferralCandidates,
f.isRoleRef,
)
}
@@ -75,6 +83,7 @@ func (f Filter) setScalar(node *yaml.RNode) error {
f.Target,
f.ReferralCandidates,
f.ReferralCandidates.Resources(),
f.isRoleRef,
)
if err != nil {
return err
@@ -86,14 +95,56 @@ func (f Filter) setScalar(node *yaml.RNode) error {
return nil
}
// getRoleRefGvk returns a Gvk in the roleRef field. Return error
// if the roleRef, roleRef/apiGroup or roleRef/kind is missing.
func getRoleRefGvk(res json.Marshaler) (*resid.Gvk, error) {
n, err := kyaml_filtersutil.GetRNode(res)
if err != nil {
return nil, err
}
roleRef, err := n.Pipe(yaml.Lookup("roleRef"))
if err != nil {
return nil, err
}
if roleRef.IsNil() {
return nil, fmt.Errorf("roleRef cannot be found in %s", n.MustString())
}
apiGroup, err := roleRef.Pipe(yaml.Lookup("apiGroup"))
if err != nil {
return nil, err
}
if apiGroup.IsNil() {
return nil, fmt.Errorf("apiGroup cannot be found in roleRef %s", roleRef.MustString())
}
kind, err := roleRef.Pipe(yaml.Lookup("kind"))
if err != nil {
return nil, err
}
if kind.IsNil() {
return nil, fmt.Errorf("kind cannot be found in roleRef %s", roleRef.MustString())
}
return &resid.Gvk{
Group: apiGroup.YNode().Value,
Kind: kind.YNode().Value,
}, nil
}
func filterReferralCandidates(
referrer *resource.Resource,
matches []*resource.Resource) []*resource.Resource {
matches []*resource.Resource,
target resid.Gvk,
) []*resource.Resource {
var ret []*resource.Resource
for _, m := range matches {
if referrer.PrefixesSuffixesEquals(m) {
ret = append(ret, m)
// If target kind is not ServiceAccount, we shouldn't consider condidates which
// doesn't have same namespace.
if target.Kind != "ServiceAccount" && m.GetNamespace() != referrer.GetNamespace() {
continue
}
if !referrer.PrefixesSuffixesEquals(m) {
continue
}
ret = append(ret, m)
}
return ret
}
@@ -109,16 +160,27 @@ func selectReferral(
referrer *resource.Resource,
target resid.Gvk,
referralCandidates resmap.ResMap,
referralCandidateSubset []*resource.Resource) (string, string, error) {
referralCandidateSubset []*resource.Resource,
isRoleRef bool) (string, string, error) {
var roleRefGvk *resid.Gvk
if isRoleRef {
var err error
roleRefGvk, err = getRoleRefGvk(referrer)
if err != nil {
return "", "", err
}
}
for _, res := range referralCandidateSubset {
id := res.OrgId()
if id.IsSelected(&target) && res.GetOriginalName() == oldName {
// If the we are processing a roleRef, the apiGroup and Kind in the
// roleRef are needed to be considered.
if (!isRoleRef || id.IsSelected(roleRefGvk)) &&
id.IsSelected(&target) && res.GetOriginalName() == oldName {
matches := referralCandidates.GetMatchingResourcesByOriginalId(id.Equals)
// If there's more than one match,
// filter the matches by prefix and suffix
if len(matches) > 1 {
filteredMatches := filterReferralCandidates(referrer, matches)
filteredMatches := filterReferralCandidates(referrer, matches, target)
if len(filteredMatches) > 1 {
return "", "", fmt.Errorf(
"multiple matches for %s:\n %v",
@@ -147,10 +209,11 @@ func getSimpleNameField(
referrer *resource.Resource,
target resid.Gvk,
referralCandidates resmap.ResMap,
referralCandidateSubset []*resource.Resource) (string, error) {
referralCandidateSubset []*resource.Resource,
isRoleRef bool) (string, error) {
newName, _, err := selectReferral(oldName, referrer, target,
referralCandidates, referralCandidateSubset)
referralCandidates, referralCandidateSubset, isRoleRef)
return newName, err
}
@@ -169,7 +232,8 @@ func setNameAndNs(
in *yaml.RNode,
referrer *resource.Resource,
target resid.Gvk,
referralCandidates resmap.ResMap) error {
referralCandidates resmap.ResMap,
isRoleRef bool) error {
if in.YNode().Kind != yaml.MappingNode {
return fmt.Errorf("expect a mapping node")
@@ -205,7 +269,7 @@ func setNameAndNs(
oldName := nameNode.YNode().Value
newname, newnamespace, err := selectReferral(oldName, referrer, target,
referralCandidates, subset)
referralCandidates, subset, isRoleRef)
if err != nil {
return err
}

View File

@@ -5,10 +5,9 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
filtertest_test "sigs.k8s.io/kustomize/api/testutils/filtertest"
"sigs.k8s.io/kustomize/api/types"
)
@@ -168,6 +167,44 @@ metadata:
map:
name: newName
namespace: oldNs
`,
filter: Filter{
FieldSpec: types.FieldSpec{Path: "map"},
Target: resid.Gvk{
Group: "apps",
Version: "v1",
Kind: "Secret",
},
},
},
"null value": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: dep
map:
name: null
`,
candidates: `
apiVersion: apps/v1
kind: Secret
metadata:
name: newName
---
apiVersion: apps/v1
kind: NotSecret
metadata:
name: newName2
`,
originalNames: []string{"oldName", ""},
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: dep
map:
name: null
`,
filter: Filter{
FieldSpec: types.FieldSpec{Path: "map"},
@@ -182,7 +219,7 @@ map:
for tn, tc := range testCases {
t.Run(tn, func(t *testing.T) {
factory := resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())
factory := provider.NewDefaultDepProvider().GetResourceFactory()
referrer, err := factory.FromBytes([]byte(tc.input))
if err != nil {
t.Fatal(err)
@@ -217,27 +254,6 @@ func TestNamerefFilterUnhappy(t *testing.T) {
filter Filter
originalNames []string
}{
"invalid node type": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: dep
ref:
name: null
`,
candidates: "",
originalNames: []string{},
expected: "obj '' at path 'ref/name': node is expected to be either a string or a slice of string or a map of string",
filter: Filter{
FieldSpec: types.FieldSpec{Path: "ref/name"},
Target: resid.Gvk{
Group: "apps",
Version: "v1",
Kind: "Secret",
},
},
},
"multiple match": {
input: `
apiVersion: apps/v1
@@ -304,7 +320,7 @@ metadata:
for tn, tc := range testCases {
t.Run(tn, func(t *testing.T) {
factory := resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())
factory := provider.NewDefaultDepProvider().GetResourceFactory()
referrer, err := factory.FromBytes([]byte(tc.input))
if err != nil {
t.Fatal(err)
@@ -715,7 +731,7 @@ ref:
for tn, tc := range testCases {
t.Run(tn, func(t *testing.T) {
factory := resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())
factory := provider.NewDefaultDepProvider().GetResourceFactory()
referrer, err := factory.FromBytes([]byte(tc.input))
if err != nil {
t.Fatal(err)

View File

@@ -69,7 +69,7 @@ func (ns Filter) hacks(obj *yaml.RNode) error {
// metaNamespaceHack is a hack for implementing the namespace transform
// for the metadata.namespace field on namespace scoped resources.
// namespace scoped resources are determined by NOT being present
// in a blacklist of cluster-scoped resource types (by apiVersion and kind).
// in a hard-coded list of cluster-scoped resource types (by apiVersion and kind).
//
// This hack should be updated to allow individual resources to specify
// if they are cluster scoped through either an annotation on the resources,

View File

@@ -194,47 +194,47 @@ metadata:
{
name: "update-clusterrolebinding",
input: `
apiVersion: example.com/v1
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
subjects:
- name: default
---
apiVersion: example.com/v1
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
subjects:
- name: default
namespace: foo
---
apiVersion: example.com/v1
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
subjects:
- name: something
---
apiVersion: example.com/v1
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
subjects:
- name: something
namespace: foo
`,
expected: `
apiVersion: example.com/v1
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
subjects:
- name: default
namespace: bar
---
apiVersion: example.com/v1
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
subjects:
- name: default
namespace: bar
---
apiVersion: example.com/v1
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
subjects:
- name: something
---
apiVersion: example.com/v1
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
subjects:
- name: something

View File

@@ -18,7 +18,12 @@ var _ kio.Filter = Filter{}
func (pf Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
var result []*yaml.RNode
for i := range nodes {
r, err := merge2.Merge(pf.Patch, nodes[i])
r, err := merge2.Merge(
pf.Patch, nodes[i],
yaml.MergeOptions{
ListIncreaseDirection: yaml.MergeOptionsListPrepend,
},
)
if err != nil {
return nil, err
}

View File

@@ -15,6 +15,78 @@ func TestFilter(t *testing.T) {
patch *yaml.RNode
expected string
}{
"nullMapEntry1": {
input: `
apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
B:
C: Z
`,
patch: yaml.MustParse(`
apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
C: Z
D: W
baz:
hello: world
`),
expected: `
apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
C: Z
D: W
baz:
hello: world
`,
},
"nullMapEntry2": {
input: `
apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
C: Z
D: W
baz:
hello: world
`,
patch: yaml.MustParse(`
apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
B:
C: Z
`),
expected: `
apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
C: Z
D: W
baz:
hello: world
`,
},
"simple patch": {
input: `
apiVersion: apps/v1
@@ -67,10 +139,10 @@ spec:
template:
spec:
containers:
- name: foo0
- name: foo1
- name: foo2
- name: foo3
- name: foo0
`,
},
"volumes patch": {
@@ -107,10 +179,10 @@ spec:
template:
spec:
volumes:
- name: foo0
- name: foo1
- name: foo2
- name: foo3
- name: foo0
`,
},
"nested patch": {
@@ -142,6 +214,441 @@ spec:
- name: nginx
args:
- def
`,
},
"remove mapping - directive": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test
image: test
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test
image: test
$patch: delete
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers: []
`,
},
"replace mapping - directive": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test
image: test
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
$patch: replace
containers:
- name: new
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: new
`,
},
"merge mapping - directive": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test
image: test
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test
image: test1
$patch: merge
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test
image: test1
`,
},
"remove list - directive": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test
image: test
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- whatever
- $patch: delete
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec: {}
`,
},
"replace list - directive": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test
image: test
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: replace
image: replace
- $patch: replace
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: replace
image: replace
`,
},
"merge list - directive": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test
image: test
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test2
image: test2
- $patch: merge
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: myDeploy
spec:
template:
spec:
containers:
- name: test2
image: test2
- name: test
image: test
`,
},
"list map keys - add a port, no names": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
protocol: TCP
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
protocol: UDP
- containerPort: 80
protocol: UDP
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
protocol: UDP
- containerPort: 80
protocol: UDP
- containerPort: 8080
protocol: TCP
`,
},
"list map keys - add name to port": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
protocol: UDP
- containerPort: 8080
protocol: TCP
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
protocol: UDP
name: UDP-name-patch
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
protocol: UDP
name: UDP-name-patch
- containerPort: 8080
protocol: TCP
`,
},
"list map keys - replace port name": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
protocol: UDP
name: UDP-name-original
- containerPort: 8080
protocol: TCP
name: TCP-name-original
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
protocol: UDP
name: UDP-name-patch
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
protocol: UDP
name: UDP-name-patch
- containerPort: 8080
protocol: TCP
name: TCP-name-original
`,
},
"list map keys - add a port, no protocol": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 8080
`,
patch: yaml.MustParse(`
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 80
`),
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
template:
spec:
containers:
- image: test-image
name: test-deployment
ports:
- containerPort: 80
- containerPort: 8080
`,
},
}

View File

@@ -188,6 +188,26 @@ data:
FieldSpec: types.FieldSpec{Path: "data/slice2"},
},
},
"null value": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: dep
data:
FOO: null`,
expected: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: dep
data:
FOO: null`,
filter: Filter{
MappingFunc: expansion2.MappingFuncFor(replacementCounts, map[string]interface{}{}),
FieldSpec: types.FieldSpec{Path: "data/FOO"},
},
},
}
for tn, tc := range testCases {
@@ -260,20 +280,6 @@ data:
FieldSpec: types.FieldSpec{Path: "data"},
},
},
"null input": {
input: `
apiVersion: apps/v1
kind: Deployment
metadata:
name: dep
data:
FOO: null`,
expectedError: "obj '' at path 'data/FOO': invalid type encountered 0",
filter: Filter{
MappingFunc: expansion2.MappingFuncFor(replacementCounts, map[string]interface{}{}),
FieldSpec: types.FieldSpec{Path: "data/FOO"},
},
},
}
for tn, tc := range testCases {

View File

@@ -1,22 +1,27 @@
module sigs.k8s.io/kustomize/api
go 1.14
go 1.15
require (
github.com/evanphx/json-patch v4.5.0+incompatible
github.com/go-errors/errors v1.0.1
github.com/go-openapi/spec v0.19.5
github.com/golangci/golangci-lint v1.21.0
github.com/google/go-cmp v0.3.0
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
github.com/hashicorp/go-multierror v1.1.0
github.com/pkg/errors v0.8.1
github.com/stretchr/testify v1.4.0
github.com/yujunz/go-getter v1.4.1-lite
golang.org/x/tools v0.0.0-20191010075000-0337d82405ff
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e
gopkg.in/yaml.v2 v2.3.0
gopkg.in/yaml.v3 v3.0.0-20200121175148-a6ecf24a6d71
k8s.io/api v0.17.0
k8s.io/apimachinery v0.17.0
k8s.io/client-go v0.17.0
k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a
sigs.k8s.io/kustomize/kyaml v0.7.1
sigs.k8s.io/kustomize/kyaml v0.9.4
sigs.k8s.io/yaml v1.2.0
)
replace sigs.k8s.io/kustomize/kyaml v0.9.4 => ../kyaml

View File

@@ -158,6 +158,7 @@ github.com/go-toolsmith/strparse v1.0.0 h1:Vcw78DnpCAKlM20kSbAyO4mPfJn/lyYA4BJUD
github.com/go-toolsmith/strparse v1.0.0/go.mod h1:YI2nUKP9YGZnL/L1/DLFBfixrcjslWct4wyljWhSRy8=
github.com/go-toolsmith/typep v1.0.0 h1:zKymWyA1TRYvqYrYDrfEMZULyrhcnGY3x7LDKU2XQaA=
github.com/go-toolsmith/typep v1.0.0/go.mod h1:JSQCQMUPdRlMZFswiq3TGpNp1GMktqkR2Ns5AIQkATU=
github.com/gobuffalo/here v0.6.0/go.mod h1:wAG085dHOYqUpf+Ap+WOdrPTp5IYcDAs/x7PLa8Y5fM=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/gofrs/flock v0.0.0-20190320160742-5135e617513b h1:ekuhfTjngPhisSjOJ0QWKpPQE8/rbknHaes6WVJj5Hw=
@@ -166,6 +167,7 @@ github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7a
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d h1:3PaI8p3seN09VjbTYC/QWlUZdZ1qS1zGjy7LH2Wt07I=
github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
@@ -225,6 +227,7 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+
github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d h1:7XGaL1e6bYS1yIonGp9761ExpPPV1ui0SAC59Yube9k=
github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY=
github.com/gophercloud/gophercloud v0.1.0/go.mod h1:vxM41WHh5uqHVBMZHzuwNOHh8XEoIEcSTewFxm1c5g8=
github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gostaticanalysis/analysisutil v0.0.0-20190318220348-4088753ea4d3 h1:JVnpOZS+qxli+rgVl98ILOXVNbW+kb5wcxeGx8ShUIw=
github.com/gostaticanalysis/analysisutil v0.0.0-20190318220348-4088753ea4d3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE=
@@ -232,8 +235,12 @@ github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:Fecb
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig=
github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-multierror v1.1.0 h1:B9UzwGQJehnUY1yNrnwREHc3fGbC2xefo8g4TbElacI=
github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo=
github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I=
github.com/hashicorp/go-version v1.1.0 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0=
@@ -283,6 +290,7 @@ github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.7.0 h1:aizVhC/NAAcKWb+5QsU1iNOZb4Yws5UO2I+aIprQITM=
github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs=
github.com/markbates/pkger v0.17.1/go.mod h1:0JoVlrol20BSywW79rN3kdFFsE5xYM+rSCQDXbLhiuI=
github.com/matoous/godox v0.0.0-20190911065817-5d6d842e92eb h1:RHba4YImhrUVQDHUCe2BNSOz4tVy2yGyXhvYDvxGgeE=
github.com/matoous/godox v0.0.0-20190911065817-5d6d842e92eb/go.mod h1:1BELzlh859Sh1c6+90blK8lbYy0kwQf1bYlBhBysy1s=
github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
@@ -307,6 +315,8 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0=
github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4=
github.com/mozilla/tls-observatory v0.0.0-20190404164649-a3c1b6cfecfd/go.mod h1:SrKMQvPiws7F7iqYp8/TX+IhxCYhzr6N/1yb8cwHsGk=
github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
@@ -359,6 +369,7 @@ github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e h1:MZM7FHLqUHYI0Y/mQAt
github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=
github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041 h1:llrF3Fs4018ePo4+G/HV/uQUqEI1HMDjCeOf2V6puPc=
github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
@@ -526,6 +537,8 @@ golang.org/x/tools v0.0.0-20190910044552-dd2b5c81c578/go.mod h1:b+2E5dAYhXwXZwtn
golang.org/x/tools v0.0.0-20190930201159-7c411dea38b0/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191010075000-0337d82405ff h1:XdBG6es/oFDr1HwaxkxgVve7NB281QhxgK/i4voubFs=
golang.org/x/tools v0.0.0-20191010075000-0337d82405ff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e h1:aZzprAO9/8oim3qStq3wc1Xuxx4QmAGriC4VU4ojemQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
@@ -553,6 +566,7 @@ gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bl
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
@@ -584,8 +598,6 @@ mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b h1:DxJ5nJdkhDlLok9K6qO+5290kphD
mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b/go.mod h1:2odslEg/xrtNQqCYg2/jCoyKnw3vv5biOc3JnIcYfL4=
mvdan.cc/unparam v0.0.0-20190720180237-d51796306d8f h1:Cq7MalBHYACRd6EesksG1Q8EoIAKOsiZviGKbOLIej4=
mvdan.cc/unparam v0.0.0-20190720180237-d51796306d8f/go.mod h1:4G1h5nDURzA3bwVMZIVpwbkw+04kSxk3rAtzlimaUJw=
sigs.k8s.io/kustomize/kyaml v0.7.1 h1:Ih6SJPvfKYfZaIFWUa2YAyg/0ZSTpA3LFjR/hv7+8ao=
sigs.k8s.io/kustomize/kyaml v0.7.1/go.mod h1:ne3F9JPhW2wrVaLslxBsEe6MQJQ9YK5rUutrdhBWXwI=
sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI=
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
sigs.k8s.io/yaml v1.2.0 h1:kr/MCeFWJWTwyaHoR9c8EjH9OumOmoF9YGiZd7lFm/Q=

View File

@@ -8,17 +8,14 @@ import (
"testing"
"sigs.k8s.io/kustomize/api/internal/plugins/builtinconfig"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
resmaptest_test "sigs.k8s.io/kustomize/api/testutils/resmaptest"
)
func TestNameReferenceHappyRun(t *testing.T) {
rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl())
m := resmaptest_test.NewRmBuilder(t, rf).AddWithName(
m := resmaptest_test.NewRmBuilderDefault(t).AddWithName(
"cm1",
map[string]interface{}{
"apiVersion": "v1",
@@ -261,7 +258,8 @@ func TestNameReferenceHappyRun(t *testing.T) {
},
}).ResMap()
expected := resmaptest_test.NewSeededRmBuilder(t, rf, m.ShallowCopy()).ReplaceResource(
expected := resmaptest_test.NewSeededRmBuilderDefault(
t, m.ShallowCopy()).ReplaceResource(
map[string]interface{}{
"group": "apps",
"apiVersion": "v1",
@@ -475,14 +473,12 @@ func TestNameReferenceHappyRun(t *testing.T) {
}
func TestNameReferenceUnhappyRun(t *testing.T) {
rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl())
tests := []struct {
resMap resmap.ResMap
expectedErr string
}{
{
resMap: resmaptest_test.NewRmBuilder(t, rf).Add(
resMap: resmaptest_test.NewRmBuilderDefault(t).Add(
map[string]interface{}{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRole",
@@ -502,7 +498,7 @@ func TestNameReferenceUnhappyRun(t *testing.T) {
}).ResMap(),
expectedErr: "is expected to be"},
{
resMap: resmaptest_test.NewRmBuilder(t, rf).Add(
resMap: resmaptest_test.NewRmBuilderDefault(t).Add(
map[string]interface{}{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRole",
@@ -538,8 +534,7 @@ func TestNameReferenceUnhappyRun(t *testing.T) {
}
func TestNameReferencePersistentVolumeHappyRun(t *testing.T) {
rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl())
rf := provider.NewDefaultDepProvider().GetResourceFactory()
v1 := rf.FromMapWithName(
"volume1",
@@ -664,9 +659,7 @@ const (
// object with the same original names (uniquename) in different namespaces
// and with different current Id.
func TestNameReferenceNamespace(t *testing.T) {
rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl())
m := resmaptest_test.NewRmBuilder(t, rf).
m := resmaptest_test.NewRmBuilderDefault(t).
// Add ConfigMap with the same org name in noNs, "ns1" and "ns2" namespaces
AddWithName(orgname, map[string]interface{}{
"apiVersion": "v1",
@@ -715,7 +708,7 @@ func TestNameReferenceNamespace(t *testing.T) {
AddWithNsAndName(ns1, orgname, deploymentMap(ns1, prefixedname, orgname, orgname)).
AddWithNsAndName(ns2, orgname, deploymentMap(ns2, suffixedname, orgname, orgname)).ResMap()
expected := resmaptest_test.NewSeededRmBuilder(t, rf, m.ShallowCopy()).
expected := resmaptest_test.NewSeededRmBuilderDefault(t, m.ShallowCopy()).
ReplaceResource(deploymentMap(defaultNs, modifiedname, modifiedname, modifiedname)).
ReplaceResource(deploymentMap(ns1, prefixedname, prefixedname, prefixedname)).
ReplaceResource(deploymentMap(ns2, suffixedname, suffixedname, suffixedname)).ResMap()
@@ -735,9 +728,7 @@ func TestNameReferenceNamespace(t *testing.T) {
// object with the same original names (uniquename) in different namespaces
// and with different current Id.
func TestNameReferenceClusterWide(t *testing.T) {
rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl())
m := resmaptest_test.NewRmBuilder(t, rf).
m := resmaptest_test.NewRmBuilderDefault(t).
// Add ServiceAccount with the same org name in noNs, "ns1" and "ns2" namespaces
AddWithName(orgname, map[string]interface{}{
"apiVersion": "v1",
@@ -789,9 +780,9 @@ func TestNameReferenceClusterWide(t *testing.T) {
"name": modifiedname,
},
"roleRef": map[string]interface{}{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRole",
"name": orgname,
"apiGroup": "rbac.authorization.k8s.io",
"kind": "ClusterRole",
"name": orgname,
},
"subjects": []interface{}{
map[string]interface{}{
@@ -816,7 +807,7 @@ func TestNameReferenceClusterWide(t *testing.T) {
},
}}).ResMap()
expected := resmaptest_test.NewSeededRmBuilder(t, rf, m.ShallowCopy()).
expected := resmaptest_test.NewSeededRmBuilderDefault(t, m.ShallowCopy()).
ReplaceResource(
map[string]interface{}{
"apiVersion": "rbac.authorization.k8s.io/v1",
@@ -845,9 +836,9 @@ func TestNameReferenceClusterWide(t *testing.T) {
"name": modifiedname,
},
"roleRef": map[string]interface{}{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRole",
"name": modifiedname,
"apiGroup": "rbac.authorization.k8s.io",
"kind": "ClusterRole",
"name": modifiedname,
},
// The following tests required a change in
// getNameFunc implementation in order to leverage
@@ -898,9 +889,7 @@ func TestNameReferenceClusterWide(t *testing.T) {
// object with the same original names (uniquename) in different namespaces
// and with different current Id.
func TestNameReferenceNamespaceTransformation(t *testing.T) {
rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl())
m := resmaptest_test.NewRmBuilder(t, rf).
m := resmaptest_test.NewRmBuilderDefault(t).
AddWithNsAndName(ns4, orgname, map[string]interface{}{
"apiVersion": "v1",
"kind": "Secret",
@@ -937,9 +926,9 @@ func TestNameReferenceNamespaceTransformation(t *testing.T) {
"name": modifiedname,
},
"roleRef": map[string]interface{}{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRole",
"name": orgname,
"apiGroup": "rbac.authorization.k8s.io",
"kind": "ClusterRole",
"name": orgname,
},
"subjects": []interface{}{
map[string]interface{}{
@@ -964,7 +953,7 @@ func TestNameReferenceNamespaceTransformation(t *testing.T) {
},
}}).ResMap()
expected := resmaptest_test.NewSeededRmBuilder(t, rf, m.ShallowCopy()).
expected := resmaptest_test.NewSeededRmBuilderDefault(t, m.ShallowCopy()).
ReplaceResource(
map[string]interface{}{
"apiVersion": "rbac.authorization.k8s.io/v1",
@@ -973,9 +962,9 @@ func TestNameReferenceNamespaceTransformation(t *testing.T) {
"name": modifiedname,
},
"roleRef": map[string]interface{}{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRole",
"name": modifiedname,
"apiGroup": "rbac.authorization.k8s.io",
"kind": "ClusterRole",
"name": modifiedname,
},
// The following tests required a change in
// getNameFunc implementation in order to leverage
@@ -1026,9 +1015,7 @@ func TestNameReferenceNamespaceTransformation(t *testing.T) {
// It validates the change done is IsSameFuzzyNamespace which
// uses the IsNsEquals method instead of the simple == operator.
func TestNameReferenceCandidateSelection(t *testing.T) {
rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl())
m := resmaptest_test.NewRmBuilder(t, rf).
m := resmaptest_test.NewRmBuilderDefault(t).
AddWithName("cm1", map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
@@ -1045,7 +1032,7 @@ func TestNameReferenceCandidateSelection(t *testing.T) {
AddWithName("deploy1", deploymentMap("", "p1-deploy1", "cm1", "secret1")).
ResMap()
expected := resmaptest_test.NewSeededRmBuilder(t, rf, m.ShallowCopy()).
expected := resmaptest_test.NewSeededRmBuilderDefault(t, m.ShallowCopy()).
ReplaceResource(deploymentMap("", "p1-deploy1", "p1-cm1-hash", "p1-secret1-hash")).
ResMap()

View File

@@ -7,10 +7,8 @@ import (
"reflect"
"testing"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
resmaptest_test "sigs.k8s.io/kustomize/api/testutils/resmaptest"
"sigs.k8s.io/kustomize/api/types"
)
@@ -46,8 +44,7 @@ func TestRefVarTransformer(t *testing.T) {
{Gvk: resid.Gvk{Version: "v1", Kind: "ConfigMap"}, Path: "data/interface"},
{Gvk: resid.Gvk{Version: "v1", Kind: "ConfigMap"}, Path: "data/num"},
},
res: resmaptest_test.NewRmBuilder(
t, resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())).
res: resmaptest_test.NewRmBuilderDefault(t).
Add(map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
@@ -77,8 +74,7 @@ func TestRefVarTransformer(t *testing.T) {
}}).ResMap(),
},
expected: expected{
res: resmaptest_test.NewRmBuilder(
t, resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())).
res: resmaptest_test.NewRmBuilderDefault(t).
Add(map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
@@ -116,8 +112,7 @@ func TestRefVarTransformer(t *testing.T) {
fs: []types.FieldSpec{
{Gvk: resid.Gvk{Version: "v1", Kind: "ConfigMap"}, Path: "data/slice"},
},
res: resmaptest_test.NewRmBuilder(
t, resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())).
res: resmaptest_test.NewRmBuilderDefault(t).
Add(map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
@@ -132,14 +127,25 @@ func TestRefVarTransformer(t *testing.T) {
' at path 'data/slice': invalid value type expect a string`,
},
{
description: "var replacement panic in nil",
description: "var replacement in nil",
given: given{
varMap: map[string]interface{}{},
fs: []types.FieldSpec{
{Gvk: resid.Gvk{Version: "v1", Kind: "ConfigMap"}, Path: "data/nil"},
},
res: resmaptest_test.NewRmBuilder(
t, resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())).
res: resmaptest_test.NewRmBuilderDefault(t).
Add(map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "cm1",
},
"data": map[string]interface{}{
"nil": nil, // noticeably *not* a []string
}}).ResMap(),
},
expected: expected{
res: resmaptest_test.NewRmBuilderDefault(t).
Add(map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
@@ -150,7 +156,6 @@ func TestRefVarTransformer(t *testing.T) {
"nil": nil, // noticeably *not* a []string
}}).ResMap(),
},
errMessage: `obj '' at path 'data/nil': invalid type encountered 0`,
},
}

View File

@@ -12,7 +12,7 @@ import (
. "sigs.k8s.io/kustomize/api/internal/accumulator"
"sigs.k8s.io/kustomize/api/internal/plugins/builtinconfig"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
@@ -20,16 +20,14 @@ import (
"sigs.k8s.io/kustomize/api/types"
)
func makeResAccumulator(t *testing.T) (*ResAccumulator, *resource.Factory) {
func makeResAccumulator(t *testing.T) *ResAccumulator {
ra := MakeEmptyAccumulator()
err := ra.MergeConfig(builtinconfig.MakeDefaultConfig())
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
rf := resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl())
err = ra.AppendAll(
resmaptest_test.NewRmBuilder(t, rf).
resmaptest_test.NewRmBuilderDefault(t).
Add(map[string]interface{}{
"apiVersion": "apps/v1",
"kind": "Deployment",
@@ -66,11 +64,11 @@ func makeResAccumulator(t *testing.T) (*ResAccumulator, *resource.Factory) {
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
return ra, rf
return ra
}
func TestResolveVarsHappy(t *testing.T) {
ra, _ := makeResAccumulator(t)
ra := makeResAccumulator(t)
err := ra.MergeVars([]types.Var{
{
Name: "SERVICE_ONE",
@@ -99,7 +97,7 @@ func TestResolveVarsHappy(t *testing.T) {
}
func TestResolveVarsOneUnused(t *testing.T) {
ra, _ := makeResAccumulator(t)
ra := makeResAccumulator(t)
err := ra.MergeVars([]types.Var{
{
Name: "SERVICE_ONE",
@@ -140,11 +138,10 @@ func expectLog(t *testing.T, log bytes.Buffer, expect string) {
}
func TestResolveVarsVarNeedsDisambiguation(t *testing.T) {
ra, rf := makeResAccumulator(t)
ra := makeResAccumulator(t)
rm0 := resmap.New()
err := rm0.Append(
rf.FromMap(
provider.NewDefaultDepProvider().GetResourceFactory().FromMap(
map[string]interface{}{
"apiVersion": "v1",
"kind": "Service",
@@ -213,8 +210,7 @@ func makeVarToNamepaceAndPath(
}
func TestResolveVarConflicts(t *testing.T) {
rf := resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())
rf := provider.NewDefaultDepProvider().GetResourceFactory()
// create configmaps in foo and bar namespaces with `data.provider` values.
fooAws := makeNamespacedConfigMapWithDataProviderValue("foo", "aws")
barAws := makeNamespacedConfigMapWithDataProviderValue("bar", "aws")
@@ -261,7 +257,7 @@ func TestResolveVarConflicts(t *testing.T) {
}
func TestResolveVarsGoodResIdBadField(t *testing.T) {
ra, _ := makeResAccumulator(t)
ra := makeResAccumulator(t)
err := ra.MergeVars([]types.Var{
{
Name: "SERVICE_ONE",
@@ -286,7 +282,7 @@ func TestResolveVarsGoodResIdBadField(t *testing.T) {
}
func TestResolveVarsUnmappableVar(t *testing.T) {
ra, _ := makeResAccumulator(t)
ra := makeResAccumulator(t)
err := ra.MergeVars([]types.Var{
{
Name: "SERVICE_THREE",
@@ -310,7 +306,7 @@ func TestResolveVarsUnmappableVar(t *testing.T) {
}
func TestResolveVarsWithNoambiguation(t *testing.T) {
ra1, rf := makeResAccumulator(t)
ra1 := makeResAccumulator(t)
err := ra1.MergeVars([]types.Var{
{
Name: "SERVICE_ONE",
@@ -327,7 +323,7 @@ func TestResolveVarsWithNoambiguation(t *testing.T) {
// Create another accumulator having a resource with different prefix
ra2 := MakeEmptyAccumulator()
m := resmaptest_test.NewRmBuilder(t, rf).
m := resmaptest_test.NewRmBuilderDefault(t).
Add(map[string]interface{}{
"apiVersion": "apps/v1",
"kind": "Deployment",

View File

@@ -0,0 +1,23 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package conflict
import (
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resource"
)
type cdFactory struct{}
var _ resource.ConflictDetectorFactory = &cdFactory{}
// NewFactory returns a new conflict detector factory.
func NewFactory() resource.ConflictDetectorFactory {
return &cdFactory{}
}
// New returns an instance of smPatchMergeOnlyDetector.
func (c cdFactory) New(_ resid.Gvk) (resource.ConflictDetector, error) {
return &smPatchMergeOnlyDetector{}, nil
}

View File

@@ -0,0 +1,28 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package conflict
import (
"sigs.k8s.io/kustomize/api/resource"
)
// smPatchMergeOnlyDetector ignores conflicts,
// but does real strategic merge patching.
// This is part of an effort to eliminate dependence on
// apimachinery package to allow kustomize integration
// into kubectl (#2506 and #1500)
type smPatchMergeOnlyDetector struct{}
var _ resource.ConflictDetector = &smPatchMergeOnlyDetector{}
func (c *smPatchMergeOnlyDetector) HasConflict(
_, _ *resource.Resource) (bool, error) {
return false, nil
}
func (c *smPatchMergeOnlyDetector) MergePatches(
r, patch *resource.Resource) (*resource.Resource, error) {
err := r.ApplySmPatch(patch)
return r, err
}

View File

@@ -217,7 +217,7 @@ overview of each component with the following sections going into more details.
The overall structure is outlined in the following figure:
![overview](
https://sigs.k8s.io/kustomize/internal/tools/pictures/sys_arch.png)
https://github.com/kubernetes-sigs/kustomize/blob/master/api/internal/crawl/pictures/token_config.png)
#### Crawler
The leftmost component consists of a crawler with an http cache of GitHub

View File

@@ -7,14 +7,13 @@ import (
"sort"
"strings"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/yaml"
)
var fileReader = kunstruct.NewKunstructuredFactoryImpl()
// This document is meant to be used at the elasticsearch document type.
// Fields are serialized as-is to elasticsearch, where indices are built
// to facilitate text search queries. Identifiers, Values, FilePath,
@@ -42,6 +41,7 @@ type KustomizationDocument struct {
Kinds []string `json:"kinds,omitempty"`
Identifiers []string `json:"identifiers,omitempty"`
Values []string `json:"values,omitempty"`
resFactory *resource.Factory
}
type set map[string]struct{}
@@ -52,6 +52,7 @@ func (doc *KustomizationDocument) Copy() *KustomizationDocument {
Kinds: doc.Kinds,
Identifiers: doc.Identifiers,
Values: doc.Values,
resFactory: provider.NewDefaultDepProvider().GetResourceFactory(),
}
}
@@ -150,7 +151,7 @@ func (doc *KustomizationDocument) readBytes() ([]map[string]interface{}, error)
}
configs := make([]map[string]interface{}, 0)
ks, err := fileReader.SliceFromBytes(data)
ks, err := doc.resFactory.SliceFromBytes(data)
if err != nil {
return nil, fmt.Errorf("unable to parse resource: %v", err)
}

View File

@@ -1,6 +1,6 @@
module sigs.k8s.io/kustomize/api/internal/crawl
go 1.14
go 1.15
require (
github.com/elastic/go-elasticsearch/v6 v6.8.5

View File

@@ -206,8 +206,10 @@ github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:Fecb
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig=
github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo=
github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I=
github.com/hashicorp/go-version v1.1.0 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0=
@@ -271,6 +273,8 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0=
github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4=
github.com/mozilla/tls-observatory v0.0.0-20190404164649-a3c1b6cfecfd/go.mod h1:SrKMQvPiws7F7iqYp8/TX+IhxCYhzr6N/1yb8cwHsGk=
github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
@@ -313,6 +317,7 @@ github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/securego/gosec v0.0.0-20191002120514-e680875ea14d/go.mod h1:w5+eXa0mYznDkHaMCXA4XYffjlH+cy1oyKbfzJXa2Do=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/shirou/gopsutil v0.0.0-20190901111213-e4ec7b275ada/go.mod h1:WWnYX4lzhCH5h/3YBfyVA3VbLYjlMZZAQcW9ojMexNc=
github.com/shirou/w32 v0.0.0-20160930032740-bb4de0191aa4/go.mod h1:qsXQc7+bwAM3Q1u/4XEfrquwF8Lw7D7y5cD8CuHnfIc=
@@ -470,6 +475,7 @@ golang.org/x/tools v0.0.0-20190719005602-e377ae9d6386/go.mod h1:jcCCGcm9btYwXyDq
golang.org/x/tools v0.0.0-20190910044552-dd2b5c81c578/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190930201159-7c411dea38b0/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191010075000-0337d82405ff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
@@ -524,8 +530,8 @@ k8s.io/utils v0.0.0-20191114184206-e782cd3c129f/go.mod h1:sZAwmy6armz5eXlNoLmJcl
mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed/go.mod h1:Xkxe497xwlCKkIaQYRfC7CSLworTXY9RMqwhhCm+8Nc=
mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b/go.mod h1:2odslEg/xrtNQqCYg2/jCoyKnw3vv5biOc3JnIcYfL4=
mvdan.cc/unparam v0.0.0-20190720180237-d51796306d8f/go.mod h1:4G1h5nDURzA3bwVMZIVpwbkw+04kSxk3rAtzlimaUJw=
sigs.k8s.io/kustomize/kyaml v0.7.1 h1:Ih6SJPvfKYfZaIFWUa2YAyg/0ZSTpA3LFjR/hv7+8ao=
sigs.k8s.io/kustomize/kyaml v0.7.1/go.mod h1:ne3F9JPhW2wrVaLslxBsEe6MQJQ9YK5rUutrdhBWXwI=
sigs.k8s.io/kustomize/kyaml v0.9.4 h1:DDuzZtjIzFqp2IPy4DTyCI69Cl3bDgcJODjI6sjF9NY=
sigs.k8s.io/kustomize/kyaml v0.9.4/go.mod h1:UTm64bSWVdBUA8EQoYCxVOaBQxUdIOr5LKWxA4GNbkw=
sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI=
sigs.k8s.io/yaml v1.1.0 h1:4A07+ZFc2wgJwo8YNlQpr1rVlgUDlxXHhPJciaPY5gs=
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=

View File

@@ -0,0 +1,51 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package generators
import (
"sigs.k8s.io/kustomize/api/filters/filtersutil"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
// MakeConfigMap makes a configmap.
//
// ConfigMap: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/#configmap-v1-core
//
// ConfigMaps and Secrets are similar.
//
// Both objects have a `data` field, which contains a map from keys to
// values that must be UTF-8 valid strings. Such data might be simple text,
// or whoever made the data may have done so by performing a base64 encoding
// on binary data. Regardless, k8s has no means to know this, so it treats
// the data field as a string.
//
// The ConfigMap has an additional field `binaryData`, also a map, but its
// values are _intended_ to be interpreted as a base64 encoding of []byte,
// by whatever makes use of the ConfigMap.
//
// In a ConfigMap, any key used in `data` cannot also be used in `binaryData`
// and vice-versa. A key must be unique across both maps.
func MakeConfigMap(
ldr ifc.KvLoader, args *types.ConfigMapArgs) (rn *yaml.RNode, err error) {
rn, err = makeBaseNode("ConfigMap", args.Name, args.Namespace)
if err != nil {
return nil, err
}
m, err := makeValidatedDataMap(ldr, args.Name, args.KvPairSources)
if err != nil {
return nil, err
}
for _, k := range filtersutil.SortedMapKeys(m) {
fldName, vrN := makeConfigMapValueRNode(m[k])
if _, err = rn.Pipe(
yaml.LookupCreate(yaml.MappingNode, fldName),
yaml.SetField(k, vrN)); err != nil {
return nil, err
}
}
copyLabelsAndAnnotations(rn, args.Options)
return rn, err
}

View File

@@ -0,0 +1,223 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package generators_test
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"sigs.k8s.io/kustomize/api/filesys"
. "sigs.k8s.io/kustomize/api/internal/generators"
"sigs.k8s.io/kustomize/api/kv"
"sigs.k8s.io/kustomize/api/loader"
valtest_test "sigs.k8s.io/kustomize/api/testutils/valtest"
"sigs.k8s.io/kustomize/api/types"
)
var binaryHello = []byte{
0xff, // non-utf8
0x68, // h
0x65, // e
0x6c, // l
0x6c, // l
0x6f, // o
}
func manyHellos(count int) (result []byte) {
for i := 0; i < count; i++ {
result = append(result, binaryHello...)
}
return
}
func TestMakeConfigMap(t *testing.T) {
type expected struct {
out string
errMsg string
}
testCases := map[string]struct {
args types.ConfigMapArgs
exp expected
}{
"construct config map from env": {
args: types.ConfigMapArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "envConfigMap",
KvPairSources: types.KvPairSources{
EnvSources: []string{
filepath.Join("configmap", "app.env"),
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: ConfigMap
metadata:
name: envConfigMap
data:
DB_PASSWORD: qwerty
DB_USERNAME: admin
`,
},
},
"construct config map from text file": {
args: types.ConfigMapArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "fileConfigMap1",
KvPairSources: types.KvPairSources{
FileSources: []string{
filepath.Join("configmap", "app-init.ini"),
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: ConfigMap
metadata:
name: fileConfigMap1
data:
app-init.ini: |
FOO=bar
BAR=baz
`,
},
},
"construct config map from text and binary file": {
args: types.ConfigMapArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "fileConfigMap2",
KvPairSources: types.KvPairSources{
FileSources: []string{
filepath.Join("configmap", "app-init.ini"),
filepath.Join("configmap", "app.bin"),
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: ConfigMap
metadata:
name: fileConfigMap2
data:
app-init.ini: |
FOO=bar
BAR=baz
binaryData:
app.bin: |
/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbG
xv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hl
bGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv/2
hlbGxv/2hlbGxv/2hlbGxv/2hlbGxv
`,
},
},
"construct config map from literal": {
args: types.ConfigMapArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "literalConfigMap1",
KvPairSources: types.KvPairSources{
LiteralSources: []string{"a=x", "b=y", "c=\"Hello World\"", "d='true'"},
},
Options: &types.GeneratorOptions{
Labels: map[string]string{
"foo": "bar",
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: ConfigMap
metadata:
name: literalConfigMap1
labels:
foo: 'bar'
data:
a: x
b: y
c: Hello World
d: "true"
`,
},
},
"construct config map from literal with GeneratorOptions in ConfigMapArgs": {
args: types.ConfigMapArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "literalConfigMap2",
KvPairSources: types.KvPairSources{
LiteralSources: []string{"a=x", "b=y", "c=\"Hello World\"", "d='true'"},
},
Options: &types.GeneratorOptions{
Labels: map[string]string{
"veggie": "celery",
"dog": "beagle",
"cat": "annoying",
},
Annotations: map[string]string{
"river": "Missouri",
"city": "Iowa City",
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: ConfigMap
metadata:
name: literalConfigMap2
labels:
cat: 'annoying'
dog: 'beagle'
veggie: 'celery'
annotations:
city: 'Iowa City'
river: 'Missouri'
data:
a: x
b: y
c: Hello World
d: "true"
`,
},
},
}
fSys := filesys.MakeFsInMemory()
fSys.WriteFile(
filesys.RootedPath("configmap", "app.env"),
[]byte("DB_USERNAME=admin\nDB_PASSWORD=qwerty\n"))
fSys.WriteFile(
filesys.RootedPath("configmap", "app-init.ini"),
[]byte("FOO=bar\nBAR=baz\n"))
fSys.WriteFile(
filesys.RootedPath("configmap", "app.bin"),
manyHellos(30))
kvLdr := kv.NewLoader(
loader.NewFileLoaderAtRoot(fSys),
valtest_test.MakeFakeValidator())
for n := range testCases {
tc := testCases[n]
t.Run(n, func(t *testing.T) {
rn, err := MakeConfigMap(kvLdr, &tc.args)
if err != nil {
if !assert.EqualError(t, err, tc.exp.errMsg) {
t.FailNow()
}
return
}
if tc.exp.errMsg != "" {
t.Fatalf("%s: should return error '%s'", n, tc.exp.errMsg)
}
output := rn.MustString()
if !assert.Equal(t, tc.exp.out, output) {
t.FailNow()
}
})
}
}

View File

@@ -0,0 +1,60 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package generators
import (
"sigs.k8s.io/kustomize/api/filters/filtersutil"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
// MakeSecret makes a kubernetes Secret.
//
// Secret: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/#secret-v1-core
//
// ConfigMaps and Secrets are similar.
//
// Like a ConfigMap, a Secret has a `data` field, but unlike a ConfigMap it has
// no `binaryData` field.
//
// All of a Secret's data is assumed to be opaque in nature, and assumed to be
// base64 encoded from its original representation, regardless of whether the
// original data was UTF-8 text or binary.
//
// This encoding provides no secrecy. It's just a neutral, common means to
// represent opaque text and binary data. Beneath the base64 encoding
// is presumably further encoding under control of the Secret's consumer.
//
// A Secret has string field `type` which holds an identifier, used by the
// client, to choose the algorithm to interpret the `data` field. Kubernetes
// cannot make use of this data; it's up to a controller or some pod's service
// to interpret the value, using `type` as a clue as to how to do this.
func MakeSecret(
ldr ifc.KvLoader, args *types.SecretArgs) (rn *yaml.RNode, err error) {
rn, err = makeBaseNode("Secret", args.Name, args.Namespace)
if err != nil {
return nil, err
}
if _, err := rn.Pipe(
yaml.FieldSetter{
Name: "type",
Value: yaml.NewStringRNode("Opaque")}); err != nil {
return nil, err
}
m, err := makeValidatedDataMap(ldr, args.Name, args.KvPairSources)
if err != nil {
return nil, err
}
for _, k := range filtersutil.SortedMapKeys(m) {
vrN := makeSecretValueRNode(m[k])
if _, err = rn.Pipe(
yaml.LookupCreate(yaml.MappingNode, yaml.DataField),
yaml.SetField(k, vrN)); err != nil {
return nil, err
}
}
copyLabelsAndAnnotations(rn, args.Options)
return rn, err
}

View File

@@ -0,0 +1,203 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package generators_test
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"sigs.k8s.io/kustomize/api/filesys"
. "sigs.k8s.io/kustomize/api/internal/generators"
"sigs.k8s.io/kustomize/api/kv"
"sigs.k8s.io/kustomize/api/loader"
valtest_test "sigs.k8s.io/kustomize/api/testutils/valtest"
"sigs.k8s.io/kustomize/api/types"
)
func TestMakeSecret(t *testing.T) {
type expected struct {
out string
errMsg string
}
testCases := map[string]struct {
args types.SecretArgs
exp expected
}{
"construct secret from env": {
args: types.SecretArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "envSecret",
KvPairSources: types.KvPairSources{
EnvSources: []string{
filepath.Join("secret", "app.env"),
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: Secret
metadata:
name: envSecret
type: Opaque
data:
DB_PASSWORD: cXdlcnR5
DB_USERNAME: YWRtaW4=
`,
},
},
"construct secret from text file": {
args: types.SecretArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "fileSecret1",
KvPairSources: types.KvPairSources{
FileSources: []string{
filepath.Join("secret", "app-init.ini"),
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: Secret
metadata:
name: fileSecret1
type: Opaque
data:
app-init.ini: Rk9PPWJhcgpCQVI9YmF6Cg==
`,
},
},
"construct secret from text and binary file": {
args: types.SecretArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "fileSecret2",
KvPairSources: types.KvPairSources{
FileSources: []string{
filepath.Join("secret", "app-init.ini"),
filepath.Join("secret", "app.bin"),
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: Secret
metadata:
name: fileSecret2
type: Opaque
data:
app-init.ini: Rk9PPWJhcgpCQVI9YmF6Cg==
app.bin: //0=
`,
},
},
"construct secret from literal": {
args: types.SecretArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "literalSecret1",
KvPairSources: types.KvPairSources{
LiteralSources: []string{"a=x", "b=y", "c=\"Hello World\"", "d='true'"},
},
Options: &types.GeneratorOptions{
Labels: map[string]string{
"foo": "bar",
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: Secret
metadata:
name: literalSecret1
labels:
foo: 'bar'
type: Opaque
data:
a: eA==
b: eQ==
c: SGVsbG8gV29ybGQ=
d: dHJ1ZQ==
`,
},
},
"construct secret from literal with GeneratorOptions in SecretArgs": {
args: types.SecretArgs{
GeneratorArgs: types.GeneratorArgs{
Name: "literalSecret2",
KvPairSources: types.KvPairSources{
LiteralSources: []string{"a=x", "b=y", "c=\"Hello World\"", "d='true'"},
},
Options: &types.GeneratorOptions{
Labels: map[string]string{
"veggie": "celery",
"dog": "beagle",
"cat": "annoying",
},
Annotations: map[string]string{
"river": "Missouri",
"city": "Iowa City",
},
},
},
},
exp: expected{
out: `apiVersion: v1
kind: Secret
metadata:
name: literalSecret2
labels:
cat: 'annoying'
dog: 'beagle'
veggie: 'celery'
annotations:
city: 'Iowa City'
river: 'Missouri'
type: Opaque
data:
a: eA==
b: eQ==
c: SGVsbG8gV29ybGQ=
d: dHJ1ZQ==
`,
},
},
}
fSys := filesys.MakeFsInMemory()
fSys.WriteFile(
filesys.RootedPath("secret", "app.env"),
[]byte("DB_USERNAME=admin\nDB_PASSWORD=qwerty\n"))
fSys.WriteFile(
filesys.RootedPath("secret", "app-init.ini"),
[]byte("FOO=bar\nBAR=baz\n"))
fSys.WriteFile(
filesys.RootedPath("secret", "app.bin"),
[]byte{0xff, 0xfd})
kvLdr := kv.NewLoader(
loader.NewFileLoaderAtRoot(fSys),
valtest_test.MakeFakeValidator())
for n := range testCases {
tc := testCases[n]
t.Run(n, func(t *testing.T) {
rn, err := MakeSecret(kvLdr, &tc.args)
if err != nil {
if !assert.EqualError(t, err, tc.exp.errMsg) {
t.FailNow()
}
return
}
if tc.exp.errMsg != "" {
t.Fatalf("%s: should return error '%s'", n, tc.exp.errMsg)
}
output := rn.MustString()
if !assert.Equal(t, tc.exp.out, output) {
t.FailNow()
}
})
}
}

View File

@@ -0,0 +1,139 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package generators
import (
"encoding/base64"
"fmt"
"strings"
"unicode/utf8"
"github.com/go-errors/errors"
"sigs.k8s.io/kustomize/api/filters/filtersutil"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
func makeBaseNode(kind, name, namespace string) (*yaml.RNode, error) {
rn, err := yaml.Parse(fmt.Sprintf(`
apiVersion: v1
kind: %s
`, kind))
if err != nil {
return nil, err
}
if name == "" {
return nil, errors.Errorf("a configmap must have a name")
}
if _, err := rn.Pipe(yaml.SetK8sName(name)); err != nil {
return nil, err
}
if namespace != "" {
if _, err := rn.Pipe(yaml.SetK8sNamespace(namespace)); err != nil {
return nil, err
}
}
return rn, nil
}
func makeValidatedDataMap(
ldr ifc.KvLoader, name string, sources types.KvPairSources) (map[string]string, error) {
pairs, err := ldr.Load(sources)
if err != nil {
return nil, errors.WrapPrefix(err, "loading KV pairs", 0)
}
knownKeys := make(map[string]string)
for _, p := range pairs {
// legal key: alphanumeric characters, '-', '_' or '.'
if err := ldr.Validator().ErrIfInvalidKey(p.Key); err != nil {
return nil, err
}
if _, ok := knownKeys[p.Key]; ok {
return nil, errors.Errorf(
"configmap %s illegally repeats the key `%s`", name, p.Key)
}
knownKeys[p.Key] = p.Value
}
return knownKeys, nil
}
// copyLabelsAndAnnotations copies labels and annotations from
// GeneratorOptions into the given object.
func copyLabelsAndAnnotations(
rn *yaml.RNode, opts *types.GeneratorOptions) error {
if opts == nil {
return nil
}
for _, k := range filtersutil.SortedMapKeys(opts.Labels) {
v := opts.Labels[k]
if _, err := rn.Pipe(yaml.SetLabel(k, v)); err != nil {
return err
}
}
for _, k := range filtersutil.SortedMapKeys(opts.Annotations) {
v := opts.Annotations[k]
if _, err := rn.Pipe(yaml.SetAnnotation(k, v)); err != nil {
return err
}
}
return nil
}
// In a secret, all data is base64 encoded, regardless of its conformance
// or lack thereof to UTF-8.
func makeSecretValueRNode(s string) *yaml.RNode {
yN := &yaml.Node{Kind: yaml.ScalarNode}
// Purposely don't use YAML tags to identify the data as being plain text or
// binary. It kubernetes Secrets the values in the `data` map are expected
// to be base64 encoded, and in ConfigMaps that same can be said for the
// values in the `binaryData` field.
yN.Tag = yaml.NodeTagString
yN.Value = encodeBase64(s)
if strings.Contains(yN.Value, "\n") {
yN.Style = yaml.LiteralStyle
}
return yaml.NewRNode(yN)
}
func makeConfigMapValueRNode(s string) (field string, rN *yaml.RNode) {
yN := &yaml.Node{Kind: yaml.ScalarNode}
yN.Tag = yaml.NodeTagString
if utf8.ValidString(s) {
field = yaml.DataField
yN.Value = s
} else {
field = yaml.BinaryDataField
yN.Value = encodeBase64(s)
}
if strings.Contains(yN.Value, "\n") {
yN.Style = yaml.LiteralStyle
}
return field, yaml.NewRNode(yN)
}
// encodeBase64 encodes s as base64 that is broken up into multiple lines
// as appropriate for the resulting length.
func encodeBase64(s string) string {
const lineLen = 70
encLen := base64.StdEncoding.EncodedLen(len(s))
lines := encLen/lineLen + 1
buf := make([]byte, encLen*2+lines)
in := buf[0:encLen]
out := buf[encLen:]
base64.StdEncoding.Encode(in, []byte(s))
k := 0
for i := 0; i < len(in); i += lineLen {
j := i + lineLen
if j > len(in) {
j = len(in)
}
k += copy(out[k:], in[i:j])
if lines > 1 {
out[k] = '\n'
k++
}
}
return string(out[:k])
}

View File

@@ -27,9 +27,6 @@ func ClonerUsingGitExec(repoSpec *RepoSpec) error {
return err
}
if repoSpec.Ref == "" {
repoSpec.Ref = "master"
}
cmd := exec.Command(
gitProgram,
"clone",
@@ -45,28 +42,30 @@ func ClonerUsingGitExec(repoSpec *RepoSpec) error {
repoSpec.CloneSpec(), repoSpec.Dir.String())
}
cmd = exec.Command(
gitProgram,
"fetch",
"--depth=1",
"origin",
repoSpec.Ref)
cmd.Dir = repoSpec.Dir.String()
out, err = cmd.CombinedOutput()
if err != nil {
log.Printf("Error fetching ref: %s", out)
return errors.Wrapf(err, "trouble fetching %s", repoSpec.Ref)
}
if repoSpec.Ref != "" {
cmd = exec.Command(
gitProgram,
"fetch",
"--depth=1",
"origin",
repoSpec.Ref)
cmd.Dir = repoSpec.Dir.String()
out, err = cmd.CombinedOutput()
if err != nil {
log.Printf("Error fetching ref: %s", out)
return errors.Wrapf(err, "trouble fetching %s", repoSpec.Ref)
}
cmd = exec.Command(
gitProgram,
"checkout",
"FETCH_HEAD")
cmd.Dir = repoSpec.Dir.String()
out, err = cmd.CombinedOutput()
if err != nil {
log.Printf("Error checking out ref: %s", out)
return errors.Wrapf(err, "trouble checking out %s", repoSpec.Ref)
cmd = exec.Command(
gitProgram,
"checkout",
"FETCH_HEAD")
cmd.Dir = repoSpec.Dir.String()
out, err = cmd.CombinedOutput()
if err != nil {
log.Printf("Error checking out ref: %s", out)
return errors.Wrapf(err, "trouble checking out %s", repoSpec.Ref)
}
}
cmd = exec.Command(

View File

@@ -0,0 +1,43 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package conflict
import (
"encoding/json"
jsonpatch "github.com/evanphx/json-patch"
"k8s.io/apimachinery/pkg/util/mergepatch"
"sigs.k8s.io/kustomize/api/resource"
)
// conflictDetectorJson detects conflicts in a list of JSON patches.
type conflictDetectorJson struct {
resourceFactory *resource.Factory
}
var _ resource.ConflictDetector = &conflictDetectorJson{}
func (cd *conflictDetectorJson) HasConflict(
p1, p2 *resource.Resource) (bool, error) {
return mergepatch.HasConflicts(p1.Map(), p2.Map())
}
func (cd *conflictDetectorJson) MergePatches(
patch1, patch2 *resource.Resource) (*resource.Resource, error) {
baseBytes, err := json.Marshal(patch1.Map())
if err != nil {
return nil, err
}
patchBytes, err := json.Marshal(patch2.Map())
if err != nil {
return nil, err
}
mergedBytes, err := jsonpatch.MergeMergePatches(baseBytes, patchBytes)
if err != nil {
return nil, err
}
mergedMap := make(map[string]interface{})
err = json.Unmarshal(mergedBytes, &mergedMap)
return cd.resourceFactory.FromMap(mergedMap), err
}

View File

@@ -0,0 +1,65 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package conflict
import (
"fmt"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"sigs.k8s.io/kustomize/api/resource"
)
// conflictDetectorSm detects conflicts in a list of strategic merge patches.
type conflictDetectorSm struct {
lookupPatchMeta strategicpatch.LookupPatchMeta
resourceFactory *resource.Factory
}
var _ resource.ConflictDetector = &conflictDetectorSm{}
func (cd *conflictDetectorSm) HasConflict(
p1, p2 *resource.Resource) (bool, error) {
return strategicpatch.MergingMapsHaveConflicts(
p1.Map(), p2.Map(), cd.lookupPatchMeta)
}
func (cd *conflictDetectorSm) MergePatches(
patch1, patch2 *resource.Resource) (*resource.Resource, error) {
if cd.hasDeleteDirectiveMarker(patch2.Map()) {
if cd.hasDeleteDirectiveMarker(patch1.Map()) {
return nil, fmt.Errorf(
"cannot merge patches both containing '$patch: delete' directives")
}
patch1, patch2 = patch2, patch1
}
mergedMap, err := strategicpatch.MergeStrategicMergeMapPatchUsingLookupPatchMeta(
cd.lookupPatchMeta, patch1.Map(), patch2.Map())
return cd.resourceFactory.FromMap(mergedMap), err
}
func (cd *conflictDetectorSm) hasDeleteDirectiveMarker(
patch map[string]interface{}) bool {
if v, ok := patch["$patch"]; ok && v == "delete" {
return true
}
for _, v := range patch {
switch typedV := v.(type) {
case map[string]interface{}:
if cd.hasDeleteDirectiveMarker(typedV) {
return true
}
case []interface{}:
for _, sv := range typedV {
typedE, ok := sv.(map[string]interface{})
if !ok {
break
}
if cd.hasDeleteDirectiveMarker(typedE) {
return true
}
}
}
}
return false
}

View File

@@ -0,0 +1,45 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package conflict
import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
sp "k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resource"
)
type cdFactory struct {
rf *resource.Factory
}
var _ resource.ConflictDetectorFactory = &cdFactory{}
// NewFactory returns a conflict detector factory.
// The detector uses a resource factory to convert resources to/from
// json/yaml/maps representations.
func NewFactory(rf *resource.Factory) resource.ConflictDetectorFactory {
return &cdFactory{rf: rf}
}
// New returns a conflict detector that's aware of the GVK type.
func (f *cdFactory) New(gvk resid.Gvk) (resource.ConflictDetector, error) {
// Convert to apimachinery representation of object
obj, err := scheme.Scheme.New(schema.GroupVersionKind{
Group: gvk.Group,
Version: gvk.Version,
Kind: gvk.Kind,
})
if err == nil {
meta, err := sp.NewPatchMetaFromStruct(obj)
return &conflictDetectorSm{
lookupPatchMeta: meta, resourceFactory: f.rf}, err
}
if runtime.IsNotRegisteredError(err) {
return &conflictDetectorJson{resourceFactory: f.rf}, nil
}
return nil, err
}

View File

@@ -1,239 +0,0 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package merge
import (
"encoding/json"
"fmt"
jsonpatch "github.com/evanphx/json-patch"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/mergepatch"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
)
type conflictDetector interface {
hasConflict(patch1, patch2 *resource.Resource) (bool, error)
findConflict(
conflictingPatchIdx int,
patches []*resource.Resource) (*resource.Resource, error)
mergePatches(patch1, patch2 *resource.Resource) (*resource.Resource, error)
}
type jsonMergePatch struct {
resourceFactory *resource.Factory
}
var _ conflictDetector = &jsonMergePatch{}
func newJMPConflictDetector(rf *resource.Factory) conflictDetector {
return &jsonMergePatch{resourceFactory: rf}
}
func (jmp *jsonMergePatch) hasConflict(
patch1, patch2 *resource.Resource) (bool, error) {
return mergepatch.HasConflicts(patch1.Map(), patch2.Map())
}
func (jmp *jsonMergePatch) findConflict(
conflictingPatchIdx int,
patches []*resource.Resource) (*resource.Resource, error) {
for i, patch := range patches {
if i == conflictingPatchIdx {
continue
}
if !patches[conflictingPatchIdx].OrgId().Equals(patch.OrgId()) {
continue
}
conflict, err := mergepatch.HasConflicts(
patch.Map(),
patches[conflictingPatchIdx].Map())
if err != nil {
return nil, err
}
if conflict {
return patch, nil
}
}
return nil, nil
}
func (jmp *jsonMergePatch) mergePatches(
patch1, patch2 *resource.Resource) (*resource.Resource, error) {
baseBytes, err := json.Marshal(patch1.Map())
if err != nil {
return nil, err
}
patchBytes, err := json.Marshal(patch2.Map())
if err != nil {
return nil, err
}
mergedBytes, err := jsonpatch.MergeMergePatches(baseBytes, patchBytes)
if err != nil {
return nil, err
}
mergedMap := make(map[string]interface{})
err = json.Unmarshal(mergedBytes, &mergedMap)
return jmp.resourceFactory.FromMap(mergedMap), err
}
type strategicMergePatch struct {
lookupPatchMeta strategicpatch.LookupPatchMeta
rf *resource.Factory
}
var _ conflictDetector = &strategicMergePatch{}
func newSMPConflictDetector(
versionedObj runtime.Object,
rf *resource.Factory) (conflictDetector, error) {
lookupPatchMeta, err := strategicpatch.NewPatchMetaFromStruct(versionedObj)
return &strategicMergePatch{lookupPatchMeta: lookupPatchMeta, rf: rf}, err
}
func (smp *strategicMergePatch) hasConflict(
p1, p2 *resource.Resource) (bool, error) {
return strategicpatch.MergingMapsHaveConflicts(
p1.Map(), p2.Map(), smp.lookupPatchMeta)
}
func (smp *strategicMergePatch) findConflict(
conflictingPatchIdx int,
patches []*resource.Resource) (*resource.Resource, error) {
for i, patch := range patches {
if i == conflictingPatchIdx {
continue
}
if !patches[conflictingPatchIdx].OrgId().Equals(patch.OrgId()) {
continue
}
conflict, err := strategicpatch.MergingMapsHaveConflicts(
patch.Map(),
patches[conflictingPatchIdx].Map(),
smp.lookupPatchMeta)
if err != nil {
return nil, err
}
if conflict {
return patch, nil
}
}
return nil, nil
}
func (smp *strategicMergePatch) mergePatches(
patch1, patch2 *resource.Resource) (*resource.Resource, error) {
if hasDeleteDirectiveMarker(patch2.Map()) {
if hasDeleteDirectiveMarker(patch1.Map()) {
return nil, fmt.Errorf(
"cannot merge patches both containing '$patch: delete' directives")
}
patch1, patch2 = patch2, patch1
}
mergeJSONMap, err := strategicpatch.MergeStrategicMergeMapPatchUsingLookupPatchMeta(
smp.lookupPatchMeta, patch1.Map(), patch2.Map())
return smp.rf.FromMap(mergeJSONMap), err
}
type merginatorImpl struct {
rf *resource.Factory
}
// NewMerginator returns a new implementation of resmap.Merginator.
func NewMerginator(rf *resource.Factory) resmap.Merginator {
return &merginatorImpl{rf: rf}
}
var _ resmap.Merginator = (*merginatorImpl)(nil)
// Merge merges the incoming resources into a new resmap.ResMap.
// Returns an error on conflict.
func (m *merginatorImpl) Merge(
patches []*resource.Resource) (resmap.ResMap, error) {
rc := resmap.New()
for ix, patch := range patches {
id := patch.OrgId()
existing := rc.GetMatchingResourcesByOriginalId(id.Equals)
if len(existing) == 0 {
rc.Append(patch)
continue
}
if len(existing) > 1 {
return nil, fmt.Errorf("self conflict in patches")
}
versionedObj, err := scheme.Scheme.New(toSchemaGvk(id.Gvk))
if err != nil && !runtime.IsNotRegisteredError(err) {
return nil, err
}
var cd conflictDetector
if err != nil {
cd = newJMPConflictDetector(m.rf)
} else {
cd, err = newSMPConflictDetector(versionedObj, m.rf)
if err != nil {
return nil, err
}
}
conflict, err := cd.hasConflict(existing[0], patch)
if err != nil {
return nil, err
}
if conflict {
conflictingPatch, err := cd.findConflict(ix, patches)
if err != nil {
return nil, err
}
return nil, fmt.Errorf(
"conflict between %#v and %#v",
conflictingPatch.Map(), patch.Map())
}
merged, err := cd.mergePatches(existing[0], patch)
if err != nil {
return nil, err
}
rc.Replace(merged)
}
return rc, nil
}
// toSchemaGvk converts to a schema.GroupVersionKind.
func toSchemaGvk(x resid.Gvk) schema.GroupVersionKind {
return schema.GroupVersionKind{
Group: x.Group,
Version: x.Version,
Kind: x.Kind,
}
}
func hasDeleteDirectiveMarker(patch map[string]interface{}) bool {
if v, ok := patch["$patch"]; ok && v == "delete" {
return true
}
for _, v := range patch {
switch typedV := v.(type) {
case map[string]interface{}:
if hasDeleteDirectiveMarker(typedV) {
return true
}
case []interface{}:
for _, sv := range typedV {
typedE, ok := sv.(map[string]interface{})
if !ok {
break
}
if hasDeleteDirectiveMarker(typedE) {
return true
}
}
}
}
return false
}

View File

@@ -1,25 +0,0 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package merge
import (
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
)
// Merginator implements resmap.Merginator using kyaml libs.
type Merginator struct {
}
var _ resmap.Merginator = (*Merginator)(nil)
func NewMerginator(_ *resource.Factory) *Merginator {
return &Merginator{}
}
// Merge implements resmap.Merginator
func (m Merginator) Merge(
resources []*resource.Resource) (resmap.ResMap, error) {
panic("TODO(#Merginator): implement Merge")
}

View File

@@ -1,4 +0,0 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package merge_test

View File

@@ -23,11 +23,12 @@ func _() {
_ = x[ReplicaCountTransformer-12]
_ = x[SecretGenerator-13]
_ = x[ValueAddTransformer-14]
_ = x[HelmChartInflationGenerator-15]
}
const _BuiltinPluginType_name = "UnknownAnnotationsTransformerConfigMapGeneratorHashTransformerImageTagTransformerLabelTransformerLegacyOrderTransformerNamespaceTransformerPatchJson6902TransformerPatchStrategicMergeTransformerPatchTransformerPrefixSuffixTransformerReplicaCountTransformerSecretGeneratorValueAddTransformer"
const _BuiltinPluginType_name = "UnknownAnnotationsTransformerConfigMapGeneratorHashTransformerImageTagTransformerLabelTransformerLegacyOrderTransformerNamespaceTransformerPatchJson6902TransformerPatchStrategicMergeTransformerPatchTransformerPrefixSuffixTransformerReplicaCountTransformerSecretGeneratorValueAddTransformerHelmChartInflationGenerator"
var _BuiltinPluginType_index = [...]uint16{0, 7, 29, 47, 62, 81, 97, 119, 139, 163, 193, 209, 232, 255, 270, 289}
var _BuiltinPluginType_index = [...]uint16{0, 7, 29, 47, 62, 81, 97, 119, 139, 163, 193, 209, 232, 255, 270, 289, 316}
func (i BuiltinPluginType) String() string {
if i < 0 || i >= BuiltinPluginType(len(_BuiltinPluginType_index)-1) {

View File

@@ -27,6 +27,7 @@ const (
ReplicaCountTransformer
SecretGenerator
ValueAddTransformer
HelmChartInflationGenerator
)
var stringToBuiltinPluginTypeMap map[string]BuiltinPluginType
@@ -55,8 +56,9 @@ func GetBuiltinPluginType(n string) BuiltinPluginType {
}
var GeneratorFactories = map[BuiltinPluginType]func() resmap.GeneratorPlugin{
ConfigMapGenerator: builtins.NewConfigMapGeneratorPlugin,
SecretGenerator: builtins.NewSecretGeneratorPlugin,
ConfigMapGenerator: builtins.NewConfigMapGeneratorPlugin,
SecretGenerator: builtins.NewSecretGeneratorPlugin,
HelmChartInflationGenerator: builtins.NewHelmChartInflationGeneratorPlugin,
}
var TransformerFactories = map[BuiltinPluginType]func() resmap.TransformerPlugin{

View File

@@ -94,7 +94,7 @@ TO GENERATE CODE
cd $repo/plugin/builtin
go generate ./...
See travis/kyaml-pre-commit.sh for canonical way
See scripts/kyaml-pre-commit.sh for canonical way
to execute the above.
This creates

View File

@@ -9,6 +9,7 @@ import (
"io/ioutil"
"os"
"os/exec"
"runtime"
"strings"
"github.com/google/shlex"
@@ -50,7 +51,14 @@ func (p *ExecPlugin) ErrIfNotExecutable() error {
if err != nil {
return err
}
if f.Mode()&0111 == 0000 {
// In Windows, it is not possible to determine whether a
// file is executable through file mode.
// TODO: provide for setting the executable FileMode bit on Windows
// The (fs *fileStat) Mode() (m FileMode) {} function in
// https://golang.org/src/os/types_windows.go
// lacks the ability to set the FileMode executable bit in response
// to file data on Windows.
if f.Mode()&0111 == 0000 && runtime.GOOS != "windows" {
return fmt.Errorf("unexecutable plugin at: %s", p.path)
}
return nil

View File

@@ -4,18 +4,19 @@
package execplugin_test
import (
"path/filepath"
"runtime"
"strings"
"testing"
"sigs.k8s.io/kustomize/api/filesys"
. "sigs.k8s.io/kustomize/api/internal/plugins/execplugin"
pLdr "sigs.k8s.io/kustomize/api/internal/plugins/loader"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/internal/plugins/utils"
"sigs.k8s.io/kustomize/api/konfig"
fLdr "sigs.k8s.io/kustomize/api/loader"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
valtest_test "sigs.k8s.io/kustomize/api/testutils/valtest"
)
func TestExecPluginConfig(t *testing.T) {
@@ -30,10 +31,9 @@ s/$BAR/bar baz/g
if err != nil {
t.Fatal(err)
}
pvd := provider.NewDefaultDepProvider()
rf := resmap.NewFactory(
resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl()), nil)
v := valtest_test.MakeFakeValidator()
pvd.GetResourceFactory(), pvd.GetConflictDetectorFactory())
pluginConfig := rf.RF().FromMap(
map[string]interface{}{
"apiVersion": "someteam.example.com/v1",
@@ -59,7 +59,7 @@ s/$BAR/bar baz/g
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
p.Config(resmap.NewPluginHelpers(ldr, v, rf), yaml)
p.Config(resmap.NewPluginHelpers(ldr, pvd.GetFieldValidator(), rf), yaml)
expected := "someteam.example.com/v1/sedtransformer/SedTransformer"
if !strings.HasSuffix(p.Path(), expected) {
@@ -89,3 +89,32 @@ metadata:
t.Fatalf("unexpected arg array: %#v", p.Args())
}
}
func TestExecPlugin_ErrIfNotExecutable(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skipf("always returns nil on Windows")
}
srcRoot, err := utils.DeterminePluginSrcRoot(filesys.MakeFsOnDisk())
if err != nil {
t.Error(err)
}
// Test unexecutable plugin
unexecutablePlugin := filepath.Join(
srcRoot, "builtin", "", "secretgenerator", "SecretGenerator.so")
p := NewExecPlugin(unexecutablePlugin)
err = p.ErrIfNotExecutable()
if err == nil {
t.Fatalf("unexpected err: %v", err)
}
// Test executable plugin
executablePlugin := filepath.Join(
srcRoot, "someteam.example.com", "v1", "bashedconfigmap", "BashedConfigMap")
p = NewExecPlugin(executablePlugin)
err = p.ErrIfNotExecutable()
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
}

View File

@@ -74,10 +74,10 @@ func NewFnPlugin(o *types.FnPluginLoadingOptions) *FnPlugin {
runFns: runfn.RunFns{
Functions: []*yaml.RNode{},
Network: o.Network,
NetworkName: o.NetworkName,
EnableStarlark: o.EnableStar,
EnableExec: o.EnableExec,
StorageMounts: toStorageMounts(o.Mounts),
Env: o.Env,
},
}
}

View File

@@ -8,11 +8,10 @@ import (
"sigs.k8s.io/kustomize/api/filesys"
. "sigs.k8s.io/kustomize/api/internal/plugins/loader"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/loader"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
valtest_test "sigs.k8s.io/kustomize/api/testutils/valtest"
"sigs.k8s.io/kustomize/api/types"
@@ -51,8 +50,9 @@ func TestLoader(t *testing.T) {
BuildGoPlugin("builtin", "", "SecretGenerator").
BuildGoPlugin("someteam.example.com", "v1", "SomeServiceGenerator")
defer th.Reset()
rmF := resmap.NewFactory(resource.NewFactory(
kunstruct.NewKunstructuredFactoryImpl()), nil)
p := provider.NewDefaultDepProvider()
rmF := resmap.NewFactory(
p.GetResourceFactory(), p.GetConflictDetectorFactory())
fLdr, err := loader.NewLoader(
loader.RestrictionRootOnly,
filesys.Separator, filesys.MakeFsInMemory())
@@ -65,8 +65,8 @@ func TestLoader(t *testing.T) {
t.Fatal(err)
}
for _, behavior := range []types.BuiltinPluginLoadingOptions{
types.BploUseStaticallyLinked,
types.BploLoadFromFileSys} {
/* types.BploUseStaticallyLinked,
types.BploLoadFromFileSys */} {
c, err := konfig.EnabledPluginConfig(behavior)
if err != nil {
t.Fatal(err)

View File

@@ -9,9 +9,10 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"sigs.k8s.io/kustomize/api/filesys"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
@@ -64,7 +65,7 @@ func strptr(s string) *string {
}
func TestUpdateResourceOptions(t *testing.T) {
rf := resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())
rf := provider.NewDefaultDepProvider().GetResourceFactory()
in := resmap.New()
expected := resmap.New()
cases := []struct {
@@ -87,28 +88,12 @@ func TestUpdateResourceOptions(t *testing.T) {
expected.Append(makeConfigMapOptions(rf, name, c.behavior, !c.needsHash))
}
actual, err := UpdateResourceOptions(in)
if err != nil {
t.Fatalf("unexpected error: %v", err.Error())
}
for i, a := range expected.Resources() {
b := actual.GetByIndex(i)
if b == nil {
t.Fatalf("resource %d missing from processed map", i)
}
if !a.Equals(b) {
t.Errorf("expected %v got %v", a, b)
}
if a.NeedHashSuffix() != b.NeedHashSuffix() {
t.Errorf("")
}
if a.Behavior() != b.Behavior() {
t.Errorf("expected %v got %v", a.Behavior(), b.Behavior())
}
}
assert.NoError(t, err)
assert.NoError(t, expected.ErrorIfNotEqualLists(actual))
}
func TestUpdateResourceOptionsWithInvalidHashAnnotationValues(t *testing.T) {
rf := resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())
rf := provider.NewDefaultDepProvider().GetResourceFactory()
cases := []string{
"",
"FaLsE",

View File

@@ -8,6 +8,7 @@ import (
"fmt"
"strings"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"sigs.k8s.io/kustomize/api/builtins"
"sigs.k8s.io/kustomize/api/ifc"
@@ -234,7 +235,18 @@ func (kt *KustTarget) runGenerators(
func (kt *KustTarget) configureExternalGenerators() ([]resmap.Generator, error) {
ra := accumulator.MakeEmptyAccumulator()
ra, err := kt.accumulateResources(ra, kt.kustomization.Generators)
var generatorPaths []string
for _, p := range kt.kustomization.Generators {
// handle inline generators
rm, err := kt.rFactory.NewResMapFromBytes([]byte(p))
if err != nil {
// not an inline config
generatorPaths = append(generatorPaths, p)
continue
}
ra.AppendAll(rm)
}
ra, err := kt.accumulateResources(ra, generatorPaths)
if err != nil {
return nil, err
}
@@ -259,7 +271,18 @@ func (kt *KustTarget) runTransformers(ra *accumulator.ResAccumulator) error {
func (kt *KustTarget) configureExternalTransformers(transformers []string) ([]resmap.Transformer, error) {
ra := accumulator.MakeEmptyAccumulator()
ra, err := kt.accumulateResources(ra, transformers)
var transformerPaths []string
for _, p := range transformers {
// handle inline transformers
rm, err := kt.rFactory.NewResMapFromBytes([]byte(p))
if err != nil {
// not an inline config
transformerPaths = append(transformerPaths, p)
continue
}
ra.AppendAll(rm)
}
ra, err := kt.accumulateResources(ra, transformerPaths)
if err != nil {
return nil, err
@@ -313,12 +336,18 @@ func (kt *KustTarget) accumulateResources(
if errF := kt.accumulateFile(ra, path); errF != nil {
ldr, errL := kt.ldr.New(path)
if errL != nil {
return nil, fmt.Errorf("accumulateFile %q, loader.New %q", errF, errL)
return nil, multierror.Append(
fmt.Errorf("accumulateFile error: %q", errF),
fmt.Errorf("loader.New error: %q", errL),
)
}
var errD error
ra, errD = kt.accumulateDirectory(ra, ldr, false)
if errD != nil {
return nil, fmt.Errorf("accumulateFile %q, accumulateDirector: %q", errF, errD)
return nil, multierror.Append(
fmt.Errorf("accumulateFile error: %q", errF),
fmt.Errorf("accumulateDirector error: %q", errD),
)
}
}
}

View File

@@ -32,6 +32,7 @@ func (kt *KustTarget) configureBuiltinGenerators() (
for _, bpt := range []builtinhelpers.BuiltinPluginType{
builtinhelpers.ConfigMapGenerator,
builtinhelpers.SecretGenerator,
builtinhelpers.HelmChartInflationGenerator,
} {
r, err := generatorConfigurators[bpt](
kt, bpt, builtinhelpers.GeneratorFactories[bpt])
@@ -110,6 +111,23 @@ var generatorConfigurators = map[builtinhelpers.BuiltinPluginType]func(
}
return
},
builtinhelpers.HelmChartInflationGenerator: func(kt *KustTarget, bpt builtinhelpers.BuiltinPluginType, f gFactory) (
result []resmap.Generator, err error) {
var c struct {
types.HelmChartArgs
}
for _, args := range kt.kustomization.HelmChartInflationGenerator {
c.HelmChartArgs = args
p := f()
err := kt.configureBuiltinPlugin(p, c, bpt)
if err != nil {
return nil, err
}
result = append(result, p)
}
return
},
}
type tFactory func() resmap.TransformerPlugin
@@ -141,12 +159,12 @@ var transformerConfigurators = map[builtinhelpers.BuiltinPluginType]func(
kt *KustTarget, bpt builtinhelpers.BuiltinPluginType, f tFactory, _ *builtinconfig.TransformerConfig) (
result []resmap.Transformer, err error) {
var c struct {
Target types.PatchTarget `json:"target,omitempty" yaml:"target,omitempty"`
Path string `json:"path,omitempty" yaml:"path,omitempty"`
JsonOp string `json:"jsonOp,omitempty" yaml:"jsonOp,omitempty"`
Target *types.Selector `json:"target,omitempty" yaml:"target,omitempty"`
Path string `json:"path,omitempty" yaml:"path,omitempty"`
JsonOp string `json:"jsonOp,omitempty" yaml:"jsonOp,omitempty"`
}
for _, args := range kt.kustomization.PatchesJson6902 {
c.Target = *args.Target
c.Target = args.Target
c.Path = args.Path
c.JsonOp = args.Patch
p := f()
@@ -165,8 +183,7 @@ var transformerConfigurators = map[builtinhelpers.BuiltinPluginType]func(
return
}
var c struct {
Paths []types.PatchStrategicMerge `json:"paths,omitempty" yaml:"paths,omitempty"`
Patches string `json:"patches,omitempty" yaml:"patches,omitempty"`
Paths []types.PatchStrategicMerge `json:"paths,omitempty" yaml:"paths,omitempty"`
}
c.Paths = kt.kustomization.PatchesStrategicMerge
p := f()

View File

@@ -8,9 +8,10 @@ import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
@@ -76,8 +77,7 @@ commonLabels:
}
kt := makeKustTargetWithRf(
t, th.GetFSys(), "/",
resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl()))
t, th.GetFSys(), "/", provider.NewDefaultDepProvider())
for tn, tc := range testCases {
t.Run(tn, func(t *testing.T) {
th.WriteK("/", tc.content)
@@ -148,7 +148,8 @@ metadata:
{"op": "add", "path": "/spec/replica", "value": "3"}
]`)
resFactory := resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl())
pvd := provider.NewDefaultDepProvider()
resFactory := pvd.GetResourceFactory()
resources := []*resource.Resource{
resFactory.FromMapWithName("dply1", map[string]interface{}{
@@ -243,19 +244,14 @@ metadata:
t.Fatalf("unexpected error %v", err)
}
}
expYaml, err := expected.AsYaml()
assert.NoError(t, err)
kt := makeKustTargetWithRf(
t, th.GetFSys(), "/whatever", resFactory)
err := kt.Load()
if err != nil {
t.Fatalf("unexpected Resources error %v", err)
}
kt := makeKustTargetWithRf(t, th.GetFSys(), "/whatever", pvd)
assert.NoError(t, kt.Load())
actual, err := kt.MakeCustomizedResMap()
if err != nil {
t.Fatalf("unexpected Resources error %v", err)
}
if err = expected.ErrorIfNotEqualLists(actual); err != nil {
t.Fatalf("unexpected inequality: %v", err)
}
assert.NoError(t, err)
actYaml, err := actual.AsYaml()
assert.NoError(t, err)
assert.Equal(t, expYaml, actYaml)
}

View File

@@ -7,14 +7,12 @@ import (
"testing"
"sigs.k8s.io/kustomize/api/filesys"
"sigs.k8s.io/kustomize/api/internal/k8sdeps/merge"
pLdr "sigs.k8s.io/kustomize/api/internal/plugins/loader"
"sigs.k8s.io/kustomize/api/internal/target"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/konfig"
fLdr "sigs.k8s.io/kustomize/api/loader"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
valtest_test "sigs.k8s.io/kustomize/api/testutils/valtest"
)
@@ -22,9 +20,7 @@ func makeAndLoadKustTarget(
t *testing.T,
fSys filesys.FileSystem,
root string) *target.KustTarget {
kt := makeKustTargetWithRf(
t, fSys, root,
resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl()))
kt := makeKustTargetWithRf(t, fSys, root, provider.NewDefaultDepProvider())
if err := kt.Load(); err != nil {
t.Fatalf("Unexpected load error %v", err)
}
@@ -35,13 +31,13 @@ func makeKustTargetWithRf(
t *testing.T,
fSys filesys.FileSystem,
root string,
resourceFactory *resource.Factory) *target.KustTarget {
pvd *provider.DepProvider) *target.KustTarget {
ldr, err := fLdr.NewLoader(fLdr.RestrictionRootOnly, root, fSys)
if err != nil {
t.Fatal(err)
}
rf := resmap.NewFactory(
resourceFactory, merge.NewMerginator(resourceFactory))
pvd.GetResourceFactory(), pvd.GetConflictDetectorFactory())
pc := konfig.DisabledPluginConfig()
return target.NewKustTarget(
ldr,

View File

@@ -26,13 +26,15 @@ func newMultiTransformer(t []resmap.Transformer) resmap.Transformer {
return r
}
// Transform prepends the name prefix.
// Transform applies the member transformers in order to the resources,
// optionally detecting and erroring on commutation conflict.
func (o *multiTransformer) Transform(m resmap.ResMap) error {
if o.checkConflictEnabled {
return o.transformWithCheckConflict(m)
}
return o.transform(m)
}
func (o *multiTransformer) transform(m resmap.ResMap) error {
for _, t := range o.transformers {
err := t.Transform(m)

View File

@@ -21,5 +21,5 @@ import (
// major version increments in pluginator with each
// api release to allow this trick to work and not
// introduce cycles.
// _ "sigs.k8s.io/kustomize/pluginator/v2"
// _ "sigs.k8s.io/kustomize/cmd/pluginator/v2"
)

View File

@@ -10,6 +10,10 @@ import (
// FieldValidator implements ifc.Validator to check
// the values of various KRM string fields,
// e.g. labels, annotations, names, namespaces.
//
// TODO: Have this use kyaml/yaml/internal/k8sgen/pkg/labels
// which has label and annotation validation code, but is internal
// so this impl would need to move to kyaml (a fine idea).
type FieldValidator struct {
}

View File

@@ -4,38 +4,105 @@
package wrappy
import (
"fmt"
"sigs.k8s.io/kustomize/api/hasher"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/internal/generators"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/filtersutil"
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
// WNodeFactory makes instances of WNode.
//
// These instances in turn adapt
// sigs.k8s.io/kustomize/kyaml/yaml.RNode
// to implement ifc.Unstructured.
// This factory is meant to implement ifc.KunstructuredFactory.
//
// This implementation should be thin, as both WNode and WNodeFactory must be
// factored away (deleted) along with ifc.Kunstructured in favor of direct use
// of RNode methods upon completion of
// https://github.com/kubernetes-sigs/kustomize/issues/2506.
//
// See also api/krusty/internal/provider/depprovider.go
type WNodeFactory struct {
}
var _ ifc.KunstructuredFactory = (*WNodeFactory)(nil)
func (k *WNodeFactory) SliceFromBytes(bs []byte) ([]ifc.Kunstructured, error) {
panic("TODO(#WNodeFactory): implement SliceFromBytes")
yamlRNodes, err := kio.FromBytes(bs)
if err != nil {
return nil, err
}
var result []ifc.Kunstructured
for i := range yamlRNodes {
rn := yamlRNodes[i]
meta, err := rn.GetValidatedMetadata()
if err != nil {
return nil, err
}
if !shouldDropObject(meta) {
if foundNil, path := rn.HasNilEntryInList(); foundNil {
return nil, fmt.Errorf("empty item at %v in object %v", path, rn)
}
result = append(result, FromRNode(rn))
}
}
return result, nil
}
// shouldDropObject returns true if the resource should not be accumulated.
func shouldDropObject(m yaml.ResourceMeta) bool {
_, y := m.ObjectMeta.Annotations[konfig.IgnoredByKustomizeResourceAnnotation]
return y
}
func (k *WNodeFactory) FromMap(m map[string]interface{}) ifc.Kunstructured {
panic("TODO(#WNodeFactory): implement FromMap")
rn, err := FromMap(m)
if err != nil {
// TODO(#WNodeFactory): handle or bubble error"
panic(err)
}
return rn
}
// kustHash computes a hash of an unstructured object.
type kustHash struct{}
// Hash returns a hash of the given object
func (h *kustHash) Hash(m ifc.Kunstructured) (string, error) {
node, err := filtersutil.GetRNode(m)
if err != nil {
return "", err
}
return hasher.HashRNode(node)
}
func (k *WNodeFactory) Hasher() ifc.KunstructuredHasher {
panic("TODO(#WNodeFactory): implement Hasher")
return &kustHash{}
}
// MakeConfigMap makes a wrapped configmap.
func (k *WNodeFactory) MakeConfigMap(
kvLdr ifc.KvLoader, args *types.ConfigMapArgs) (ifc.Kunstructured, error) {
panic("TODO(#WNodeFactory): implement MakeConfigMap")
ldr ifc.KvLoader, args *types.ConfigMapArgs) (ifc.Kunstructured, error) {
rn, err := generators.MakeConfigMap(ldr, args)
if err != nil {
return nil, err
}
return FromRNode(rn), nil
}
// MakeSecret makes a wrapped secret.
func (k *WNodeFactory) MakeSecret(
kvLdr ifc.KvLoader, args *types.SecretArgs) (ifc.Kunstructured, error) {
panic("TODO(#WNodeFactory): implement MakeSecret")
ldr ifc.KvLoader, args *types.SecretArgs) (ifc.Kunstructured, error) {
rn, err := generators.MakeSecret(ldr, args)
if err != nil {
return nil, err
}
return FromRNode(rn), nil
}

View File

@@ -2,3 +2,320 @@
// SPDX-License-Identifier: Apache-2.0
package wrappy_test
import (
"fmt"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
. "sigs.k8s.io/kustomize/api/internal/wrappy"
)
func TestHasher(t *testing.T) {
input := `
apiVersion: v1
kind: ConfigMap
metadata:
name: foo
data:
one: ""
binaryData:
two: ""
`
expect := "698h7c7t9m"
factory := &WNodeFactory{}
k, err := factory.SliceFromBytes([]byte(input))
if err != nil {
t.Fatal(err)
}
hasher := factory.Hasher()
result, err := hasher.Hash(k[0])
if err != nil {
t.Fatal(err)
}
if result != expect {
t.Fatalf("expect %s but got %s", expect, result)
}
}
func TestSliceFromBytes(t *testing.T) {
factory := &WNodeFactory{}
testConfigMap :=
map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "winnie",
},
}
testConfigMapList :=
map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMapList",
"items": []interface{}{
testConfigMap,
testConfigMap,
},
}
testDeploymentSpec := map[string]interface{}{
"template": map[string]interface{}{
"spec": map[string]interface{}{
"hostAliases": []interface{}{
map[string]interface{}{
"hostnames": []interface{}{
"a.example.com",
},
"ip": "8.8.8.8",
},
},
},
},
}
testDeploymentA := map[string]interface{}{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": map[string]interface{}{
"name": "deployment-a",
},
"spec": testDeploymentSpec,
}
testDeploymentB := map[string]interface{}{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": map[string]interface{}{
"name": "deployment-b",
},
"spec": testDeploymentSpec,
}
testDeploymentList :=
map[string]interface{}{
"apiVersion": "v1",
"kind": "DeploymentList",
"items": []interface{}{
testDeploymentA,
testDeploymentB,
},
}
type expected struct {
out []map[string]interface{}
isErr bool
}
testCases := map[string]struct {
input []byte
exp expected
}{
"garbage": {
input: []byte("garbageIn: garbageOut"),
exp: expected{
isErr: true,
},
},
"noBytes": {
input: []byte{},
exp: expected{
out: []map[string]interface{}{},
},
},
"goodJson": {
input: []byte(`
{"apiVersion":"v1","kind":"ConfigMap","metadata":{"name":"winnie"}}
`),
exp: expected{
out: []map[string]interface{}{testConfigMap},
},
},
"goodYaml1": {
input: []byte(`
apiVersion: v1
kind: ConfigMap
metadata:
name: winnie
`),
exp: expected{
out: []map[string]interface{}{testConfigMap},
},
},
"goodYaml2": {
input: []byte(`
apiVersion: v1
kind: ConfigMap
metadata:
name: winnie
---
apiVersion: v1
kind: ConfigMap
metadata:
name: winnie
`),
exp: expected{
out: []map[string]interface{}{testConfigMap, testConfigMap},
},
},
"localConfigYaml": {
input: []byte(`
apiVersion: v1
kind: ConfigMap
metadata:
name: winnie-skip
annotations:
# this annotation causes the Resource to be ignored by kustomize
config.kubernetes.io/local-config: ""
---
apiVersion: v1
kind: ConfigMap
metadata:
name: winnie
`),
exp: expected{
out: []map[string]interface{}{testConfigMap},
},
},
"garbageInOneOfTwoObjects": {
input: []byte(`
apiVersion: v1
kind: ConfigMap
metadata:
name: winnie
---
WOOOOOOOOOOOOOOOOOOOOOOOOT: woot
`),
exp: expected{
isErr: true,
},
},
"emptyObjects": {
input: []byte(`
---
#a comment
---
`),
exp: expected{
out: []map[string]interface{}{},
},
},
"Missing .metadata.name in object": {
input: []byte(`
apiVersion: v1
kind: Namespace
metadata:
annotations:
foo: bar
`),
exp: expected{
isErr: true,
},
},
"nil value in list": {
input: []byte(`
apiVersion: builtin
kind: ConfigMapGenerator
metadata:
name: kube100-site
labels:
app: web
testList:
- testA
-
`),
exp: expected{
isErr: true,
},
},
"List": {
input: []byte(`
apiVersion: v1
kind: List
items:
- apiVersion: v1
kind: ConfigMap
metadata:
name: winnie
- apiVersion: v1
kind: ConfigMap
metadata:
name: winnie
`),
exp: expected{
out: []map[string]interface{}{
testConfigMap,
testConfigMap},
},
},
"ConfigMapList": {
input: []byte(`
apiVersion: v1
kind: ConfigMapList
items:
- apiVersion: v1
kind: ConfigMap
metadata:
name: winnie
- apiVersion: v1
kind: ConfigMap
metadata:
name: winnie
`),
exp: expected{
out: []map[string]interface{}{testConfigMapList},
},
},
"listWithAnchors": {
input: []byte(`
apiVersion: v1
kind: DeploymentList
items:
- apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-a
spec: &hostAliases
template:
spec:
hostAliases:
- hostnames:
- a.example.com
ip: 8.8.8.8
- apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-b
spec:
<<: *hostAliases
`),
exp: expected{
out: []map[string]interface{}{testDeploymentList},
},
},
}
for n := range testCases {
tc := testCases[n]
t.Run(n, func(t *testing.T) {
rs, err := factory.SliceFromBytes(tc.input)
if err != nil {
assert.True(t, tc.exp.isErr)
return
}
assert.False(t, tc.exp.isErr)
assert.Equal(t, len(tc.exp.out), len(rs))
for i := range rs {
assert.Equal(
t, fmt.Sprintf("%v", tc.exp.out[i]), fmt.Sprintf("%v", rs[i].Map()))
if n != "listWithAnchors" {
// https://github.com/kubernetes-sigs/kustomize/issues/3271
if !reflect.DeepEqual(tc.exp.out[i], rs[i].Map()) {
t.Fatalf("%s:\nexpected: %v\n actual: %v",
n, tc.exp.out[i], rs[i].Map())
}
}
}
})
}
}

View File

@@ -4,7 +4,9 @@
package wrappy
import (
"fmt"
"log"
"strings"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/resid"
@@ -29,6 +31,14 @@ func NewWNode() *WNode {
return FromRNode(yaml.NewRNode(nil))
}
func FromMap(m map[string]interface{}) (*WNode, error) {
n, err := yaml.FromMap(m)
if err != nil {
return nil, err
}
return FromRNode(n), nil
}
func FromRNode(node *yaml.RNode) *WNode {
return &WNode{node: node}
}
@@ -54,10 +64,41 @@ func (wn *WNode) GetAnnotations() map[string]string {
// GetFieldValue implements ifc.Kunstructured.
func (wn *WNode) GetFieldValue(path string) (interface{}, error) {
// The argument is a json path, e.g. "metadata.name"
// fields := strings.Split(path, ".")
// return wn.node.Pipe(yaml.Lookup(fields...))
panic("TODO(#WNode): GetFieldValue; implement or drop from API")
fields := strings.Split(path, ".")
rn, err := wn.node.Pipe(yaml.Lookup(fields...))
if err != nil {
return nil, err
}
if rn == nil {
return nil, NoFieldError{path}
}
yn := rn.YNode()
// If this is an alias node, resolve it
if yn.Kind == yaml.AliasNode {
yn = yn.Alias
}
// Return value as map for DocumentNode and MappingNode kinds
if yn.Kind == yaml.DocumentNode || yn.Kind == yaml.MappingNode {
var result map[string]interface{}
if err := yn.Decode(&result); err != nil {
return nil, err
}
return result, err
}
// Return value as slice for SequenceNode kind
if yn.Kind == yaml.SequenceNode {
var result []interface{}
for _, node := range yn.Content {
result = append(result, node.Value)
}
return result, nil
}
// Return value value directly for all other (ScalarNode) kinds
return yn.Value, nil
}
// GetGvk implements ifc.Kunstructured.
@@ -83,18 +124,37 @@ func (wn *WNode) GetName() string {
}
// GetSlice implements ifc.Kunstructured.
func (wn *WNode) GetSlice(string) ([]interface{}, error) {
panic("TODO(#WNode) GetSlice; implement or drop from API")
func (wn *WNode) GetSlice(path string) ([]interface{}, error) {
value, err := wn.GetFieldValue(path)
if err != nil {
return nil, err
}
if sliceValue, ok := value.([]interface{}); ok {
return sliceValue, nil
}
return nil, fmt.Errorf("node %s is not a slice", path)
}
// GetSlice implements ifc.Kunstructured.
func (wn *WNode) GetString(string) (string, error) {
panic("TODO(#WNode) GetString; implement or drop from API")
func (wn *WNode) GetString(path string) (string, error) {
value, err := wn.GetFieldValue(path)
if err != nil {
return "", err
}
if v, ok := value.(string); ok {
return v, nil
}
return "", fmt.Errorf("node %s is not a string: %v", path, value)
}
// Map implements ifc.Kunstructured.
func (wn *WNode) Map() map[string]interface{} {
panic("TODO(#WNode) Map; implement or drop from API")
var result map[string]interface{}
if err := wn.node.YNode().Decode(&result); err != nil {
// Log and die since interface doesn't allow error.
log.Fatalf("failed to decode ynode: %v", err)
}
return result
}
// MarshalJSON implements ifc.Kunstructured.
@@ -103,41 +163,65 @@ func (wn *WNode) MarshalJSON() ([]byte, error) {
}
// MatchesAnnotationSelector implements ifc.Kunstructured.
func (wn *WNode) MatchesAnnotationSelector(string) (bool, error) {
panic("TODO(#WNode) MatchesAnnotationSelector; implement or drop from API")
func (wn *WNode) MatchesAnnotationSelector(selector string) (bool, error) {
return wn.node.MatchesAnnotationSelector(selector)
}
// MatchesLabelSelector implements ifc.Kunstructured.
func (wn *WNode) MatchesLabelSelector(string) (bool, error) {
panic("TODO(#WNode) MatchesLabelSelector; implement or drop from API")
func (wn *WNode) MatchesLabelSelector(selector string) (bool, error) {
return wn.node.MatchesLabelSelector(selector)
}
// SetAnnotations implements ifc.Kunstructured.
func (wn *WNode) SetAnnotations(map[string]string) {
panic("TODO(#WNode) SetAnnotations; implement or drop from API")
func (wn *WNode) SetAnnotations(annotations map[string]string) {
if err := wn.node.SetAnnotations(annotations); err != nil {
log.Fatal(err) // interface doesn't allow error.
}
}
// SetGvk implements ifc.Kunstructured.
func (wn *WNode) SetGvk(resid.Gvk) {
panic("TODO(#WNode) SetGvk; implement or drop from API")
func (wn *WNode) SetGvk(gvk resid.Gvk) {
wn.setMapField(yaml.NewScalarRNode(gvk.Kind), yaml.KindField)
wn.setMapField(
yaml.NewScalarRNode(
fmt.Sprintf("%s/%s", gvk.Group, gvk.Version)), yaml.APIVersionField)
}
// SetLabels implements ifc.Kunstructured.
func (wn *WNode) SetLabels(map[string]string) {
panic("TODO(#WNode) SetLabels; implement or drop from API")
func (wn *WNode) SetLabels(labels map[string]string) {
if err := wn.node.SetLabels(labels); err != nil {
log.Fatal(err) // interface doesn't allow error.
}
}
// SetName implements ifc.Kunstructured.
func (wn *WNode) SetName(string) {
panic("TODO(#WNode) SetName; implement or drop from API")
func (wn *WNode) SetName(name string) {
wn.setMapField(yaml.NewScalarRNode(name), yaml.MetadataField, yaml.NameField)
}
// SetNamespace implements ifc.Kunstructured.
func (wn *WNode) SetNamespace(string) {
panic("TODO(#WNode) SetNamespace; implement or drop from API")
func (wn *WNode) SetNamespace(ns string) {
if err := wn.node.SetNamespace(ns); err != nil {
log.Fatal(err) // interface doesn't allow error.
}
}
func (wn *WNode) setMapField(value *yaml.RNode, path ...string) {
if err := wn.node.SetMapField(value, path...); err != nil {
// Log and die since interface doesn't allow error.
log.Fatalf("failed to set field %v: %v", path, err)
}
}
// UnmarshalJSON implements ifc.Kunstructured.
func (wn *WNode) UnmarshalJSON(data []byte) error {
return wn.node.UnmarshalJSON(data)
}
type NoFieldError struct {
Field string
}
func (e NoFieldError) Error() string {
return fmt.Sprintf("no field named '%s'", e.Field)
}

View File

@@ -1,14 +1,15 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package wrappy_test
package wrappy
import (
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"gopkg.in/yaml.v3"
. "sigs.k8s.io/kustomize/api/internal/wrappy"
"sigs.k8s.io/kustomize/api/resid"
kyaml "sigs.k8s.io/kustomize/kyaml/yaml"
)
@@ -337,3 +338,215 @@ func TestGettingFields(t *testing.T) {
t.Fatalf("unexpected annotations '%v'", actualMap)
}
}
func TestGetFieldValueReturnsMap(t *testing.T) {
wn := NewWNode()
if err := wn.UnmarshalJSON([]byte(deploymentBiggerJson)); err != nil {
t.Fatalf("unexpected unmarshaljson err: %v", err)
}
expected := map[string]interface{}{
"fruit": "apple",
"veggie": "carrot",
}
actual, err := wn.GetFieldValue("metadata.labels")
if err != nil {
t.Fatalf("error getting field value: %v", err)
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("actual map does not deep equal expected map:\n%v", diff)
}
}
func TestGetFieldValueReturnsSlice(t *testing.T) {
bytes, err := yaml.Marshal(makeBigMap())
if err != nil {
t.Fatalf("unexpected yaml.Marshal err: %v", err)
}
rNode, err := kyaml.Parse(string(bytes))
if err != nil {
t.Fatalf("unexpected yaml.Marshal err: %v", err)
}
wn := FromRNode(rNode)
expected := []interface{}{"idx0", "idx1", "idx2", "idx3"}
actual, err := wn.GetFieldValue("that")
if err != nil {
t.Fatalf("error getting slice: %v", err)
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("actual slice does not deep equal expected slice:\n%v", diff)
}
}
func TestGetFieldValueReturnsString(t *testing.T) {
wn := NewWNode()
if err := wn.UnmarshalJSON([]byte(deploymentBiggerJson)); err != nil {
t.Fatalf("unexpected unmarshaljson err: %v", err)
}
actual, err := wn.GetFieldValue("metadata.labels.fruit")
if err != nil {
t.Fatalf("error getting field value: %v", err)
}
v, ok := actual.(string)
if !ok || v != "apple" {
t.Fatalf("unexpected value '%v'", actual)
}
}
func TestGetFieldValueResolvesAlias(t *testing.T) {
yamlWithAlias := `
foo: &a theValue
bar: *a
`
rNode, err := kyaml.Parse(yamlWithAlias)
if err != nil {
t.Fatalf("unexpected yaml parse error: %v", err)
}
wn := FromRNode(rNode)
actual, err := wn.GetFieldValue("bar")
if err != nil {
t.Fatalf("error getting field value: %v", err)
}
v, ok := actual.(string)
if !ok || v != "theValue" {
t.Fatalf("unexpected value '%v'", actual)
}
}
func TestGetString(t *testing.T) {
wn := NewWNode()
if err := wn.UnmarshalJSON([]byte(deploymentBiggerJson)); err != nil {
t.Fatalf("unexpected unmarshaljson err: %v", err)
}
expected := "carrot"
actual, err := wn.GetString("metadata.labels.veggie")
if err != nil {
t.Fatalf("error getting string: %v", err)
}
if expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
}
func TestGetSlice(t *testing.T) {
bytes, err := yaml.Marshal(makeBigMap())
if err != nil {
t.Fatalf("unexpected yaml.Marshal err: %v", err)
}
rNode, err := kyaml.Parse(string(bytes))
if err != nil {
t.Fatalf("unexpected yaml.Marshal err: %v", err)
}
wn := FromRNode(rNode)
expected := []interface{}{"idx0", "idx1", "idx2", "idx3"}
actual, err := wn.GetSlice("that")
if err != nil {
t.Fatalf("error getting slice: %v", err)
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("actual slice does not deep equal expected slice:\n%v", diff)
}
}
func TestMap(t *testing.T) {
wn := NewWNode()
if err := wn.UnmarshalJSON([]byte(deploymentLittleJson)); err != nil {
t.Fatalf("unexpected unmarshaljson err: %v", err)
}
expected := map[string]interface{}{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": map[string]interface{}{
"name": "homer",
"namespace": "simpsons",
},
}
actual := wn.Map()
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("actual map does not deep equal expected map:\n%v", diff)
}
}
func TestSetName(t *testing.T) {
wn := NewWNode()
if err := wn.UnmarshalJSON([]byte(deploymentBiggerJson)); err != nil {
t.Fatalf("unexpected unmarshaljson err: %v", err)
}
wn.SetName("marge")
if expected, actual := "marge", wn.GetName(); expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
}
func TestSetNamespace(t *testing.T) {
wn := NewWNode()
if err := wn.UnmarshalJSON([]byte(deploymentBiggerJson)); err != nil {
t.Fatalf("unexpected unmarshaljson err: %v", err)
}
wn.SetNamespace("flanders")
meta, _ := wn.node.GetMeta()
if expected, actual := "flanders", meta.Namespace; expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
}
func TestSetLabels(t *testing.T) {
wn := NewWNode()
if err := wn.UnmarshalJSON([]byte(deploymentBiggerJson)); err != nil {
t.Fatalf("unexpected unmarshaljson err: %v", err)
}
wn.SetLabels(map[string]string{
"label1": "foo",
"label2": "bar",
})
labels := wn.GetLabels()
if expected, actual := 2, len(labels); expected != actual {
t.Fatalf("expected '%d', got '%d'", expected, actual)
}
if expected, actual := "foo", labels["label1"]; expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
if expected, actual := "bar", labels["label2"]; expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
}
func TestGetAnnotations(t *testing.T) {
wn := NewWNode()
if err := wn.UnmarshalJSON([]byte(deploymentBiggerJson)); err != nil {
t.Fatalf("unexpected unmarshaljson err: %v", err)
}
wn.SetAnnotations(map[string]string{
"annotation1": "foo",
"annotation2": "bar",
})
annotations := wn.GetAnnotations()
if expected, actual := 2, len(annotations); expected != actual {
t.Fatalf("expected '%d', got '%d'", expected, actual)
}
if expected, actual := "foo", annotations["annotation1"]; expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
if expected, actual := "bar", annotations["annotation2"]; expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
}
func TestSetGvk(t *testing.T) {
wn := NewWNode()
if err := wn.UnmarshalJSON([]byte(deploymentBiggerJson)); err != nil {
t.Fatalf("unexpected unmarshaljson err: %v", err)
}
wn.SetGvk(resid.GvkFromString("grp_ver_knd"))
gvk := wn.GetGvk()
if expected, actual := "grp", gvk.Group; expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
if expected, actual := "ver", gvk.Version; expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
if expected, actual := "knd", gvk.Kind; expected != actual {
t.Fatalf("expected '%s', got '%s'", expected, actual)
}
}

View File

@@ -14,6 +14,7 @@ import (
"k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/internal/k8sdeps/configmapandsecret"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/types"
)
@@ -116,10 +117,6 @@ func (kf *KunstructuredFactoryImpl) validate(u unstructured.Unstructured) error
return nil
}
// nonKustomizableResourceAnnotation if set on a Resource will cause Kustomize to
// ignore the Resource rather than Kustomize it.
const ignoredByKustomizeResourceAnnotation = "config.kubernetes.io/local-config"
// skipResource returns true if the Resource should not be accumulated
func (kf *KunstructuredFactoryImpl) skipResource(u unstructured.Unstructured) bool {
an := u.GetAnnotations()
@@ -128,7 +125,7 @@ func (kf *KunstructuredFactoryImpl) skipResource(u unstructured.Unstructured) bo
return false
}
// check if the Resource has opt-ed out of kustomize
_, found := an[ignoredByKustomizeResourceAnnotation]
_, found := an[konfig.IgnoredByKustomizeResourceAnnotation]
return found
}

View File

@@ -238,6 +238,8 @@ nameReference:
kind: Ingress
- path: metadata/annotations/nginx.ingress.kubernetes.io\/auth-tls-secret
kind: Ingress
- path: spec/tls/secretName
kind: Ingress
- path: imagePullSecrets/name
kind: ServiceAccount
- path: parameters/secretName
@@ -256,6 +258,8 @@ nameReference:
kind: Service
group: serving.knative.dev
version: v1
- path: spec/azureFile/secretName
kind: PersistentVolume
- kind: Service
version: v1
@@ -267,6 +271,10 @@ nameReference:
kind: Ingress
- path: spec/backend/serviceName
kind: Ingress
- path: spec/rules/http/paths/backend/service/name
kind: Ingress
- path: spec/defaultBackend/service/name
kind: Ingress
- path: spec/service/name
kind: APIService
group: apiregistration.k8s.io
@@ -373,5 +381,12 @@ nameReference:
kind: Job
- path: spec/template/spec/priorityClassName
kind: DaemonSet
- kind: IngressClass
version: v1
group: networking.k8s.io/v1
fieldSpecs:
- path: spec/ingressClassName
kind: Ingress
`
)

View File

@@ -8,6 +8,9 @@ const (
namespace:
- path: metadata/namespace
create: true
- path: metadata/name
kind: Namespace
create: true
- path: subjects
kind: RoleBinding
- path: subjects

View File

@@ -87,6 +87,9 @@ varReference:
- path: spec/template/spec/volumes/nfs/server
kind: Deployment
- path: spec/template/metadata/annotations
kind: Deployment
- path: spec/rules/host
kind: Ingress

View File

@@ -19,7 +19,32 @@ func DefaultKustomizationFileName() string {
return RecognizedKustomizationFileNames()[0]
}
// IfApiMachineryElseKyaml returns true if executing the apimachinery code
// path, else we're executing the kyaml code paths.
func IfApiMachineryElseKyaml(s1, s2 string) string {
if !FlagEnableKyamlDefaultValue {
return s1
}
return s2
}
const (
// FlagEnableKyamlDefaultValue is the default value for the --enable_kyaml
// flag. This value is also used in unit tests. See provider.DepProvider.
//
// TODO(#3304): eliminate branching on this constant.
// Details: https://github.com/kubernetes-sigs/kustomize/issues/3304
//
// All tests should pass for either true or false values
// of this constant, without having to check its value.
// In the cases where there's a different outcome, either decide
// that the difference is acceptable, or make the difference go away.
//
// Historically, tests passed for enable_kyaml == false, i.e. using
// apimachinery libs. This doesn't mean the code was better, it just
// means regression tests preserved those outcomes.
FlagEnableKyamlDefaultValue = false
// An environment variable to consult for kustomization
// configuration data. See:
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
@@ -31,6 +56,9 @@ const (
// A program name, for use in help, finding the XDG_CONFIG_DIR, etc.
ProgramName = "kustomize"
// If a resource has this annotation, kustomize will drop it.
IgnoredByKustomizeResourceAnnotation = "config.kubernetes.io/local-config"
// Label key that indicates the resources are built from Kustomize
ManagedbyLabelKey = "app.kubernetes.io/managed-by"

View File

@@ -9,6 +9,7 @@ import (
"runtime"
"sigs.k8s.io/kustomize/api/filesys"
"sigs.k8s.io/kustomize/api/internal/plugins/builtinhelpers"
"sigs.k8s.io/kustomize/api/types"
)
@@ -157,3 +158,15 @@ func pwdEnv() string {
}
return "PWD"
}
// GetBuiltinPluginNames returns a list of builtin plugin names
func GetBuiltinPluginNames() []string {
var ret []string
for k := range builtinhelpers.GeneratorFactories {
ret = append(ret, k.String())
}
for k := range builtinhelpers.TransformerFactories {
ret = append(ret, k.String())
}
return ret
}

View File

@@ -225,13 +225,13 @@ spec:
spec:
containers:
- env:
- name: foo
value: bar
- name: FOO
valueFrom:
configMapKeyRef:
key: somekey
name: test-infra-app-env-8h5mh7f7ch
- name: foo
value: bar
image: nginx:1.8.0
name: nginx
ports:

View File

@@ -464,3 +464,50 @@ metadata:
name: another-namespace
`)
}
func TestFnContainerEnvVars(t *testing.T) {
skipIfNoDocker(t)
th := kusttest_test.MakeEnhancedHarness(t)
defer th.Reset()
th.WriteK("/app", `
generators:
- gener.yaml
`)
// TODO: cheange image to gcr.io/kpt-functions/templater:stable
// when https://github.com/GoogleContainerTools/kpt-functions-catalog/pull/103
// is merged
th.WriteF("/app/gener.yaml", `
apiVersion: v1
kind: ConfigMap
metadata:
name: demo
annotations:
config.kubernetes.io/function: |
container:
image: quay.io/aodinokov/kpt-templater:0.0.1
envs:
- TESTTEMPLATE=value
data:
template: |
apiVersion: v1
kind: ConfigMap
metadata:
name: env
data:
value: '{{ env "TESTTEMPLATE" }}'
`)
m := th.Run("/app", th.MakeOptionsPluginsEnabled())
th.AssertActualEqualsExpected(m, `
apiVersion: v1
data:
value: value
kind: ConfigMap
metadata:
annotations:
config.kubernetes.io/path: configmap_env.yaml
name: env
`)
}

View File

@@ -385,12 +385,12 @@ spec:
- gcePersistentDisk:
pdName: nginx-persistent-storage
name: nginx-persistent-storage
- configMap:
name: staging-team-foo-configmap-in-base-hc6g9dk6g9
name: configmap-in-base
- configMap:
name: staging-configmap-in-overlay-dc6fm46dhm
name: configmap-in-overlay
- configMap:
name: staging-team-foo-configmap-in-base-hc6g9dk6g9
name: configmap-in-base
---
apiVersion: v1
kind: Service

View File

@@ -0,0 +1,622 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package krusty_test
import (
"testing"
"github.com/stretchr/testify/assert"
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
)
// Regression test for https://github.com/kubernetes-sigs/kustomize/issues/3280
// GVKN shouldn't change with default options
func TestKeepOriginalGVKN(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("apps/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteF("apps/patch.yaml", `
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: new-name
`)
th.WriteK("apps", `
resources:
- deployment.yaml
patches:
- path: patch.yaml
target:
kind: Deployment
`)
m := th.Run("apps", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- image: nginx
name: nginx
`)
}
// https://github.com/kubernetes-sigs/kustomize/issues/3280
// These tests document behavior that will change
func TestChangeName(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("apps/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteF("apps/patch.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: new-name
`)
th.WriteK("apps", `
resources:
- deployment.yaml
patches:
- path: patch.yaml
target:
kind: Deployment
`)
options := th.MakeDefaultOptions()
options.AllowResourceIdChanges = true
// name should become `new-name`
m := th.Run("apps", options)
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- image: nginx
name: nginx
`)
}
func TestChangeKind(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("apps/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteF("apps/patch.yaml", `
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: old-name
`)
th.WriteK("apps", `
resources:
- deployment.yaml
patches:
- path: patch.yaml
target:
kind: Deployment
`)
options := th.MakeDefaultOptions()
options.AllowResourceIdChanges = true
// kind should become `StatefulSet`
m := th.Run("apps", options)
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- image: nginx
name: nginx
`)
}
func TestChangeNameAndKind(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("apps/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteF("apps/patch.yaml", `
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: new-name
`)
th.WriteK("apps", `
resources:
- deployment.yaml
patches:
- path: patch.yaml
target:
kind: Deployment
`)
options := th.MakeDefaultOptions()
options.AllowResourceIdChanges = true
// kind should become `StatefulSet`
// name should become `new-name`
m := th.Run("apps", options)
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- image: nginx
name: nginx
`)
}
// https://github.com/kubernetes-sigs/kustomize/issues/3280
// Should be able to refer to a resource with either its
// original GVKN or its current one
func TestPatchOriginalName(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("base/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteF("base/patch.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: new-name
`)
th.WriteK("base", `
resources:
- deployment.yaml
patches:
- path: patch.yaml
target:
kind: Deployment
`)
th.WriteK("overlay", `
resources:
- ../base
patchesStrategicMerge:
- depPatch.yaml
`)
th.WriteF("overlay/depPatch.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
replicas: 999
`)
options := th.MakeDefaultOptions()
options.AllowResourceIdChanges = true
// name should become `new-name`
m := th.Run("overlay", options)
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
replicas: 999
template:
spec:
containers:
- image: nginx
name: nginx
`)
}
func TestPatchNewName(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("base/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteF("base/patch.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: new-name
`)
th.WriteK("base", `
resources:
- deployment.yaml
patches:
- path: patch.yaml
target:
kind: Deployment
`)
th.WriteK("overlay", `
resources:
- ../base
patchesStrategicMerge:
- depPatch.yaml
`)
th.WriteF("overlay/depPatch.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: new-name
spec:
replicas: 999
`)
options := th.MakeDefaultOptions()
options.AllowResourceIdChanges = true
// depPatch cannot find target with the name `new-name`
// because base/patch.yaml can't yet edit the name
assert.Error(t, th.RunWithErr("overlay", options))
}
func TestPatchOriginalNameAndKind(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("base/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteF("base/patch.yaml", `
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: new-name
`)
th.WriteK("base", `
resources:
- deployment.yaml
patches:
- path: patch.yaml
target:
kind: Deployment
`)
th.WriteK("overlay", `
resources:
- ../base
patchesStrategicMerge:
- depPatch.yaml
`)
th.WriteF("overlay/depPatch.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
replicas: 999
`)
options := th.MakeDefaultOptions()
options.AllowResourceIdChanges = true
// kind should become `StatefulSet`
// name should become `new-name`
m := th.Run("overlay", options)
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
replicas: 999
template:
spec:
containers:
- image: nginx
name: nginx
`)
}
func TestPatchNewNameAndKind(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("base/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteF("base/patch.yaml", `
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: new-name
`)
th.WriteK("base", `
resources:
- deployment.yaml
patches:
- path: patch.yaml
target:
kind: Deployment
`)
th.WriteK("overlay", `
resources:
- ../base
patchesStrategicMerge:
- depPatch.yaml
`)
th.WriteF("overlay/depPatch.yaml", `
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: new-name
spec:
replicas: 999
`)
options := th.MakeDefaultOptions()
options.AllowResourceIdChanges = true
// depPatch cannot find target with kind `StatefulSet` and name `new-name`
// because base/patch.yaml can't yet edit the kind or name
assert.Error(t, th.RunWithErr("overlay", options))
}
// Use original name, but new kind
// Should fail, even after #3280 is done, because this ID is invalid
func TestPatchOriginalNameAndNewKind(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("base/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: old-name
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteF("base/patch.yaml", `
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: new-name
`)
th.WriteK("base", `
resources:
- deployment.yaml
patches:
- path: patch.yaml
target:
kind: Deployment
`)
th.WriteK("overlay", `
resources:
- ../base
patchesStrategicMerge:
- depPatch.yaml
`)
th.WriteF("overlay/depPatch.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: new-name
spec:
replicas: 999
`)
options := th.MakeDefaultOptions()
options.AllowResourceIdChanges = true
// depPatch cannot find target with kind `Deployment` and name `new-name`
// because the resource never had this GVKN
assert.Error(t, th.RunWithErr("overlay", options))
}
// Here is a structure of a kustomization of two components, component1
// and component2, that both use a shared deployment definition, which
// component2 adjusts by changing the kind via a patch. This test case
// checks that it does not have a conflicting definition.
// Currently documents broken behavior.
//
// root
// / \
// component1/overlay component2/overlay
// | |
// component1/base component2/base
// \ /
// base
//
// This is the directory layout:
//
// ├── component1
// │ ├── base
// │ │ └── kustomization.yaml
// │ └── overlay
// │ └── kustomization.yaml
// ├── component2
// │ ├── base
// │ │ └── kustomization.yaml
// │ └── overlay
// │ └── kustomization.yaml
// ├── shared
// │ ├── kustomization.yaml
// │ └── deployment.yaml
// ├── kustomization.yaml
func TestBaseReuseNameAndKindConflict(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteK("/app/shared", `
resources:
- deployment.yaml
`)
th.WriteF("/app/shared/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-deploy
spec:
template:
spec:
containers:
- name: nginx
image: nginx
`)
th.WriteK("/app/component1/base", `
resources:
- ../../shared
`)
th.WriteK("/app/component1/overlay", `
resources:
- ../base
namePrefix: overlay-
`)
th.WriteK("/app/component2/base", `
resources:
- ../../shared
patches:
- path: patch.yaml
target:
kind: Deployment
name: my-deploy
`)
th.WriteF("/app/component2/base/patch.yaml", `
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: my-stateful-set
`)
th.WriteK("/app/component2/overlay", `
resources:
- ../base
namePrefix: overlay-
`)
th.WriteK("/app", `
resources:
- component1/overlay
- component2/overlay
`)
options := th.MakeDefaultOptions()
options.AllowResourceIdChanges = true
// Error occurs when app/component2/base tries to load the shared resources
// because the kind is not (yet) allowed to change yet
// so it loads a second Deployment with the name my-deploy
// instead of a StatefulSet as specified by the patch.
// Will be fixed by #3280.
assert.Error(t, th.RunWithErr("overlay", options))
}

View File

@@ -0,0 +1,103 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package krusty_test
/*
import (
"testing"
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
)
var expected string = `
apiVersion: v1
data:
rcon-password: Q0hBTkdFTUUh
kind: Secret
metadata:
labels:
app: test-minecraft
chart: minecraft-1.2.0
heritage: Helm
release: test
name: test-minecraft
type: Opaque
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
annotations:
volume.alpha.kubernetes.io/storage-class: default
labels:
app: test-minecraft
chart: minecraft-1.2.0
heritage: Helm
release: test
name: test-minecraft-datadir
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
---
apiVersion: v1
kind: Service
metadata:
labels:
app: test-minecraft
chart: minecraft-1.2.0
heritage: Helm
release: test
name: test-minecraft
spec:
ports:
- name: minecraft
port: 25565
protocol: TCP
targetPort: minecraft
selector:
app: test-minecraft
type: LoadBalancer
`
func TestHelmChartInflationGenerator(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteK("/app", `
helmChartInflationGenerator:
- chartName: minecraft
chartRepoUrl: https://kubernetes-charts.storage.googleapis.com
chartVersion: v1.2.0
releaseName: test
releaseNamespace: testNamespace
`)
m := th.Run("/app", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, expected)
}
func TestHelmChartInflationGeneratorAsPlugin(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteK("/app", `
generators:
- helm.yaml
`)
th.WriteF("/app/helm.yaml", `
apiVersion: builtin
kind: HelmChartInflationGenerator
metadata:
name: myMap
chartName: minecraft
chartRepoUrl: https://kubernetes-charts.storage.googleapis.com
chartVersion: v1.2.0
releaseName: test
releaseNamespace: testNamespace
`)
m := th.Run("/app", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, expected)
}
*/

View File

@@ -0,0 +1,79 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package krusty_test
import (
"testing"
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
)
func TestInlineTransformer(t *testing.T) {
th := kusttest_test.MakeEnhancedHarness(t)
defer th.Reset()
th.WriteF("/app/resource.yaml", `
apiVersion: apps/v1
kind: ConfigMap
metadata:
name: whatever
data: {}
`)
th.WriteK("/app", `
resources:
- resource.yaml
transformers:
- |-
apiVersion: builtin
kind: NamespaceTransformer
metadata:
name: not-important-to-example
namespace: test
fieldSpecs:
- path: metadata/namespace
create: true
`)
expected := `
apiVersion: apps/v1
data: {}
kind: ConfigMap
metadata:
name: whatever
namespace: test
`
m := th.Run("/app", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, expected)
}
func TestInlineGenerator(t *testing.T) {
th := kusttest_test.MakeEnhancedHarness(t)
defer th.Reset()
th.WriteK("/app", `
generators:
- |-
apiVersion: builtin
kind: ConfigMapGenerator
metadata:
name: mymap
literals:
- FRUIT=apple
- VEGETABLE=carrot
`)
expected := `
apiVersion: v1
data:
FRUIT: apple
VEGETABLE: carrot
kind: ConfigMap
metadata:
name: mymap-kfd8tf729k
`
m := th.Run("/app", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, expected)
}

View File

@@ -0,0 +1,106 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package krusty_test
import (
"testing"
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
)
func writeIssueBase(th kusttest_test.Harness) {
th.WriteK("base", `
nameSuffix: -test-api
resources:
- deploy.yaml
`)
th.WriteF("base/deploy.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: example
spec:
template:
spec:
containers:
- name: example
image: example:1.0
volumeMounts:
- name: conf
mountPath: /etc/config
volumes:
- name: conf
configMap:
name: conf
`)
}
func TestIssue2896Base(t *testing.T) {
th := kusttest_test.MakeHarness(t)
writeIssueBase(th)
m := th.Run("base", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: example-test-api
spec:
template:
spec:
containers:
- image: example:1.0
name: example
volumeMounts:
- mountPath: /etc/config
name: conf
volumes:
- configMap:
name: conf
name: conf
`)
}
func TestIssue2896Overlay(t *testing.T) {
th := kusttest_test.MakeHarness(t)
writeIssueBase(th)
th.WriteK("overlay", `
resources:
- ../base
patches:
- patch: |-
apiVersion: apps/v1
kind: Deployment
metadata:
name: example
spec:
template:
spec:
containers:
- name: example
image: example:2.0
`)
m := th.Run("overlay", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: example-test-api
spec:
template:
spec:
containers:
- image: example:2.0
name: example
volumeMounts:
- mountPath: /etc/config
name: conf
volumes:
- configMap:
name: conf
name: conf
`)
}

View File

@@ -0,0 +1,57 @@
package krusty_test
import (
"testing"
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
)
func TestKustomizationMetadata(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("/app/resources.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: testing123
spec:
replicas: 1
selector: null
template:
spec:
containers:
- name: event
image: testing123
imagePullPolicy: IfNotPresent
imagePullSecrets: []`)
th.WriteK("/app", `
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
metadata:
annotations:
config.kubernetes.io/local-config: "true"
labels:
foo: bar
name: test_kustomization
resources:
- resources.yaml
`)
m := th.Run("/app", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: testing123
spec:
replicas: 1
selector: null
template:
spec:
containers:
- image: testing123
imagePullPolicy: IfNotPresent
name: event
imagePullSecrets: []
`)
}

View File

@@ -11,9 +11,9 @@ import (
pLdr "sigs.k8s.io/kustomize/api/internal/plugins/loader"
"sigs.k8s.io/kustomize/api/internal/target"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/krusty/internal/provider"
fLdr "sigs.k8s.io/kustomize/api/loader"
"sigs.k8s.io/kustomize/api/provenance"
"sigs.k8s.io/kustomize/api/provider"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/types"
)
@@ -53,7 +53,7 @@ func MakeKustomizer(fSys filesys.FileSystem, o *Options) *Kustomizer {
func (b *Kustomizer) Run(path string) (resmap.ResMap, error) {
resmapFactory := resmap.NewFactory(
b.depProvider.GetResourceFactory(),
b.depProvider.GetMerginator())
b.depProvider.GetConflictDetectorFactory())
lr := fLdr.RestrictionNone
if b.options.LoadRestrictions == types.LoadRestrictionsRootOnly {
lr = fLdr.RestrictionRootOnly
@@ -85,7 +85,7 @@ func (b *Kustomizer) Run(path string) (resmap.ResMap, error) {
t := builtins.LabelTransformerPlugin{
Labels: map[string]string{
konfig.ManagedbyLabelKey: fmt.Sprintf(
"kustomize-%s", provenance.GetProvenance().Version)},
"kustomize-%s", provenance.GetProvenance().Semver())},
FieldSpecs: []types.FieldSpec{{
Path: "metadata/labels",
CreateIfNotPresent: true,

View File

@@ -146,12 +146,12 @@ spec:
- gcePersistentDisk:
pdName: nginx-persistent-storage
name: nginx-persistent-storage
- configMap:
name: a-b-configmap-in-base-798k5k7g9f
name: configmap-in-base
- configMap:
name: a-configmap-in-overlay-dc6fm46dhm
name: configmap-in-overlay
- configMap:
name: a-b-configmap-in-base-798k5k7g9f
name: configmap-in-base
---
apiVersion: v1
kind: Service
@@ -351,12 +351,12 @@ spec:
- gcePersistentDisk:
pdName: nginx-persistent-storage
name: nginx-persistent-storage
- configMap:
name: staging-team-foo-configmap-in-base-798k5k7g9f
name: configmap-in-base
- configMap:
name: staging-configmap-in-overlay-dc6fm46dhm
name: configmap-in-overlay
- configMap:
name: staging-team-foo-configmap-in-base-798k5k7g9f
name: configmap-in-base
---
apiVersion: v1
kind: Service

View File

@@ -159,7 +159,7 @@ subjects:
name: default
namespace: irrelevant
---
apiVersion: admissionregistration.k8s.io/v1beta1
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: example
@@ -180,15 +180,17 @@ webhooks:
name: svc3
namespace: random
---
apiVersion: apiextensions.k8s.io/v1beta1
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: crds.my.org
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cr1
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: crb1
@@ -197,6 +199,7 @@ subjects:
name: default
namespace: irrelevant
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv1
@@ -257,7 +260,7 @@ subjects:
name: default
namespace: newnamespace
---
apiVersion: admissionregistration.k8s.io/v1beta1
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: p1-example-s1
@@ -278,15 +281,17 @@ webhooks:
namespace: random
name: example3
---
apiVersion: apiextensions.k8s.io/v1beta1
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: crds.my.org
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: p1-cr1-s1
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: p1-crb1-s1
@@ -295,6 +300,7 @@ subjects:
name: default
namespace: newnamespace
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: p1-pv1-s1

View File

@@ -0,0 +1,287 @@
package krusty_test
import (
"testing"
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
)
// https://github.com/kubernetes-sigs/kustomize/issues/2640
func TestNameUpdateInRoleRef(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("/app/rbac.yaml", `
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: my-role
rules:
- apiGroups:
- '*'
resources:
- '*'
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: my-role
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: my-role
subjects:
- kind: ServiceAccount
name: default
namespace: foo
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: my-role
rules:
- apiGroups:
- ""
resources:
- secrets
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: my-role
roleRef:
apiGroup: rbac.authorization.k8s.io
version: v1
kind: Role
name: my-role
subjects:
- kind: ServiceAccount
name: default
`)
th.WriteK("/app", `
namespace: foo
resources:
- rbac.yaml
patches:
- patch: |-
- op: add
path: /metadata/name
value: prefix_my-role
target:
group: rbac.authorization.k8s.io
version: v1
kind: ClusterRole
name: my-role
`)
m := th.Run("/app", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: prefix_my-role
rules:
- apiGroups:
- '*'
resources:
- '*'
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: my-role
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: prefix_my-role
subjects:
- kind: ServiceAccount
name: default
namespace: foo
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: my-role
namespace: foo
rules:
- apiGroups:
- ""
resources:
- secrets
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: my-role
namespace: foo
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: my-role
version: v1
subjects:
- kind: ServiceAccount
name: default
namespace: foo
`)
}
// https://github.com/kubernetes-sigs/kustomize/issues/3073
func TestNameUpdateInRoleRef2(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("/app/workloads.yaml", `
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: myapp
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: myapp
rules:
- apiGroups:
- ""
resources:
- nodes/metrics
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: myapp
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: myapp
subjects:
- kind: ServiceAccount
name: myapp
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: myapp
rules:
- apiGroups:
- ""
resources:
- services
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: myapp
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: myapp
subjects:
- kind: ServiceAccount
name: myapp
`)
th.WriteF("/app/suffixTransformer.yaml", `
apiVersion: builtin
kind: PrefixSuffixTransformer
metadata:
name: notImportantHere
suffix: -suffix
fieldSpecs:
- path: metadata/name
kind: ClusterRole
name: myapp
- path: metadata/name
kind: ClusterRoleBinding
name: myapp
`)
th.WriteK("/app", `
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- workloads.yaml
transformers:
- suffixTransformer.yaml
namespace: test
`)
m := th.Run("/app", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: v1
kind: ServiceAccount
metadata:
name: myapp
namespace: test
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: myapp-suffix
rules:
- apiGroups:
- ""
resources:
- nodes/metrics
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: myapp-suffix
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: myapp-suffix
subjects:
- kind: ServiceAccount
name: myapp
namespace: test
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: myapp
namespace: test
rules:
- apiGroups:
- ""
resources:
- services
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: myapp
namespace: test
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: myapp
subjects:
- kind: ServiceAccount
name: myapp
namespace: test
`)
}

View File

@@ -9,7 +9,7 @@ import (
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
)
func TestNullValues(t *testing.T) {
func TestNullValues1(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("/app/deployment.yaml", `
apiVersion: apps/v1
@@ -62,3 +62,36 @@ spec:
name: example
`)
}
func TestNullValues2(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("deploy.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test
spec:
template:
spec:
containers:
- name: test
volumes: null
`)
th.WriteK(".", `
resources:
- deploy.yaml
`)
m := th.Run(".", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test
spec:
template:
spec:
containers:
- name: test
volumes: null
`)
}

View File

@@ -36,16 +36,21 @@ type Options struct {
// When true, use kyaml/ packages to manipulate KRM yaml.
// When false, use k8sdeps/ instead (uses k8s.io/api* packages).
UseKyaml bool
// When true, allow name and kind changing via a patch
// When false, patch name/kind don't overwrite target name/kind
AllowResourceIdChanges bool
}
// MakeDefaultOptions returns a default instance of Options.
func MakeDefaultOptions() *Options {
return &Options{
DoLegacyResourceSort: false,
AddManagedbyLabel: false,
LoadRestrictions: types.LoadRestrictionsRootOnly,
DoPrune: false,
PluginConfig: konfig.DisabledPluginConfig(),
UseKyaml: false,
DoLegacyResourceSort: false,
AddManagedbyLabel: false,
LoadRestrictions: types.LoadRestrictionsRootOnly,
DoPrune: false,
PluginConfig: konfig.DisabledPluginConfig(),
UseKyaml: false,
AllowResourceIdChanges: false,
}
}

View File

@@ -213,3 +213,132 @@ roleRef:
name: my-role-ns2
`)
}
// The ServiceAccount in subjects in role binding can be across namespace
// but the roleRef is not. This test is used to cover such case.
func TestRoleBindingWhenSubjectsAcrossNamespace(t *testing.T) {
th := kusttest_test.MakeEnhancedHarness(t)
defer th.Reset()
th.WriteK("/app", `
resources:
- ./ns1
- ./ns2
`)
th.WriteK("/app/ns1", `
namespace: namespace-1
resources:
- role-ns1.yaml
- rolebinding-ns1.yaml
`)
th.WriteF("/app/ns1/role-ns1.yaml", `
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: testRole
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get"]
`)
th.WriteF("/app/ns1/rolebinding-ns1.yaml", `
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: testRoleBinding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: testRole
subjects:
- kind: ServiceAccount
name: testAccount
namespace: namespace-2
`)
th.WriteK("/app/ns2", `
namespace: namespace-2
resources:
- role-ns2.yaml
- rolebinding-ns2.yaml
`)
th.WriteF("/app/ns2/role-ns2.yaml", `
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: testRole
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get"]
`)
th.WriteF("/app/ns2/rolebinding-ns2.yaml", `
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: testRoleBinding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: testRole
subjects:
- kind: ServiceAccount
name: testAccount
namespace: namespace-1
`)
m := th.Run("/app", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: testRole
namespace: namespace-1
rules:
- apiGroups:
- ""
resources:
- pods
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: testRoleBinding
namespace: namespace-1
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: testRole
subjects:
- kind: ServiceAccount
name: testAccount
namespace: namespace-2
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: testRole
namespace: namespace-2
rules:
- apiGroups:
- ""
resources:
- pods
verbs:
- get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: testRoleBinding
namespace: namespace-2
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: testRole
subjects:
- kind: ServiceAccount
name: testAccount
namespace: namespace-1
`)
}

View File

@@ -215,25 +215,25 @@ spec2:
template:
spec:
containers:
- image: nginx:v1
- image: nginx:v2
name: nginx3
- image: my-nginx:latest
- image: my-nginx:previous
name: nginx4
spec3:
template:
spec:
initContainers:
- image: postgres:alpine-9
- image: my-postgres:v3
name: postgresdb
- image: docker:17-git
- image: my-docker@sha256:25a0d4b4
name: init-docker
- image: myprivaterepohostname:1234/my/image:latest
- image: myprivaterepohostname:1234/my/image:v1.0.1
name: myImage
- image: myprivaterepohostname:1234/my/image
- image: myprivaterepohostname:1234/my/image:v1.0.1
name: myImage2
- image: my-app-image:v1
name: my-app
- image: gcr.io:8080/my-project/my-cool-app:latest
- image: my-cool-app:latest
name: my-cool-app
`)
}

View File

@@ -1969,3 +1969,70 @@ spec:
server: kustomized-nfs-server-service.default.srv.cluster.local
`)
}
func TestDeploymentAnnotations(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteK("/app", `
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
configMapGenerator:
- name: testConfigMap
envs:
- test.properties
vars:
- name: FOO
objref:
kind: ConfigMap
name: testConfigMap
apiVersion: v1
fieldref:
fieldpath: data.foo
commonAnnotations:
foo: $(FOO)
resources:
- deployment.yaml
`)
th.WriteF("/app/deployment.yaml", `
apiVersion: apps/v1
kind: Deployment
metadata:
name: test
spec:
template:
spec:
containers:
- name: test
`)
th.WriteF("/app/test.properties", `foo=bar`)
m := th.Run("/app", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
foo: bar
name: test
spec:
template:
metadata:
annotations:
foo: bar
spec:
containers:
- name: test
---
apiVersion: v1
data:
foo: bar
kind: ConfigMap
metadata:
annotations:
foo: bar
name: testConfigMap-798k5k7g9f
`)
}

View File

@@ -20,6 +20,9 @@ type remoteTargetSpec struct {
// Dir is where the resource is saved
Dir filesys.ConfirmedDir
// TempDir is the directory created to hold all resources, including Dir
TempDir filesys.ConfirmedDir
}
// Getter is a function that can gets resource
@@ -31,7 +34,7 @@ func newLoaderAtGetter(raw string, fSys filesys.FileSystem, referrer *fileLoader
}
cleaner := func() error {
return fSys.RemoveAll(rs.Dir.String())
return fSys.RemoveAll(rs.TempDir.String())
}
if err := getter(rs); err != nil {
@@ -55,12 +58,12 @@ func newLoaderAtGetter(raw string, fSys filesys.FileSystem, referrer *fileLoader
func getRemoteTarget(rs *remoteTargetSpec) error {
var err error
rs.Dir, err = filesys.NewTmpConfirmedDir()
rs.TempDir, err = filesys.NewTmpConfirmedDir()
if err != nil {
return err
}
rs.Dir = filesys.ConfirmedDir(rs.Dir.Join("repo"))
rs.Dir = filesys.ConfirmedDir(rs.TempDir.Join("repo"))
// Get the pwd
pwd, err := os.Getwd()

View File

@@ -6,6 +6,7 @@ package provenance
import (
"fmt"
"runtime"
"strings"
)
var (
@@ -57,3 +58,11 @@ func (v Provenance) Short() string {
BuildDate: v.BuildDate,
})
}
// Semver returns the semantic version of kustomize.
// kustomize version is set in format "kustomize/vX.X.X" in every release.
// X.X.X is a semver. If the version string is not in this format,
// return the original version string
func (v Provenance) Semver() string {
return strings.TrimPrefix(v.Version, "kustomize/")
}

View File

@@ -5,13 +5,13 @@ package provider
import (
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/internal/k8sdeps/merge"
kmerge "sigs.k8s.io/kustomize/api/internal/merge"
"sigs.k8s.io/kustomize/api/internal/conflict"
k8sconflict "sigs.k8s.io/kustomize/api/internal/k8sdeps/conflict"
"sigs.k8s.io/kustomize/api/internal/validate"
"sigs.k8s.io/kustomize/api/internal/wrappy"
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/k8sdeps/validator"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/resource"
)
@@ -95,17 +95,27 @@ import (
// would really reduce the work
// (e.g. drop Vars, drop ReplacementTranformer).
//
// - resmap.Merginator
// - resource.ConflictDetector
//
// 1) api/internal/k8sdeps/merge.Merginator
// 1) api/internal/k8sdeps/conflict.conflictDetectorJson
// api/internal/k8sdeps/conflict.conflictDetectorSm
//
// Uses k8s.io/apimachinery/pkg/util/strategicpatch,
// apimachinery/pkg/util/mergepatch, etc. to merge
// resource.Resource instances.
//
// 2) api/internal/merge.Merginator
// 2) api/internal/conflict.smPatchMergeOnlyDetector
//
// At time of writing, this is unimplemented.
// At time of writing, this doesn't report conflicts,
// but it does know how to merge patches. Conflict
// reporting isn't vital to kustomize function. It's
// rare that a person would configure one transformer
// with many patches, much less so many that it became
// hard to spot conflicts. In the case of an undetected
// conflict, the last patch applied wins, likely what
// the user wants anyway. Regardless, the effect of this
// is plainly visible and usable in the output, even if
// a conflict happened but wasn't reported as an error.
//
// - ifc.Validator
//
@@ -116,6 +126,7 @@ import (
//
// 2) api/internal/validate.FieldValidator
//
// See TODO inside the validator for status.
// At time of writing, this is a do-nothing
// validator as it's not critical to kustomize function.
//
@@ -138,18 +149,20 @@ import (
// If you're reading this, plan not done.
//
type DepProvider struct {
resourceFactory *resource.Factory
merginator resmap.Merginator
fieldValidator ifc.Validator
kFactory ifc.KunstructuredFactory
resourceFactory *resource.Factory
conflictDectectorFactory resource.ConflictDetectorFactory
fieldValidator ifc.Validator
}
func makeK8sdepBasedInstances() *DepProvider {
kf := kunstruct.NewKunstructuredFactoryImpl()
rf := resource.NewFactory(kf)
return &DepProvider{
resourceFactory: rf,
merginator: merge.NewMerginator(rf),
fieldValidator: validator.NewKustValidator(),
kFactory: kf,
resourceFactory: rf,
conflictDectectorFactory: k8sconflict.NewFactory(rf),
fieldValidator: validator.NewKustValidator(),
}
}
@@ -157,9 +170,10 @@ func makeKyamlBasedInstances() *DepProvider {
kf := &wrappy.WNodeFactory{}
rf := resource.NewFactory(kf)
return &DepProvider{
resourceFactory: rf,
merginator: kmerge.NewMerginator(rf),
fieldValidator: validate.NewFieldValidator(),
kFactory: kf,
resourceFactory: rf,
conflictDectectorFactory: conflict.NewFactory(),
fieldValidator: validate.NewFieldValidator(),
}
}
@@ -170,12 +184,20 @@ func NewDepProvider(useKyaml bool) *DepProvider {
return makeK8sdepBasedInstances()
}
func NewDefaultDepProvider() *DepProvider {
return NewDepProvider(konfig.FlagEnableKyamlDefaultValue)
}
func (dp *DepProvider) GetKunstructuredFactory() ifc.KunstructuredFactory {
return dp.kFactory
}
func (dp *DepProvider) GetResourceFactory() *resource.Factory {
return dp.resourceFactory
}
func (dp *DepProvider) GetMerginator() resmap.Merginator {
return dp.merginator
func (dp *DepProvider) GetConflictDetectorFactory() resource.ConflictDetectorFactory {
return dp.conflictDectectorFactory
}
func (dp *DepProvider) GetFieldValidator() ifc.Validator {

View File

@@ -5,6 +5,9 @@ package resid
import (
"strings"
"sigs.k8s.io/kustomize/kyaml/openapi"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
// Gvk identifies a Kubernetes API type.
@@ -77,6 +80,22 @@ func (x Gvk) String() string {
return strings.Join([]string{g, v, k}, fieldSep)
}
// StringWoEmptyField returns a string representation of the GVK. Non-exist
// fields will be omitted.
func (x Gvk) StringWoEmptyField() string {
var s []string
if x.Group != "" {
s = append(s, x.Group)
}
if x.Version != "" {
s = append(s, x.Version)
}
if x.Kind != "" {
s = append(s, x.Kind)
}
return strings.Join(s, fieldSep)
}
// Equals returns true if the Gvk's have equal fields.
func (x Gvk) Equals(o Gvk) bool {
return x.Group == o.Group && x.Version == o.Version && x.Kind == o.Kind
@@ -99,6 +118,7 @@ var orderFirst = []string{
"ClusterRoleBinding",
"ConfigMap",
"Secret",
"Endpoints",
"Service",
"LimitRange",
"PriorityClass",
@@ -171,39 +191,23 @@ func (x Gvk) IsSelected(selector *Gvk) bool {
return true
}
var notNamespaceableKinds = []string{
"APIService",
"CSIDriver",
"CSINode",
"CertificateSigningRequest",
"Cluster",
"ClusterRole",
"ClusterRoleBinding",
"ComponentStatus",
"CustomResourceDefinition",
"MutatingWebhookConfiguration",
"Namespace",
"Node",
"PersistentVolume",
"PodSecurityPolicy",
"PriorityClass",
"RuntimeClass",
"SelfSubjectAccessReview",
"SelfSubjectRulesReview",
"StorageClass",
"SubjectAccessReview",
"TokenReview",
"ValidatingWebhookConfiguration",
"VolumeAttachment",
// toKyamlTypeMeta returns a yaml.TypeMeta from x's information.
func (x Gvk) toKyamlTypeMeta() yaml.TypeMeta {
var apiVersion strings.Builder
if x.Group != "" {
apiVersion.WriteString(x.Group)
apiVersion.WriteString("/")
}
apiVersion.WriteString(x.Version)
return yaml.TypeMeta{
APIVersion: apiVersion.String(),
Kind: x.Kind,
}
}
// IsNamespaceableKind returns true if x is a namespaceable Gvk
// Implements https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/#not-all-objects-are-in-a-namespace
func (x Gvk) IsNamespaceableKind() bool {
for _, k := range notNamespaceableKinds {
if k == x.Kind {
return false
}
}
return true
isNamespaceScoped, found := openapi.IsNamespaceScoped(x.toKyamlTypeMeta())
return !found || isNamespaceScoped
}

View File

@@ -18,6 +18,8 @@ package resid
import (
"testing"
"github.com/stretchr/testify/assert"
)
var equalsTests = []struct {
@@ -78,6 +80,8 @@ var lessThanTests = []struct {
Gvk{Group: "a", Version: "b", Kind: "ValidatingWebhookConfiguration"}},
{Gvk{Group: "a", Version: "b", Kind: "Service"},
Gvk{Group: "a", Version: "b", Kind: "APIService"}},
{Gvk{Group: "a", Version: "b", Kind: "Endpoints"},
Gvk{Group: "a", Version: "b", Kind: "Service"}},
}
func TestIsLessThan1(t *testing.T) {
@@ -94,15 +98,16 @@ func TestIsLessThan1(t *testing.T) {
var stringTests = []struct {
x Gvk
s string
r string
}{
{Gvk{}, "~G_~V_~K"},
{Gvk{Kind: "k"}, "~G_~V_k"},
{Gvk{Version: "v"}, "~G_v_~K"},
{Gvk{Version: "v", Kind: "k"}, "~G_v_k"},
{Gvk{Group: "g"}, "g_~V_~K"},
{Gvk{Group: "g", Kind: "k"}, "g_~V_k"},
{Gvk{Group: "g", Version: "v"}, "g_v_~K"},
{Gvk{Group: "g", Version: "v", Kind: "k"}, "g_v_k"},
{Gvk{}, "~G_~V_~K", ""},
{Gvk{Kind: "k"}, "~G_~V_k", "k"},
{Gvk{Version: "v"}, "~G_v_~K", "v"},
{Gvk{Version: "v", Kind: "k"}, "~G_v_k", "v_k"},
{Gvk{Group: "g"}, "g_~V_~K", "g"},
{Gvk{Group: "g", Kind: "k"}, "g_~V_k", "g_k"},
{Gvk{Group: "g", Version: "v"}, "g_v_~K", "g_v"},
{Gvk{Group: "g", Version: "v", Kind: "k"}, "g_v_k", "g_v_k"},
}
func TestString(t *testing.T) {
@@ -113,6 +118,14 @@ func TestString(t *testing.T) {
}
}
func TestStringWoEmptyField(t *testing.T) {
for _, hey := range stringTests {
if hey.x.StringWoEmptyField() != hey.r {
t.Fatalf("bad string %s for %v '%s'", hey.x.StringWoEmptyField(), hey.x, hey.r)
}
}
}
func TestParseGroupVersion(t *testing.T) {
tests := []struct {
input string
@@ -244,3 +257,40 @@ func TestSelectByGVK(t *testing.T) {
}
}
}
func TestIsNamespaceableKind(t *testing.T) {
testCases := []struct {
name string
gvk Gvk
expected bool
}{
{
"namespaceable resource",
Gvk{Group: "apps", Version: "v1", Kind: "Deployment"},
true,
},
{
"clusterscoped resource",
Gvk{Group: "", Version: "v1", Kind: "Namespace"},
false,
},
{
"unknown resource (should default to namespaceable)",
Gvk{Group: "example1.com", Version: "v1", Kind: "Bar"},
true,
},
{
"unknown resource (should default to namespaceable)",
Gvk{Group: "apps", Version: "v1", Kind: "ClusterRoleBinding"},
true,
},
}
for i := range testCases {
test := testCases[i]
t.Run(test.name, func(t *testing.T) {
isNamespaceable := test.gvk.IsNamespaceableKind()
assert.Equal(t, test.expected, isNamespaceable)
})
}
}

View File

@@ -265,7 +265,7 @@ func TestResIdEquals(t *testing.T) {
Name: "nm",
},
gVknResult: false,
nsEquals: false,
nsEquals: true,
equals: false,
},
{
@@ -376,7 +376,7 @@ func TestEffectiveNamespace(t *testing.T) {
}{
{
id: ResId{
Gvk: Gvk{Group: "g", Version: "v", Kind: "Node"},
Gvk: Gvk{Group: "", Version: "v1", Kind: "Node"},
Name: "nm",
},
expected: TotallyNotANamespace,
@@ -384,7 +384,7 @@ func TestEffectiveNamespace(t *testing.T) {
{
id: ResId{
Namespace: "foo",
Gvk: Gvk{Group: "g", Version: "v", Kind: "Node"},
Gvk: Gvk{Group: "", Version: "v1", Kind: "Node"},
Name: "nm",
},
expected: TotallyNotANamespace,

View File

@@ -9,26 +9,21 @@ import (
"sigs.k8s.io/kustomize/api/internal/kusterr"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
// Merginator merges resources.
type Merginator interface {
// Merge creates a new ResMap by merging incoming resources.
// Error if conflict found.
Merge([]*resource.Resource) (ResMap, error)
}
// Factory makes instances of ResMap.
type Factory struct {
// Makes resources.
resF *resource.Factory
// Makes ResMaps via merging.
pm Merginator
// Makes ConflictDetectors.
cdf resource.ConflictDetectorFactory
}
// NewFactory returns a new resmap.Factory.
func NewFactory(rf *resource.Factory, pm Merginator) *Factory {
return &Factory{resF: rf, pm: pm}
func NewFactory(
rf *resource.Factory, cdf resource.ConflictDetectorFactory) *Factory {
return &Factory{resF: rf, cdf: cdf}
}
// RF returns a resource.Factory.
@@ -133,8 +128,8 @@ func (rmF *Factory) FromSecretArgs(
// Merge creates a new ResMap by merging incoming resources.
// Error if conflict found.
func (rmF *Factory) Merge(patches []*resource.Resource) (ResMap, error) {
return rmF.pm.Merge(patches)
func (rmF *Factory) Merge(incoming []*resource.Resource) (ResMap, error) {
return (&merginator{cdf: rmF.cdf}).Merge(incoming)
}
func newResMapFromResourceSlice(
@@ -148,3 +143,20 @@ func newResMapFromResourceSlice(
}
return result, nil
}
// NewResMapFromRNodeSlice returns a ResMap from a slice of RNodes
func (rmF *Factory) NewResMapFromRNodeSlice(rnodes []*yaml.RNode) (ResMap, error) {
var resources []*resource.Resource
for _, rnode := range rnodes {
s, err := rnode.String()
if err != nil {
return nil, err
}
r, err := rmF.resF.FromBytes([]byte(s))
if err != nil {
return nil, err
}
resources = append(resources, r)
}
return newResMapFromResourceSlice(resources)
}

View File

@@ -5,18 +5,20 @@ package resmap_test
import (
"encoding/base64"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"sigs.k8s.io/kustomize/api/filesys"
"sigs.k8s.io/kustomize/api/ifc"
"sigs.k8s.io/kustomize/api/konfig"
"sigs.k8s.io/kustomize/api/kv"
"sigs.k8s.io/kustomize/api/loader"
"sigs.k8s.io/kustomize/api/resid"
. "sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
resmaptest_test "sigs.k8s.io/kustomize/api/testutils/resmaptest"
valtest_test "sigs.k8s.io/kustomize/api/testutils/valtest"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
func TestFromFile(t *testing.T) {
@@ -59,29 +61,21 @@ metadata:
"name": "dply2",
"namespace": "test",
}}).ResMap()
expYaml, err := expected.AsYaml()
assert.NoError(t, err)
fSys := filesys.MakeFsInMemory()
err := fSys.WriteFile("deployment.yaml", []byte(resourceStr))
if err != nil {
t.Fatal(err)
}
assert.NoError(t, fSys.WriteFile("deployment.yaml", []byte(resourceStr)))
ldr, err := loader.NewLoader(
loader.RestrictionRootOnly, filesys.Separator, fSys)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
m, err := rmF.FromFile(ldr, "deployment.yaml")
if err != nil {
t.Fatal(err)
}
if m.Size() != 3 {
t.Fatalf("result should contain 3, but got %d", m.Size())
}
if err := expected.ErrorIfNotEqualLists(m); err != nil {
t.Fatalf("actual doesn't match expected: %v", err)
}
assert.NoError(t, err)
mYaml, err := m.AsYaml()
assert.NoError(t, err)
assert.Equal(t, expYaml, mYaml)
}
func TestFromBytes(t *testing.T) {
@@ -108,17 +102,15 @@ metadata:
"metadata": map[string]interface{}{
"name": "cm2",
}}).ResMap()
expYaml, err := expected.AsYaml()
assert.NoError(t, err)
m, err := rmF.NewResMapFromBytes(encoded)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(m, expected) {
t.Fatalf("%#v doesn't match expected %#v", m, expected)
}
assert.NoError(t, err)
mYaml, err := m.AsYaml()
assert.NoError(t, err)
assert.Equal(t, expYaml, mYaml)
}
var cmap = resid.Gvk{Version: "v1", Kind: "ConfigMap"}
func TestNewFromConfigMaps(t *testing.T) {
type testCase struct {
description string
@@ -228,12 +220,12 @@ BAR=baz
}
}
r, err := rmF.NewResMapFromConfigMapArgs(kvLdr, tc.input)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err = tc.expected.ErrorIfNotEqualLists(r); err != nil {
t.Fatalf("testcase: %q, err: %v", tc.description, err)
}
assert.NoError(t, err, tc.description)
rYaml, err := r.AsYaml()
assert.NoError(t, err, tc.description)
expYaml, err := tc.expected.AsYaml()
assert.NoError(t, err, tc.description)
assert.Equal(t, expYaml, rYaml)
}
}
@@ -262,6 +254,8 @@ func TestNewResMapFromSecretArgs(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
actYaml, err := actual.AsYaml()
assert.NoError(t, err)
expected := resmaptest_test.NewRmBuilder(t, rf).Add(
map[string]interface{}{
@@ -276,7 +270,127 @@ func TestNewResMapFromSecretArgs(t *testing.T) {
"DB_PASSWORD": base64.StdEncoding.EncodeToString([]byte("somepw")),
},
}).ResMap()
if err = expected.ErrorIfNotEqualLists(actual); err != nil {
expYaml, err := expected.AsYaml()
assert.NoError(t, err)
assert.Equal(t, string(expYaml), string(actYaml))
}
func TestFromRNodeSlice(t *testing.T) {
input := `apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: namespace-reader
rules:
- apiGroups:
- ""
resources:
- namespaces
verbs:
- get
- watch
- list
`
rnodes := []*yaml.RNode{
yaml.MustParse(input),
}
rm, err := rmF.NewResMapFromRNodeSlice(rnodes)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expected := resmaptest_test.NewRmBuilder(t, rf).Add(
map[string]interface{}{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRole",
"metadata": map[string]interface{}{
"name": "namespace-reader",
},
"rules": []interface{}{
map[string]interface{}{
"apiGroups": []interface{}{
"",
},
"resources": []interface{}{
"namespaces",
},
"verbs": []interface{}{
"get",
"watch",
"list",
},
},
},
}).ResMap()
if err = expected.ErrorIfNotEqualLists(rm); err != nil {
t.Fatalf("error: %s", err)
}
}
func TestMerge_Empty(t *testing.T) {
rm, err := rmF.Merge([]*resource.Resource{})
assert.NoError(t, err)
assert.Equal(t, 0, rm.Size())
}
func TestMerge(t *testing.T) {
var (
err error
yml []byte
r1, r2 *resource.Resource
)
r1, err = rf.FromBytes([]byte(`apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
B:
C: Z
`))
assert.NoError(t, err)
r2, err = rf.FromBytes([]byte(`apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
C: Z
D: W
baz:
hello: world
`))
assert.NoError(t, err)
rm, err := rmF.Merge([]*resource.Resource{r1, r2})
assert.NoError(t, err)
yml, err = rm.AsYaml()
assert.NoError(t, err)
assert.Equal(t, konfig.IfApiMachineryElseKyaml(`apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
B: null
C: Z
D: W
baz:
hello: world
`, `apiVersion: example.com/v1
kind: Foo
metadata:
name: my-foo
spec:
bar:
C: Z
D: W
baz:
hello: world
`), string(yml))
}

118
api/resmap/merginator.go Normal file
View File

@@ -0,0 +1,118 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package resmap
import (
"fmt"
"sigs.k8s.io/kustomize/api/resource"
)
// merginator coordinates merging the resources in incoming to the result.
type merginator struct {
incoming []*resource.Resource
cdf resource.ConflictDetectorFactory
result ResMap
}
func (m *merginator) Merge(in []*resource.Resource) (ResMap, error) {
m.result = New()
m.incoming = in
for index := range m.incoming {
alreadyInResult, err := m.appendIfNoMatch(index)
if err != nil {
return nil, err
}
if alreadyInResult != nil {
// The resource at index has the same resId as a previously
// considered resource.
//
// If they conflict with each other (e.g. they both want to change
// the image name in a Deployment, but to different values),
// return an error.
//
// If they don't conflict, then merge them into a single resource,
// since they both target the same item, and we want cumulative
// behavior. E.g. say both patches modify a map. Without a merge,
// the last patch wins, replacing the entire map.
err = m.mergeWithExisting(index, alreadyInResult)
if err != nil {
return nil, err
}
}
}
return m.result, nil
}
func (m *merginator) appendIfNoMatch(index int) (*resource.Resource, error) {
candidate := m.incoming[index]
matchedResources := m.result.GetMatchingResourcesByOriginalId(
candidate.OrgId().Equals)
if len(matchedResources) == 0 {
m.result.Append(candidate)
return nil, nil
}
if len(matchedResources) > 1 {
return nil, fmt.Errorf("multiple resources targeted by patch")
}
return matchedResources[0], nil
}
func (m *merginator) mergeWithExisting(
index int, alreadyInResult *resource.Resource) error {
candidate := m.incoming[index]
cd, err := m.cdf.New(candidate.OrgId().Gvk)
if err != nil {
return err
}
hasConflict, err := cd.HasConflict(candidate, alreadyInResult)
if err != nil {
return err
}
if hasConflict {
return m.makeError(cd, index)
}
merged, err := cd.MergePatches(alreadyInResult, candidate)
if err != nil {
return err
}
_, err = m.result.Replace(merged)
return err
}
// Make an error message describing the conflict.
func (m *merginator) makeError(cd resource.ConflictDetector, index int) error {
conflict, err := m.findConflict(cd, index)
if err != nil {
return err
}
if conflict == nil {
return fmt.Errorf("expected conflict for %s", m.incoming[index].OrgId())
}
return fmt.Errorf(
"conflict between %#v at index %d and %#v",
m.incoming[index].Map(), index, conflict.Map())
}
// findConflict looks for a conflict in a resource slice.
// It returns the first conflict between the resource at index
// and some other resource. Two resources can only conflict if
// they have the same original ResId.
func (m *merginator) findConflict(
cd resource.ConflictDetector, index int) (*resource.Resource, error) {
targetId := m.incoming[index].OrgId()
for i, p := range m.incoming {
if i == index || !targetId.Equals(p.OrgId()) {
continue
}
conflict, err := cd.HasConflict(p, m.incoming[index])
if err != nil {
return nil, err
}
if conflict {
return p, nil
}
}
return nil, nil
}

View File

@@ -10,6 +10,7 @@ import (
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
// A Transformer modifies an instance of ResMap.
@@ -235,4 +236,13 @@ type ResMap interface {
// Select returns a list of resources that
// are selected by a Selector
Select(types.Selector) ([]*resource.Resource, error)
// ToRNodeSlice converts the resources in the resmp
// to a list of RNodes
ToRNodeSlice() ([]*yaml.RNode, error)
// ApplySmPatch applies a strategic-merge patch to the
// selected set of resources.
ApplySmPatch(
selectedSet *resource.IdSet, patch *resource.Resource) error
}

View File

@@ -6,12 +6,13 @@ package resmap
import (
"bytes"
"fmt"
"regexp"
"strings"
"github.com/pkg/errors"
"sigs.k8s.io/kustomize/api/resid"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
kyaml_yaml "sigs.k8s.io/kustomize/kyaml/yaml"
"sigs.k8s.io/yaml"
)
@@ -339,10 +340,8 @@ func (m *resWrangler) ErrorIfNotEqualLists(other ResMap) error {
}
for i, r1 := range m.rList {
r2 := m2.rList[i]
if !r1.Equals(r2) {
return fmt.Errorf(
"Item i=%d differs:\n n1 = %s\n n2 = %s\n o1 = %s\n o2 = %s\n",
i, r1.OrgId(), r2.OrgId(), r1, r2)
if err := r1.ErrIfNotEquals(r2); err != nil {
return err
}
}
return nil
@@ -510,51 +509,34 @@ func (m *resWrangler) appendReplaceOrMerge(
return nil
}
func anchorRegex(pattern string) string {
if pattern == "" {
return pattern
}
return "^" + pattern + "$"
}
// Select returns a list of resources that
// are selected by a Selector
func (m *resWrangler) Select(s types.Selector) ([]*resource.Resource, error) {
ns := regexp.MustCompile(anchorRegex(s.Namespace))
nm := regexp.MustCompile(anchorRegex(s.Name))
var result []*resource.Resource
sr, err := types.NewSelectorRegex(&s)
if err != nil {
return nil, err
}
for _, r := range m.Resources() {
curId := r.CurId()
orgId := r.OrgId()
// matches the namespace when namespace is not empty in the selector
// It first tries to match with the original namespace
// then matches with the current namespace
if r.GetNamespace() != "" {
matched := ns.MatchString(orgId.EffectiveNamespace())
if !matched {
matched = ns.MatchString(curId.EffectiveNamespace())
if !matched {
continue
}
}
if !sr.MatchNamespace(orgId.EffectiveNamespace()) &&
!sr.MatchNamespace(curId.EffectiveNamespace()) {
continue
}
// matches the name when name is not empty in the selector
// It first tries to match with the original name
// then matches with the current name
if r.GetName() != "" {
matched := nm.MatchString(orgId.Name)
if !matched {
matched = nm.MatchString(curId.Name)
if !matched {
continue
}
}
if !sr.MatchName(orgId.Name) &&
!sr.MatchName(curId.Name) {
continue
}
// matches the GVK
if !r.GetGvk().IsSelected(&s.Gvk) {
if !sr.MatchGvk(r.GetGvk()) {
continue
}
@@ -579,3 +561,64 @@ func (m *resWrangler) Select(s types.Selector) ([]*resource.Resource, error) {
}
return result, nil
}
// ToRNodeSlice converts the resources in the resmp
// to a list of RNodes
func (m *resWrangler) ToRNodeSlice() ([]*kyaml_yaml.RNode, error) {
var rnodes []*kyaml_yaml.RNode
for _, r := range m.Resources() {
s, err := r.AsYAML()
if err != nil {
return nil, err
}
rnode, err := kyaml_yaml.Parse(string(s))
if err != nil {
return nil, err
}
rnodes = append(rnodes, rnode)
}
return rnodes, nil
}
func (m *resWrangler) ApplySmPatch(
selectedSet *resource.IdSet, patch *resource.Resource) error {
newRm := New()
for _, res := range m.Resources() {
if !selectedSet.Contains(res.CurId()) {
newRm.Append(res)
continue
}
patchCopy := patch.DeepCopy()
patchCopy.SetName(res.GetName())
patchCopy.SetNamespace(res.GetNamespace())
patchCopy.SetGvk(res.GetGvk())
err := res.ApplySmPatch(patchCopy)
if err != nil {
// Check for an error string from UnmarshalJSON that's indicative
// of an object that's missing basic KRM fields, and thus may have been
// entirely deleted (an acceptable outcome). This error handling should
// be deleted along with use of ResMap and apimachinery functions like
// UnmarshalJSON.
if !strings.Contains(err.Error(), "Object 'Kind' is missing") {
// Some unknown error, let it through.
return err
}
if !res.IsEmpty() {
return errors.Wrapf(
err, "with unexpectedly non-empty object map of size %d",
len(res.Map()))
}
// Fall through to handle deleted object.
}
if !res.IsEmpty() {
// IsEmpty means all fields have been removed from the object.
// This can happen if a patch required deletion of the
// entire resource (not just a part of it). This means
// the overall resmap must shrink by one.
newRm.Append(res)
}
}
m.Clear()
m.AppendAll(newRm)
return nil
}

Some files were not shown because too many files have changed in this diff Show More