{-# LANGUAGE ScopedTypeVariables #-}
{- Shell Equivalents
Copyright (C) 2004-2009 John Goerzen <jgoerzen@complete.org>
Please see the COPYRIGHT file
-}

{- |
   Module     : HSH.ShellEquivs
   Copyright  : Copyright (C) 2009 John Goerzen
   License    : GNU LGPL, version 2.1 or above

   Maintainer : John Goerzen <jgoerzen@complete.org>
   Stability  : provisional
   Portability: portable

Copyright (c) 2006-2009 John Goerzen, jgoerzen\@complete.org

This module provides shell-like commands.  Most, but not all, are designed
to be used directly as part of a HSH pipeline.  All may be used outside
HSH entirely as well.

-}

{-# LANGUAGE ScopedTypeVariables #-}

#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))
#define __HSH_POSIX__
#else
#define __HSH_WINDOWS__
#endif

module HSH.ShellEquivs(
                       abspath,
                       appendTo,
                       basename,
                       bracketCD,
                       catFrom,
                       catBytes,
                       catBytesFrom,
                       catTo,
#ifdef __HSH_POSIX__
                       catToFIFO,
#endif
                       cd,
                       cut,
                       cutR,
                       dirname,
                       discard,
                       echo,
                       exit,
                       glob,
                       grep,
                       grepV,
                       egrep,
                       egrepV,
                       joinLines,
                       lower,
                       upper,
                       mkdir,
                       numberLines,
                       pwd,
#ifdef __HSH_POSIX__
                       readlink,
                       readlinkabs,
#endif
                       rev,
                       revW,
                       HSH.Command.setenv,
                       space,
                       unspace,
                       tac,
                       tee,
#ifdef __HSH_POSIX__
                       teeFIFO,
#endif
                       tr,
                       trd,
                       wcW,
                       wcL,
                       HSH.Command.unsetenv,
                       uniq,
                      ) where

import Data.List (genericLength, intersperse, isInfixOf, nub)
import Data.Char (toLower, toUpper)
import Text.Regex (matchRegex, mkRegex)
import Text.Printf (printf)
import Control.Monad (foldM)
import System.Directory hiding (createDirectory, isSymbolicLink)
import qualified Control.Exception as E 
-- import System.FilePath (splitPath)

#ifdef __HSH_POSIX__
import System.Posix.Files (getFileStatus, isSymbolicLink, readSymbolicLink)
import System.Posix.User (getEffectiveUserName, getUserEntryForName, homeDirectory)
import System.Posix.Directory (createDirectory)
import System.Posix.Types (FileMode())
import System.Posix.IO
import System.Posix.Error
#endif

import System.Path (absNormPath, bracketCWD)
import System.Exit
import System.IO
import System.Process
import qualified System.Directory as SD
import qualified System.Path.Glob as Glob (glob)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString as BS
import System.IO.Unsafe(unsafeInterleaveIO)
import HSH.Channel
import HSH.Command(setenv, unsetenv)

{- | Return the absolute path of the arg.  Raises an error if the
computation is impossible. This is a thin wrapper around
System.Path.absNormPath.  Unix/Linux users note:
System.Path.absNormPath is known to produce odd results when
a tilde expansion is requested; you might prefer 'glob' to this
function if you know your input is free of wildcards. See
https://github.com/jgoerzen/hsh/issues/7 for details. -}
abspath :: FilePath -> IO FilePath
abspath :: String -> IO String
abspath String
inp =
    do String
p <- IO String
pwd
       case String -> String -> Maybe String
absNormPath String
p String
inp of
         Maybe String
Nothing -> String -> IO String
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO String) -> String -> IO String
forall a b. (a -> b) -> a -> b
$ String
"Cannot make " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
forall a. Show a => a -> String
show String
inp String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" absolute within " String -> String -> String
forall a. [a] -> [a] -> [a]
++
                    String -> String
forall a. Show a => a -> String
show String
p
         Just String
x -> String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return String
x

{- | The filename part of a path -}
basename :: FilePath -> FilePath
basename :: String -> String
basename =  (String, String) -> String
forall a b. (a, b) -> b
snd ((String, String) -> String)
-> (String -> (String, String)) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> (String, String)
splitpath

{- | The directory part of a path -}
dirname :: FilePath -> FilePath
dirname :: String -> String
dirname = (String, String) -> String
forall a b. (a, b) -> a
fst ((String, String) -> String)
-> (String -> (String, String)) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> (String, String)
splitpath

{- | Changes the current working directory to the given path, executes
the given I\/O action, then changes back to the original directory,
even if the I\/O action raised an exception.

This is an alias for the MissingH function System.Path.bracketCWD. -}
bracketCD :: FilePath -> IO a -> IO a
bracketCD :: forall a. String -> IO a -> IO a
bracketCD = String -> IO a -> IO a
forall a. String -> IO a -> IO a
bracketCWD

{- | Load the specified files and display them, one at a time.

The special file @-@ means to display the input.  If it is not given,
no input is processed at all.

@-@ may be given a maximum of one time.

See also 'catBytes' . -}
catFrom :: [FilePath] -> Channel -> IO Channel
catFrom :: [String] -> Channel -> IO Channel
catFrom [String]
fplist Channel
ichan =
    do ByteString
r <- (ByteString -> String -> IO ByteString)
-> ByteString -> [String] -> IO ByteString
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM ByteString -> String -> IO ByteString
foldfunc ByteString
BSL.empty [String]
fplist
       Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString -> Channel
forall a. Channelizable a => a -> Channel
toChannel ByteString
r)
    where foldfunc :: ByteString -> String -> IO ByteString
foldfunc ByteString
accum String
fp =
                  case String
fp of
                    String
"-" -> do ByteString
c <- Channel -> IO ByteString
chanAsBSL Channel
ichan
                              ByteString -> IO ByteString
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString -> ByteString -> ByteString
BSL.append ByteString
accum ByteString
c)
                    String
