Skip to content

Commit

Permalink
adding content check + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Mzack9999 committed Jun 4, 2024
1 parent f9f1064 commit 7e2ce6f
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
26 changes: 25 additions & 1 deletion file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"strconv"
"strings"
"time"
"unicode"

"github.com/asaskevich/govalidator"
"github.com/mattn/go-isatty"
Expand Down Expand Up @@ -613,5 +614,28 @@ func IsEmpty(filename string) (bool, error) {
return false, err
}

return fileInfo.Size() == 0, nil
if fileInfo.Size() == 0 {
return true, nil
}

file, err := os.Open(filename)
if err != nil {
return false, err
}
defer file.Close()

// Read up to 512 bytes to check for non-space characters
buffer := make([]byte, 16)
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
return false, err
}

// Check if all read characters are spaces, null characters, new lines, or carriage returns
for i := 0; i < n; i++ {
if unicode.IsSpace(rune(buffer[i])) || buffer[i] == 0 || buffer[i] == '\n' || buffer[i] == '\r' {
return true, nil
}
}
return false, nil
}
35 changes: 35 additions & 0 deletions file/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -632,3 +632,38 @@ func TestFileExistsIn(t *testing.T) {
})
}
}

func TestIsEmpty(t *testing.T) {
// Create a temporary directory
tempDir := t.TempDir()

// Test case: File not existent
t.Run("file not existent", func(t *testing.T) {
nonExistentFile := filepath.Join(tempDir, "nonexistent.txt")
isEmpty, err := IsEmpty(nonExistentFile)
require.Error(t, err, "expected an error for non-existent file")
require.False(t, isEmpty, "non-existent file should not be considered empty")
})

// Test case: Empty file
t.Run("empty file", func(t *testing.T) {
emptyFile := filepath.Join(tempDir, "empty.txt")
err := os.WriteFile(emptyFile, []byte(""), 0644)
require.NoError(t, err, "failed to create empty file")
defer os.Remove(emptyFile) // Clean up the created file
isEmpty, err := IsEmpty(emptyFile)
require.NoError(t, err, "should not error for an empty file")
require.True(t, isEmpty, "empty file should be considered empty")
})

// Test case: File containing only spaces
t.Run("file with spaces", func(t *testing.T) {
spacesFile := filepath.Join(tempDir, "spaces.txt")
err := os.WriteFile(spacesFile, []byte(" "), 0644)
require.NoError(t, err, "failed to create file with spaces")
defer os.Remove(spacesFile) // Clean up the created file
isEmpty, err := IsEmpty(spacesFile)
require.NoError(t, err, "should not error for a file with only spaces")
require.True(t, isEmpty, "file with only spaces should be considered empty")
})
}

0 comments on commit 7e2ce6f

Please sign in to comment.