fixed sanitisation a bit

This commit is contained in:
stuce-bot 2025-05-19 12:06:39 +02:00
parent b07950f797
commit b6f757c35e
4 changed files with 69 additions and 48 deletions

View file

@ -7,34 +7,40 @@ module FileActions where
import Data.Text qualified as T
import Data.Text.IO qualified as TIO
import System.Directory
import Text.Read qualified as TR
import TodoListItem
tempFile = "tempFile"
-- TODO: add sanitisation using the todo item type ?
-- TODO: sometimes the whitespace does not work as expected, find why and solve it
add folder file item = do
content <- TIO.readFile (folder <> file)
let result = content <> item
write folder file result
write folder file content = do
TIO.writeFile (folder <> tempFile) content
readF folder file = do
content <- readFile (folder <> file)
let itemsAsStrings = lines content
-- TODO: check if can simplify this step by making read work on list of items (i suppose it doesnt yet)
let itemsAsObjects = map TR.read itemsAsStrings :: [TodoListItem]
return itemsAsObjects
writeF folder file content = do
let result = show content
writeFile (folder <> tempFile) result
renameFile (folder <> tempFile) (folder <> file)
appendF folder file item = do
content <- readF folder file
let result = content <> item -- TODO: check if more elegant solution exist (without needing a list for 1 item)
writeF folder file result
delete :: FilePath -> FilePath -> TodoListItem -> IO ()
delete folder file item = do
content <- TIO.readFile (folder <> file)
let result = T.unlines $ filter (not . item) (T.lines content)
write folder file result
content <- readF folder file
let result = filter (/= item) content
writeF folder file result
check folder file item = do
content <- TIO.readFile (folder <> file)
let result = T.unlines $ map (swapIfMatch item) (T.lines content)
TIO.writeFile (folder <> tempFile) result
renameFile (folder <> tempFile) (folder <> file)
swapIfMatch name strEncodedItem = if name == strEncodedItem then swapCheck strEncodedItem else strEncodedItem
swapCheck text
| T.index text 1 == 'x' = "[ ] " <> T.drop 4 text
| T.index text 1 == ' ' = "[x] " <> T.drop 4 text
| otherwise = error "incorrectly formated element"
check :: FilePath -> FilePath -> TodoListItem -> IO ()
check folder file name = do
content <- readF folder file
let result = map (swapIfMatch name) content
writeF folder file result
where
swapIfMatch name item = do
if item == name
then TodoListItem{name = TodoListItem.name item, done = not (TodoListItem.done item)}
else item