fn -> do ByteString
c <- String -> IO ByteString
BSL.readFile String
fn
                             ByteString -> IO ByteString
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString -> ByteString -> ByteString
BSL.append ByteString
accum ByteString
c)

{- | Copy data from input to output, optionally with a fixed
maximum size, in bytes.  Processes data using ByteStrings internally,
so be aware of any possible UTF-8 conversions.

You may wish to use @hSetBuffering h (BlockBuffering Nothing)@ prior to calling
this function for optimal performance.

See also 'catFrom', 'catBytesFrom' -}
catBytes :: (Maybe Integer)    -- ^ Maximum amount of data to transfer
          -> Channel             -- ^ Handle for input
          -> IO Channel
catBytes :: Maybe Integer -> Channel -> IO Channel
catBytes Maybe Integer
count Channel
hr = Channel -> Maybe Integer -> Channel -> IO Channel
catBytesFrom Channel
hr Maybe Integer
count Channel
hr

{- | Generic version of 'catBytes'; reads data from specified Channel, and
ignores stdin.
-}

catBytesFrom :: Channel          -- ^ Handle to read from
             -> (Maybe Integer)  -- ^ Maximum amount of data to transfer
             -> Channel          -- ^ Handle for input (ignored)
             -> IO Channel
catBytesFrom :: Channel -> Maybe Integer -> Channel -> IO Channel
catBytesFrom (ChanHandle Handle
hr) Maybe Integer
count Channel
cignore =
    case Maybe Integer
count of
         Maybe Integer
Nothing -> Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Handle -> Channel
ChanHandle Handle
hr)
         Just Integer
m -> do ByteString
c <- Handle -> Int -> IO ByteString
BSL.hGet Handle
hr (Integer -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Integer
m)
                      Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString -> Channel
ChanBSL ByteString
c)
catBytesFrom Channel
cinput Maybe Integer
count Channel
cignore =
    case Maybe Integer
count of
      Maybe Integer
Nothing -> Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Channel
cinput
      Just Integer
m -> do ByteString
r <- Channel -> IO ByteString
chanAsBSL Channel
cinput
                   Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString -> Channel
