/Utils.hs

http://github.com/jgoerzen/gopherbot · Haskell · 75 lines · 46 code · 10 blank · 19 comment · 10 complexity · 728658e9ed63a94380bbaf14d91bfa53 MD5 · raw file

  1. {-
  2. Copyright (C) 2005 John Goerzen <jgoerzen@complete.org>
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  14. -}
  15. module Utils where
  16. import Types
  17. import Config
  18. import MissingH.Maybe
  19. import MissingH.Path
  20. import Control.Concurrent
  21. import Control.Exception
  22. import System.IO
  23. --import Foreign.C.String
  24. import Data.List
  25. getFSPath :: GAddress -> FilePath
  26. getFSPath ga =
  27. forceMaybeMsg ("getFSPath1 " ++ show ga) . secureAbsNormPath (baseDir ++ "/gopher") $ base
  28. where base = (host ga) ++ "/" ++ (show $ port ga) ++ "/" ++
  29. (path ga) ++ case (dtype ga) of
  30. '1' -> "/.gophermap"
  31. _ -> ""
  32. newLock :: IO Lock
  33. newLock = newEmptyMVar
  34. acquire :: Lock -> IO ()
  35. acquire l =
  36. do t <- myThreadId
  37. putMVar l t
  38. release :: Lock -> IO ()
  39. release l =
  40. do t <- myThreadId
  41. r <- tryTakeMVar l
  42. case r of
  43. Nothing -> do msg $ "Warning: released lock which was unheld."
  44. Just x -> if x == t
  45. then return ()
  46. else fail $ "Thread " ++ (show t) ++
  47. " released lock held by thread " ++
  48. (show x)
  49. withLock :: Lock -> (IO a) -> IO a
  50. withLock l action = bracket_ (acquire l) (release l) action
  51. msg :: String -> IO ()
  52. msg l =
  53. do t <- myThreadId
  54. let disp = (show t) ++ ": " ++ l ++ "\n"
  55. putStr disp
  56. hFlush stdout
  57. --withCStringLen disp (\(c, len) -> hPutBuf stdout c len >> hFlush stdout)
  58. ce :: String -> String
  59. ce i =
  60. '\'' :
  61. (concat $ map (\c -> if c == '\'' then "''" else [c]) i)
  62. ++ "'"