Revision 9fb621af src/Ganeti/Utils.hs

b/src/Ganeti/Utils.hs
48 48
  , getCurrentTime
49 49
  , clockTimeToString
50 50
  , chompPrefix
51
  , wrap
52
  , trim
51 53
  ) where
52 54

  
53 55
import Data.Char (toUpper, isAlphaNum, isDigit, isSpace)
......
326 328
  if pfx `isPrefixOf` str || str == init pfx
327 329
    then Just $ drop (length pfx) str
328 330
    else Nothing
331

  
332
-- | Breaks a string in lines with length \<= maxWidth.
333
--
334
-- NOTE: The split is OK if:
335
--
336
-- * It doesn't break a word, i.e. the next line begins with space
337
--   (@isSpace . head $ rest@) or the current line ends with space
338
--   (@null revExtra@);
339
--
340
-- * It breaks a very big word that doesn't fit anyway (@null revLine@).
341
wrap :: Int      -- ^ maxWidth
342
     -> String   -- ^ string that needs wrapping
343
     -> [String] -- ^ string \"broken\" in lines
344
wrap maxWidth = filter (not . null) . map trim . wrap0
345
  where wrap0 :: String -> [String]
346
        wrap0 text
347
          | length text <= maxWidth = [text]
348
          | isSplitOK               = line : wrap0 rest
349
          | otherwise               = line' : wrap0 rest'
350
          where (line, rest) = splitAt maxWidth text
351
                (revExtra, revLine) = break isSpace . reverse $ line
352
                (line', rest') = (reverse revLine, reverse revExtra ++ rest)
353
                isSplitOK =
354
                  null revLine || null revExtra || startsWithSpace rest
355
                startsWithSpace (x:_) = isSpace x
356
                startsWithSpace _     = False
357

  
358
-- | Removes surrounding whitespace. Should only be used in small
359
-- strings.
360
trim :: String -> String
361
trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace

Also available in: Unified diff