ChanBSL (Int64 -> ByteString -> ByteString
BSL.take (Integer -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Integer
m) ByteString
r))

{- | Takes input, writes it to the specified file, and does not pass it on.
     The return value is the empty string.  See also 'catToBS', 
     'catToFIFO' -}
catTo :: FilePath -> Channel -> IO Channel
catTo :: String -> Channel -> IO Channel
catTo String
fp Channel
ichan =
    do Handle
ofile <- String -> IOMode -> IO Handle
openFile String
fp IOMode
WriteMode
       Bool -> Channel -> Handle -> IO ()
chanToHandle Bool
True Channel
ichan Handle
ofile
       Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Channel
ChanString String
"")

#ifdef __HSH_POSIX__

{- | Like 'catTo', but opens the destination in ReadWriteMode instead of
ReadOnlyMode.  Due to an oddity of the Haskell IO system, this is required
when writing to a named pipe (FIFO) even if you will never read from it.

This call will BLOCK all threads on open until a reader connects.

This is provided in addition to 'catTo' because you may want to cat to
something that you do not have permission to read from.

This function is only available on POSIX platforms.

See also 'catTo' -}
catToFIFO :: FilePath -> Channel -> IO Channel
catToFIFO :: String -> Channel -> IO Channel
catToFIFO String
fp Channel
ichan =
    do Handle
h <- String -> IO Handle
fifoOpen String
fp
       Bool -> Channel -> Handle -> IO ()
chanToHandle Bool
True Channel
ichan Handle
h
       Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Channel
ChanString String
"")

fifoOpen :: FilePath -> IO Handle
fifoOpen :: String -> IO Handle
fifoOpen String
fp = 
    do Fd
fd <- (Fd -> Bool) -> String -> String -> IO Fd -> IO Fd
forall a. (a -> Bool) -> String -> String -> IO a -> IO a
throwErrnoPathIf (Fd -> Fd -> Bool
forall a. Ord a => a -> a -> Bool
< Fd
0) String
"HSH fifoOpen" String
fp (IO Fd -> IO Fd) -> IO Fd -> IO Fd
forall a b. (a -> b) -> a -> b
$ 
             String -> OpenMode -> Maybe FileMode -> OpenFileFlags -> IO Fd
openFd String
fp OpenMode
WriteOnly Maybe FileMode
forall a. Maybe a
Nothing OpenFileFlags
defaultFileFlags
       Fd -> IO Handle
fdToHandle Fd
fd

#endif

{- | Like 'catTo', but appends to the file. -}
appendTo :: FilePath -> String -> IO String
appendTo :: String -> String -> IO String
appendTo String
fp String
inp =
    do String -> String -> IO ()
appendFile String
fp String
inp
       String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return String
""

{- | An alias for System.Directory.setCurrentDirectory.

Want to change to a user\'s home directory?  Try this:

> glob "~jgoerzen" >>= cd . head

See also 'bracketCD'.
-}
cd :: FilePath -> IO ()
cd :: String -> IO ()
cd = String -> IO ()
setCurrentDirectory

{- | Split a list by a given character and select the nth list.

> cut ' ' 2 "foo bar baz quux" -> "bar"
-}
cut :: Integer -> Char -> String -> String
cut :: Integer -> Char -> String -> String
cut Integer
pos = [Integer] -> Char -> String -> String
cutR [Integer
pos]

{- | Read all input and produce no output.  Discards input completely. -}
discard :: Channel -> IO Channel
discard :: Channel -> IO Channel
discard Channel
inh =
    do ByteString
c <- Channel -> IO ByteString
chanAsBSL Channel
inh
       Int64 -> IO Int64
forall a. a -> IO a
E.evaluate (ByteString -> Int64
BSL.length ByteString
c)
       Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Channel
ChanString String
"")

