diff --git a/pkg/kubectl/cmd/util/editor/BUILD b/pkg/kubectl/cmd/util/editor/BUILD index 1533b35a456..ec7ea4d3966 100644 --- a/pkg/kubectl/cmd/util/editor/BUILD +++ b/pkg/kubectl/cmd/util/editor/BUILD @@ -41,7 +41,10 @@ go_library( go_test( name = "go_default_test", - srcs = ["editor_test.go"], + srcs = [ + "editoptions_test.go", + "editor_test.go", + ], embed = [":go_default_library"], ) diff --git a/pkg/kubectl/cmd/util/editor/editoptions.go b/pkg/kubectl/cmd/util/editor/editoptions.go index b7ae830d228..9af8f0f33c3 100644 --- a/pkg/kubectl/cmd/util/editor/editoptions.go +++ b/pkg/kubectl/cmd/util/editor/editoptions.go @@ -657,12 +657,12 @@ func (h *editHeader) writeTo(w io.Writer, editMode EditMode) error { for _, r := range h.reasons { if len(r.other) > 0 { - fmt.Fprintf(w, "# %s:\n", r.head) + fmt.Fprintf(w, "# %s:\n", hashOnLineBreak(r.head)) } else { - fmt.Fprintf(w, "# %s\n", r.head) + fmt.Fprintf(w, "# %s\n", hashOnLineBreak(r.head)) } for _, o := range r.other { - fmt.Fprintf(w, "# * %s\n", o) + fmt.Fprintf(w, "# * %s\n", hashOnLineBreak(o)) } fmt.Fprintln(w, "#") } @@ -738,3 +738,18 @@ func hasLines(r io.Reader) (bool, error) { } return false, nil } + +// hashOnLineBreak returns a string built from the provided string by inserting any necessary '#' +// characters after '\n' characters, indicating a comment. +func hashOnLineBreak(s string) string { + r := "" + for i, ch := range s { + j := i + 1 + if j < len(s) && ch == '\n' && s[j] != '#' { + r += "\n# " + } else { + r += string(ch) + } + } + return r +} diff --git a/pkg/kubectl/cmd/util/editor/editoptions_test.go b/pkg/kubectl/cmd/util/editor/editoptions_test.go new file mode 100644 index 00000000000..69a30583c0c --- /dev/null +++ b/pkg/kubectl/cmd/util/editor/editoptions_test.go @@ -0,0 +1,51 @@ +/* +Copyright 2018 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package editor + +import ( + "testing" +) + +func TestHashOnLineBreak(t *testing.T) { + tests := []struct { + original string + expected string + }{ + { + original: "", + expected: "", + }, + { + original: "\n", + expected: "\n", + }, + { + original: "a\na\na\n", + expected: "a\n# a\n# a\n", + }, + { + original: "a\n\n\na\n\n", + expected: "a\n# \n# \n# a\n# \n", + }, + } + for _, test := range tests { + r := hashOnLineBreak(test.original) + if r != test.expected { + t.Errorf("expected: %s, saw: %s", test.expected, r) + } + } +}