|
| 1 | +{-# LANGUAGE ScopedTypeVariables #-} |
| 2 | +module Main where |
| 3 | + |
| 4 | +import Control.Monad (when) |
| 5 | +import System.Directory (createDirectory, doesFileExist, getCurrentDirectory, setCurrentDirectory) |
| 6 | +import System.Environment (getEnv) |
| 7 | +import System.Exit (exitFailure, exitSuccess) |
| 8 | +import System.IO (hPutStrLn, stderr) |
| 9 | +import MyLib (getDataFileName) |
| 10 | +import Control.Exception |
| 11 | + |
| 12 | +main :: IO () |
| 13 | +main = do |
| 14 | + -- Print the datadir environment variable |
| 15 | + dataDirEnv <- getEnv "datadir_test_datadir" |
| 16 | + putStrLn $ "datadir_test_datadir: " ++ dataDirEnv |
| 17 | + |
| 18 | + -- Get path to our test data file |
| 19 | + dataFilePath <- getDataFileName "testdata/sample.txt" |
| 20 | + putStrLn $ "Data file path: " ++ dataFilePath |
| 21 | + |
| 22 | + -- Check that we can access the file |
| 23 | + fileExists <- doesFileExist dataFilePath |
| 24 | + putStrLn $ "File exists: " ++ show fileExists |
| 25 | + |
| 26 | + -- Create a subdirectory and change into it |
| 27 | + currentDir <- getCurrentDirectory |
| 28 | + putStrLn $ "Current directory: " ++ currentDir |
| 29 | + createDirectory "subdir" `catch` \(_ :: SomeException) -> pure () |
| 30 | + setCurrentDirectory "subdir" |
| 31 | + newDir <- getCurrentDirectory |
| 32 | + putStrLn $ "New directory: " ++ newDir |
| 33 | + |
| 34 | + -- Try to access the data file again after changing directory |
| 35 | + dataFilePathAfterCd <- getDataFileName "testdata/sample.txt" |
| 36 | + putStrLn $ "Data file path after cd: " ++ dataFilePathAfterCd |
| 37 | + |
| 38 | + fileExistsAfterCd <- doesFileExist dataFilePathAfterCd |
| 39 | + putStrLn $ "File exists after cd: " ++ show fileExistsAfterCd |
| 40 | + |
| 41 | + -- Exit with error if we can't find the file |
| 42 | + when (not fileExistsAfterCd) $ do |
| 43 | + hPutStrLn stderr "ERROR: Could not find data file after changing directory!" |
| 44 | + hPutStrLn stderr $ "datadir_test_datadir was set to: " ++ dataDirEnv |
| 45 | + exitFailure |
| 46 | + |
| 47 | + putStrLn "SUCCESS: Data file found correctly even after changing directory!" |
| 48 | + exitSuccess |
0 commit comments