{- | Split a list by a given character and select ranges of the resultant lists.

> cutR [2..4] ' ' "foo bar baz quux foobar" -> "baz quux foobar"
> cutR [1..1000] ' ' "foo bar baz quux foobar" -> "bar baz quux foobar"
> cutR [-1000..1000] ' ' "foo bar baz quux foobar" -> "foo bar baz quux foobar"

   Note that too large and too small indices are essentially ignored.
-}
cutR :: [Integer] -> Char -> String -> String
cutR :: [Integer] -> Char -> String -> String
cutR [Integer]
nums Char
delim String
z = Int -> String -> String
forall a. Int -> [a] -> [a]
drop Int
1 (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ [String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [Char
delimChar -> String -> String
forall a. a -> [a] -> [a]
:String
x | (String
x, Integer
y) <- [String] -> [Integer] -> [(String, Integer)]
forall a b. [a] -> [b] -> [(a, b)]
zip [String]
string [Integer
0..], Integer -> [Integer] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
elem Integer
y [Integer]
nums]
     where string :: [String]
string = Char -> String -> [String]
split Char
delim String
z

{- | Takes a string and sends it on as standard output.

The input to this function is never read.

You can pass this thing a String, a ByteString, or even a Handle.

See also 'echoBS'. -}
echo :: Channelizable a => a -> Channel -> IO Channel
echo :: forall a. Channelizable a => a -> Channel -> IO Channel
echo a
inp Channel
_ = Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Channel -> IO Channel) -> (a -> Channel) -> a -> IO Channel
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Channel
forall a. Channelizable a => a -> Channel
toChannel (a -> IO Channel) -> a -> IO Channel
forall a b. (a -> b) -> a -> b
$ a
inp

{- | Search for the regexp in the lines.  Return those that match. -}
egrep :: String -> [String] -> [String]
egrep :: String -> [String] -> [String]
egrep String
pat = (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (Regex -> String -> Bool
ismatch Regex
regex)
    where regex :: Regex
regex = String -> Regex
mkRegex String
pat
          ismatch :: Regex -> String -> Bool
ismatch Regex
r String
inp = case Regex -> String -> Maybe [String]
matchRegex Regex
r String
inp of
                            Maybe [String]
Nothing -> Bool
False
                            Just [String]
_ -> Bool
True

{- | Search for the regexp in the lines.  Return those that do NOT match. -}
egrepV :: String -> [String] -> [String]
egrepV :: String -> [String] -> [String]
egrepV String
pat = (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Regex -> String -> Bool
ismatch Regex
regex)
    where regex :: Regex
regex = String -> Regex
mkRegex String
pat
          ismatch :: Regex -> String -> Bool
ismatch Regex
r String
inp = case Regex -> String -> Maybe [String]
matchRegex Regex
r String
inp of
                            Maybe [String]
Nothing -> Bool
False
                            Just [String]
_ -> Bool
True

{- | Exits with the specified error code. 0 indicates no error. -}
exit :: Int -> IO a
exit :: forall a. Int -> IO a
exit Int
code
    | Int
code Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 = ExitCode -> IO a
forall a. ExitCode -> IO a
exitWith ExitCode
ExitSuccess
    | Bool
otherwise = ExitCode -> IO a
forall a. ExitCode -> IO a
exitWith (Int -> ExitCode
ExitFailure Int
code)

{- | Takes a pattern.  Returns a list of names that match that pattern.
Handles:

>~username at beginning of file to expand to user's home dir
>? matches exactly one character
>* matches zero or more characters
>[list] matches any character in list
>[!list] matches any character not in list

The result of a tilde expansion on a nonexistant username is to do no
tilde expansion.

The tilde with no username equates to the current user.

Non-tilde expansion is done by the MissingH module System.Path.Glob. -}
glob :: FilePath -> IO [FilePath]
glob :: String -> IO [String]
glob inp :: String
inp@(Char
'~':String
remainder) =
    IO [String] -> (SomeException -> IO [String]) -> IO [String]
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
E.catch IO [String]
expanduser (\(SomeException
e::E.SomeException) -> String -> IO [String]
Glob.glob String
rest)
    where (String
username, String
rest) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
span (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'/') String
remainder
#ifdef __HSH_POSIX__
          expanduser :: IO [String]
expanduser =
              do String
lookupuser <-
                     if String
username String -> String -> Bool
forall a. Eq a => a -> a -> Bool
/= String
""
                        then String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return String
username
                        else IO String
getEffectiveUserName
                 UserEntry
ue <- String -> IO UserEntry
getUserEntryForName String
lookupuser
                 String -> IO [String]
Glob.glob (UserEntry -> String
homeDirectory UserEntry
ue String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
rest)
#else
          expanduser = fail "non-posix; will be caught above"
#endif
glob String
x = String -> IO [String]
Glob.glob String
x

{- | Search for the string in the lines.  Return those that match.
Same as:

> grep needle = filter (isInfixOf needle)
-}
grep :: String -> [String] -> [String]
grep :: String -> [String] -> [String]
grep = (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter ((String -> Bool) -> [String] -> [String])
-> (String -> String -> Bool) -> String -> [String] -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
isInfixOf

{- | Search for the string in the lines.  Return those that do NOT match. -}
grepV :: String -> [String] -> [String]
grepV :: String -> [String] -> [String]
grepV String
needle = (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
isInfixOf String
needle)

-- | Join lines of a file
joinLines :: [String] -> [String]
joinLines :: [String] -> [String]
joinLines = String -> [String]
forall a. a -> [a]
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> [String])
-> ([String] -> String) -> [String] -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat

#ifdef __HSH_POSIX__
{- | Creates the given directory.  A value of 0o755 for mode would be typical.

An alias for System.Posix.Directory.createDirectory.

The second argument will be ignored on non-POSIX systems. -}
mkdir :: FilePath -> FileMode -> IO ()
mkdir :: String -> FileMode -> IO ()
mkdir = String -> FileMode -> IO ()
createDirectory
#else
mkdir :: FilePath -> a -> IO ()
mkdir fp _ = SD.createDirectory fp
#endif

{- | Number each line of a file -}
numberLines :: [String] -> [String]
numberLines :: [String] -> [String]
numberLines = (Int -> String -> String) -> [Int] -> [String] -> [String]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith (String -> Int -> String -> String
forall r. PrintfType r => String -> r
printf String
"%3d %s") [(Int
1::Int)..]

{- | An alias for System.Directory.getCurrentDirectory. -}
pwd :: IO FilePath
pwd :: IO String
pwd = IO String
getCurrentDirectory

#ifdef __HSH_POSIX__
{- | Return the destination that the given symlink points to.

An alias for System.Posix.Files.readSymbolicLink

This function is only available on POSIX platforms. -}
readlink :: FilePath -> IO FilePath
readlink :: String -> IO String
readlink String
fp =
    do Bool
issym <- (String -> IO FileStatus
getFileStatus String
fp IO FileStatus -> (FileStatus -> IO Bool) -> IO Bool
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool -> IO Bool) -> (FileStatus -> Bool) -> FileStatus -> IO Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileStatus -> Bool
isSymbolicLink)
       if Bool
issym
           then String -> IO String
readSymbolicLink String
fp
           else String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return String
fp

{- | As 'readlink', but turns the result into an absolute path.

This function is only available on POSIX platforms. -}
readlinkabs :: FilePath -> IO FilePath
readlinkabs :: String -> IO String
readlinkabs String
inp =
       do Bool
issym <- (String -> IO FileStatus
getFileStatus String
inp IO FileStatus -> (FileStatus -> IO Bool) -> IO Bool
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool -> IO Bool) -> (FileStatus -> Bool) -> FileStatus -> IO Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileStatus -> Bool
isSymbolicLink)
          if Bool
