Skip to content

Commit

Permalink
Add isSymlink function and test to gen license to avoid for symlink t…
Browse files Browse the repository at this point in the history
…o become normal file. (#2290)

This commit adds a new function called `isSymlink` to check if a given path is a symbolic link. It also includes a corresponding test in the `main_test.go` file. This functionality will be useful for handling symbolic links in the codebase.
  • Loading branch information
ykadowak committed Jan 10, 2024
1 parent ac50bf3 commit 6f4b179
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
17 changes: 17 additions & 0 deletions hack/license/gen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,24 @@ func dirwalk(dir string) []string {
return paths
}

func isSymlink(path string) (bool, error) {
lst, err := os.Lstat(path)
if err != nil {
return false, err
}
return lst.Mode()&os.ModeSymlink != 0, nil
}

func readAndRewrite(path string) error {
// return if it is a symlink
isSym, err := isSymlink(path)
if err != nil {
return err
}
if isSym {
return nil
}

f, err := os.OpenFile(path, os.O_RDWR|os.O_SYNC, fs.ModePerm)
if err != nil {
return errors.Errorf("filepath %s, could not open", path)
Expand Down
55 changes: 55 additions & 0 deletions hack/license/gen/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,58 @@
//

package main

import (
"os"
"path/filepath"
"testing"
)

func TestIsSymlink(t *testing.T) {
t.Parallel()

dir := t.TempDir()
symlinkPath := filepath.Join(dir, "target")
filePath := filepath.Join(dir, "file")

_, err := os.Create(filePath)
if err != nil {
t.Error(err)
}

err = os.Symlink(filePath, symlinkPath)
if err != nil {
t.Error(err)
}

tests := []struct {
name string
path string
expected bool
}{
{
name: "return true when it is a symlink",
path: symlinkPath,
expected: true,
},
{
name: "return false when it is a normal file",
path: filePath,
expected: false,
},
}

for _, tc := range tests {
test := tc
t.Run(test.name, func(tt *testing.T) {
tt.Parallel()
isSymlink, err := isSymlink(test.path)
if err != nil {
tt.Error(err)
}
if isSymlink != test.expected {
tt.Errorf("expected %v, got %v", test.expected, isSymlink)
}
})
}
}

0 comments on commit 6f4b179

Please sign in to comment.