packages feed

headergen-0.1.1.1: src/Headergen/Utility.hs

{- |
Module      :  $Header$
Description :  Contains utility functions.
Author      :  Nils 'bash0r' Jonsson
Copyright   :  (c) 2015 Nils 'bash0r' Jonsson
License     :  MIT

Maintainer  :  aka.bash0r@gmail.com
Stability   :  unstable
Portability :  non-portable (Portability is untested.)

Some utility functions.
-}
module Headergen.Utility
( alignText
, trimText
, def
, requestForAllowance
, parentDirectory
) where


import Data.List

import System.Console.Haskeline
import System.FilePath.Posix


-- | Align message if it is less than n characters.
alignText :: (Num a) => Int -> String -> String
alignText n xs =
  if genericLength xs < n
     then alignText n (xs ++ " ")
     else xs

-- | Align text or cut text to be exact n characters.
trimText :: (Num a) => Int -> String -> String
trimText n crt =
  if genericLength crt >= n
     then take n crt
     else alignText n crt

-- | Try to get a value out of a Maybe String.
def :: Maybe String -> String -> String
def v d =
  case v of
    Just v ->
      if null v
         then d
         else v
    Nothing ->
      d

-- | Request the user for allowance to override a file.
requestForAllowance :: IO Bool
requestForAllowance = runInputT defaultSettings allowanceRequest
  where
    allowanceRequest = do
      line <- getInputLine "File exists already. Override? [y/n] "
      case line of
        (Just "y") -> return True
        (Just "n") -> return False
        _          -> allowanceRequest

-- | Try to get the parent directory of a given path.
parentDirectory :: FilePath -> Maybe FilePath
parentDirectory path =
  let splitted   = splitDirectories path
      reversed   = reverse splitted
      dropped    = drop 1 reversed
      rereversed = reverse dropped
      newPath    = joinPath rereversed
   in case newPath of
        []        -> Nothing
        otherwise -> Just otherwise