issym
             then do String
rl <- String -> IO String
readlink String
inp
                     case String -> String -> Maybe String
absNormPath (String -> String
dirname String
inp) String
rl of
                       Maybe String
Nothing -> String -> IO String
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO String) -> String -> IO String
forall a b. (a -> b) -> a -> b
$ String
"Cannot make " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
forall a. Show a => a -> String
show String
rl String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" absolute within " String -> String -> String
forall a. [a] -> [a] -> [a]
++
                                  String -> String
forall a. Show a => a -> String
show (String -> String
dirname String
inp)
                       Just String
x -> String -> IO String
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return String
x
             else String -> IO String
abspath String
inp
#endif

{- | Reverse characters on each line (rev) -}
rev, revW :: [String] -> [String]
rev :: [String] -> [String]
rev = (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map String -> String
forall a. [a] -> [a]
reverse

{- | Reverse words on each line -}
revW :: [String] -> [String]
revW = (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map ([String] -> String
unwords ([String] -> String) -> (String -> [String]) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> [String]
forall a. [a] -> [a]
reverse ([String] -> [String])
-> (String -> [String]) -> String -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String]
words)

{- | Reverse lines in a String (like Unix tac).

Implemented as:

> tac = reverse

See 'uniq'. -}
tac :: [String] -> [String]
tac :: [String] -> [String]
tac = [String] -> [String]
forall a. [a] -> [a]
reverse

{- | Takes input, writes it to all the specified files, and passes it on.
This function does /NOT/ buffer input.

See also 'catFrom'. -}
tee :: [FilePath] -> Channel -> IO Channel
tee :: [String] -> Channel -> IO Channel
tee [String]
fplist Channel
inp = (String -> IO Handle) -> [String] -> Channel -> IO Channel
teeBSGeneric (\String
fp -> String -> IOMode -> IO Handle
openFile String
fp IOMode
WriteMode) [String]
fplist Channel
inp

#ifdef __HSH_POSIX__
{- | FIFO-safe version of 'tee'.

This call will BLOCK all threads on open until a reader connects.

This function is only available on POSIX platforms. -}
teeFIFO :: [FilePath] -> Channel -> IO Channel
teeFIFO :: [String] -> Channel -> IO Channel
teeFIFO [String]
fplist Channel
inp = (String -> IO Handle) -> [String] -> Channel -> IO Channel
teeBSGeneric String -> IO Handle
fifoOpen [String]
fplist Channel
inp
#endif

teeBSGeneric :: (FilePath -> IO Handle) 
             -> [FilePath] 
             -> Channel -> IO Channel
teeBSGeneric :: (String -> IO Handle) -> [String] -> Channel -> IO Channel
teeBSGeneric String -> IO Handle
openfunc [String]
fplist Channel
ichan =
    do [Handle]
handles <- (String -> IO Handle) -> [String] -> IO [Handle]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM String -> IO Handle
openfunc [String]
fplist
       ByteString
inp <- Channel -> IO ByteString
chanAsBSL Channel
ichan
       [ByteString]
resultChunks <- [Handle] -> [ByteString] -> IO [ByteString]
hProcChunks [Handle]
handles (ByteString -> [ByteString]
BSL.toChunks ByteString
inp)
       Channel -> IO Channel
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString -> Channel
ChanBSL (ByteString -> Channel) -> ByteString -> Channel
forall a b. (a -> b) -> a -> b
$ [ByteString] -> ByteString
BSL.fromChunks [ByteString]
resultChunks)
    where hProcChunks :: [Handle] -> [BS.ByteString] -> IO [BS.ByteString]
          hProcChunks :: [Handle] -> [ByteString] -> IO [ByteString]
