Skip to content

Commit

Permalink
Moved excludeWhitespace() function to util package
Browse files Browse the repository at this point in the history
  • Loading branch information
arknable committed May 14, 2021
1 parent 70a813b commit ca51410
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 13 deletions.
11 changes: 0 additions & 11 deletions cmd/cmd_pkg.go
Expand Up @@ -245,14 +245,3 @@ func loadCommandHandler(cmd *cobra.Command, args []string) {
exitWithError(err.Error())
}
}

func excludeWhitespaces(arr []string) []string {
result := make([]string, 0)
for _, h := range arr {
if h == "" {
continue
}
result = append(result, h)
}
return result
}
6 changes: 4 additions & 2 deletions cmd/flags_run_local_instance_unix.go
Expand Up @@ -4,6 +4,8 @@ import (
"bufio"
"os/exec"
"strings"

"github.com/nanovms/ops/util/slice"
)

// Checks which process is using given port number
Expand All @@ -19,7 +21,7 @@ func checkPortUserPID(portNumber string) (string, error) {

scanner := bufio.NewScanner(strings.NewReader(string(out)))
scanner.Scan() // check header first
cols := excludeWhitespaces(strings.Split(scanner.Text(), " "))
cols := slice.ExcludeWhitespaces(strings.Split(scanner.Text(), " "))
headerIdx := -1
for i, v := range cols {
if strings.ToLower(v) == "pid" {
Expand All @@ -31,7 +33,7 @@ func checkPortUserPID(portNumber string) (string, error) {
scanner.Scan()
line := strings.Trim(scanner.Text(), " ")
if line != "" {
cols = excludeWhitespaces(strings.Split(line, " "))
cols = slice.ExcludeWhitespaces(strings.Split(line, " "))
pid = cols[headerIdx]
}

Expand Down
15 changes: 15 additions & 0 deletions util/slice/string.go
@@ -0,0 +1,15 @@
package slice

import "strings"

// ExcludeWhitespaces removes whitespaces from given slice
func ExcludeWhitespaces(arr []string) []string {
result := make([]string, 0)
for _, h := range arr {
if strings.Trim(h, " ") == "" {
continue
}
result = append(result, h)
}
return result
}
24 changes: 24 additions & 0 deletions util/slice/string_test.go
@@ -0,0 +1,24 @@
package slice

import (
"strings"
"testing"
)

func TestExcludeWhitespaces(t *testing.T) {
arr := []string{
"lorem", "ipsum", " ", "dolor", "", "sit", "amet",
}
trimmed := ExcludeWhitespaces(arr)
for _, v := range trimmed {
if v == "" {
t.Error("found unstripped whice space")
}
}

expected := "lorem,ipsum,dolor,sit,amet"
str := strings.Join(trimmed, ",")
if str != expected {
t.Errorf("expected '%s', got '%s'", expected, str)
}
}

0 comments on commit ca51410

Please sign in to comment.