Skip to content

Commit

Permalink
fs: add folder resource
Browse files Browse the repository at this point in the history
Signed-off-by: Jérôme Jutteau <[email protected]>
  • Loading branch information
jerome-jutteau committed Jun 20, 2022
1 parent c4d5d17 commit 2ad1967
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@

## fs
- file
- folder
48 changes: 47 additions & 1 deletion internal/providers/fs/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import (
)

const Name = "fs"

const typeFile = "file"
const typeFolder = "folder"

type FileSystem struct {
Path string
Expand All @@ -35,7 +37,7 @@ func New(config ProviderConfig, debug bool) (*FileSystem, error) {
}

func Types() []ObjectType {
object_types := []ObjectType{typeFile}
object_types := []ObjectType{typeFile, typeFolder}
return object_types
}

Expand Down Expand Up @@ -64,6 +66,8 @@ func (provider *FileSystem) ReadObjects(typeName string) []Object {
switch typeName {
case typeFile:
return provider.readFiles()
case typeFolder:
return provider.readFolders()
}
return []Object{}
}
Expand All @@ -72,6 +76,8 @@ func (provider *FileSystem) DeleteObjects(typeName string, objects []Object) {
switch typeName {
case typeFile:
provider.deleteFiles(objects)
case typeFolder:
provider.deleteFolders(objects)
}
}

Expand Down Expand Up @@ -120,3 +126,43 @@ func (provider *FileSystem) deleteFiles(files []Object) {
log.Println("OK")
}
}

func (provider *FileSystem) readFolders() []Object {
folders := make([]Object, 0)

if err := os.Chdir(provider.Path); err != nil {
log.Printf("cannot move to directory: %s", err.Error())
return folders
}

folderStack := []string{"."}
for len(folderStack) > 0 {
dirPath := folderStack[len(folderStack)-1]
folderStack = folderStack[:len(folderStack)-1]
dir, err := os.ReadDir(dirPath)
if err != nil {
log.Printf("cannot read directory: %s", err.Error())
continue
}
for _, node := range dir {
nodePath := path.Join(dirPath, node.Name())
if node.IsDir() {
folderStack = append(folderStack, nodePath)
folders = append(folders, nodePath)
}
}
}
return folders
}

func (provider *FileSystem) deleteFolders(folders []Object) {
for _, relativeFolderPath := range folders {
folderPath := path.Join(provider.Path, relativeFolderPath)
log.Printf("Deleting folder %s ... ", folderPath)
if err := os.Remove(folderPath); err != nil {
log.Printf("cannot remove folder %s\n", err.Error())
continue
}
log.Println("OK")
}
}

0 comments on commit 2ad1967

Please sign in to comment.