From dd8d444d9fb0bce556b3f1002ac5e73bda4a012a Mon Sep 17 00:00:00 2001 From: Mahad Zaryab <43658574+mahadzaryab1@users.noreply.github.com> Date: Sun, 20 Oct 2024 11:47:05 -0400 Subject: [PATCH] Slice now produces empty pipe for empty slice (fixes #110) (#216) --- script.go | 6 +++++- script_test.go | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/script.go b/script.go index 1fb2978..2d39bdb 100644 --- a/script.go +++ b/script.go @@ -180,8 +180,12 @@ func Post(url string) *Pipe { return NewPipe().Post(url) } -// Slice creates a pipe containing each element of s, one per line. +// Slice creates a pipe containing each element of s, one per line. If s is +// empty or nil, then the pipe is empty. func Slice(s []string) *Pipe { + if len(s) == 0 { + return NewPipe() + } return Echo(strings.Join(s, "\n") + "\n") } diff --git a/script_test.go b/script_test.go index a58ff47..a3f9124 100644 --- a/script_test.go +++ b/script_test.go @@ -1387,6 +1387,18 @@ func TestSliceProducesElementsOfSpecifiedSliceOnePerLine(t *testing.T) { } } +func TestSliceGivenEmptySliceProducesEmptyPipe(t *testing.T) { + t.Parallel() + want := "" + got, err := script.Slice([]string{}).String() + if err != nil { + t.Fatal(err) + } + if want != got { + t.Fatalf("want %q, got %q", want, got) + } +} + func TestStdoutReturnsErrorGivenReadErrorOnPipe(t *testing.T) { t.Parallel() brokenReader := iotest.ErrReader(errors.New("oh no"))