@@ -206,6 +206,7 @@ module Turtle.Prelude (
206
206
, sort
207
207
, sortOn
208
208
, sortBy
209
+ , toLines
209
210
210
211
-- * Folds
211
212
, countChars
@@ -300,14 +301,16 @@ import Control.Exception (Exception, bracket, bracket_, finally, mask, throwIO)
300
301
import Control.Foldl (Fold (.. ), genericLength , handles , list , premap )
301
302
import qualified Control.Foldl
302
303
import qualified Control.Foldl.Text
303
- import Control.Monad (guard , liftM , msum , when , unless , (>=>) , mfilter )
304
+ import Control.Monad (foldM , guard , liftM , msum , when , unless , (>=>) , mfilter )
304
305
import Control.Monad.IO.Class (MonadIO (.. ))
305
306
import Control.Monad.Managed (MonadManaged (.. ), managed , managed_ , runManaged )
306
307
#ifdef mingw32_HOST_OS
307
308
import Data.Bits ((.&.) )
308
309
#endif
309
310
import Data.IORef (newIORef , readIORef , writeIORef )
310
311
import qualified Data.List as List
312
+ import Data.List.NonEmpty (NonEmpty (.. ))
313
+ import qualified Data.List.NonEmpty as NonEmpty
311
314
import Data.Monoid ((<>) )
312
315
import Data.Ord (comparing )
313
316
import qualified Data.Set as Set
@@ -354,7 +357,7 @@ import System.Posix (
354
357
touchFile )
355
358
import System.Posix.Files (createSymbolicLink )
356
359
#endif
357
- import Prelude hiding (FilePath )
360
+ import Prelude hiding (FilePath , lines )
358
361
359
362
import Turtle.Pattern (Pattern , anyChar , chars , match , selfless , sepBy )
360
363
import Turtle.Shell
@@ -2166,3 +2169,46 @@ sortOn f = sortBy (comparing f)
2166
2169
-- [(1,'a'),(2,'c'),(3,'d'),(3,'e'),(4,'b'),(7,'f')]
2167
2170
sortBy :: (Functor io , MonadIO io ) => (a -> a -> Ordering ) -> Shell a -> io [a ]
2168
2171
sortBy f s = List. sortBy f <$> fold s list
2172
+
2173
+ {-| Group an arbitrary stream of `Text` into newline-delimited `Line`s
2174
+
2175
+ >>> stdout (toLines ("ABC" <|> "DEF" <|> "GHI")
2176
+ ABCDEFGHI
2177
+ >>> stdout (toLines empty) -- Note that this always emits at least 1 `Line`
2178
+
2179
+ >>> stdout (toLines ("ABC\nDEF" <|> "" <|> "GHI\nJKL"))
2180
+ ABC
2181
+ DEFGHI
2182
+ JKL
2183
+ -}
2184
+ toLines :: Shell Text -> Shell Line
2185
+ toLines (Shell k) = Shell k'
2186
+ where
2187
+ -- step :: x -> Line -> IO x
2188
+ -- begin :: x
2189
+ -- done :: x -> IO r
2190
+ --
2191
+ -- step' :: y -> Text -> IO y
2192
+ -- begin :: y
2193
+ -- done :: y -> IO r
2194
+ k' (FoldShell step begin done) =
2195
+ k (FoldShell step' begin' done')
2196
+ where
2197
+ step' (Pair x prefix) text = do
2198
+ let suffix :| lines = Turtle.Line. textToLines text
2199
+
2200
+ let line = prefix <> suffix
2201
+
2202
+ let lines' = line :| lines
2203
+
2204
+ x' <- foldM step x (NonEmpty. init lines')
2205
+
2206
+ let prefix' = NonEmpty. last lines'
2207
+
2208
+ return (Pair x' prefix')
2209
+
2210
+ begin' = (Pair begin " " )
2211
+
2212
+ done' (Pair x prefix) = do
2213
+ x' <- step x prefix
2214
+ done x'
0 commit comments