hProcChunks [Handle]
handles [ByteString]
chunks = IO [ByteString] -> IO [ByteString]
forall a. IO a -> IO a
unsafeInterleaveIO (IO [ByteString] -> IO [ByteString])
-> IO [ByteString] -> IO [ByteString]
forall a b. (a -> b) -> a -> b
$
              case [ByteString]
chunks of
                [] -> do (Handle -> IO ()) -> [Handle] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Handle -> IO ()
hClose [Handle]
handles
                         [ByteString] -> IO [ByteString]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [ByteString
BS.empty]
                (ByteString
x:[ByteString]
xs) -> do (Handle -> IO ()) -> [Handle] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (\Handle
h -> Handle -> ByteString -> IO ()
BS.hPutStr Handle
h ByteString
x) [Handle]
handles
                             [ByteString]
remainder <- [Handle] -> [ByteString] -> IO [ByteString]
hProcChunks [Handle]
handles [ByteString]
xs
                             [ByteString] -> IO [ByteString]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ByteString
x ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: [ByteString]
remainder)
    
{- | Translate a character x to y, like:

>tr 'e' 'f'

Or, in sed,

>y//
 -}
tr :: Char -> Char -> String -> String
tr :: Char -> Char -> String -> String
tr Char
a Char
b = (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map (\Char
x -> if Char
x Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
a then Char
b else Char
x)

{- | Delete specified character in a string. -}
trd :: Char -> String -> String
trd :: Char -> String -> String
trd = (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
filter ((Char -> Bool) -> String -> String)
-> (Char -> Char -> Bool) -> Char -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
(/=)

{- | Remove duplicate lines from a file (like Unix uniq).

Takes a String representing a file or output and plugs it through lines and then nub to uniqify on a line basis. -}
uniq :: String -> String
uniq :: String -> String
uniq = [String] -> String
unlines ([String] -> String) -> (String -> [String]) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> [String]
forall a. Eq a => [a] -> [a]
nub ([String] -> [String])
-> (String -> [String]) -> String -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String]
lines

{- | Double space a file; add an empty line between each line. -}
space :: [String] -> [String]
space :: [String] -> [String]
space = String -> [String] -> [String]
forall a. a -> [a] -> [a]
intersperse String
""

{- | Inverse of double 'space'; drop all empty lines. -}
unspace :: [String] -> [String]
unspace :: [String] -> [String]
unspace = (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null)

{- | Convert a string to all lower case -}
lower :: String -> String
lower :: String -> String
lower = (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower

{- | Convert a string to all upper case -}
upper :: String -> String
upper :: String -> String
upper = (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toUpper

{- | Count number of lines.  Like wc -l -}
wcL :: [String] -> [String]
wcL :: [String] -> [String]
wcL [String]
inp = [Integer -> String
forall a. Show a => a -> String
show ([String] -> Integer
forall i a. Num i => [a] -> i
genericLength [String]
inp :: Integer)]

{- | Count number of words in a file (like wc -w) -}
wcW :: [String] -> [String]
wcW :: [String] -> [String]
wcW [String]
inp = [Integer -> String
forall a. Show a => a -> String
show (([String] -> Integer
forall i a. Num i => [a] -> i
genericLength ([String] -> Integer) -> [String] -> Integer
forall a b. (a -> b) -> a -> b
$ String -> [String]
words (String -> [String]) -> String -> [String]
forall a b. (a -> b) -> a -> b
$ [String] -> String
unlines [String]
inp) :: Integer)]

{- Utility function.
> split ' ' "foo bar baz" -> ["foo","bar","baz"] -}
split :: Char -> String -> [String]
split :: Char -> String -> [String]
split Char
c String
s = case String
rest of
              []     -> [String
chunk]
              Char
_:String
rst -> String
chunk String -> [String] -> [String]
forall a. a -> [a] -> [a]
: Char -> String -> [String]
split Char
c String
rst
    where (String
chunk, String
rest) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
==Char
c) String
s

-- TODO: Perhaps simplify to make use of split
splitpath :: String -> (String, String)
splitpath :: String -> (String, String)
splitpath String
"" = (String
".", String
".")
splitpath String
"/" = (String
"/", String
"/")
splitpath String
p
    | String -> Char
forall a. HasCallStack => [a] -> a
last String
p Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/' = String -> (String, String)
splitpath (String -> String
forall a. HasCallStack => [a] -> [a]
init String
p)
    | Bool -> Bool
not (Char
'/' Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` String
p) = (String
".", String
p)
    | String -> Char
forall a. HasCallStack => [a] -> a
head String
p Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/' Bool -> Bool -> Bool
&& String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ((Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
filter (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/') String
p) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1 = (String
"/", String -> String
forall a. HasCallStack => [a] -> [a]
tail String
p)
    | Bool
otherwise = (\(String
base, String
dir) -> (String -> String
forall a. [a] -> [a]
reverse (String -> String
forall a. HasCallStack => [a] -> [a]
tail String
dir), String -> String
forall a. [a] -> [a]
reverse String
base))
        ((Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/') (String -> String
forall a. [a] -> [a]
reverse String
p))