Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Break command args into chunks under system limit like what xargs does #63

Merged
merged 1 commit into from
Mar 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions Retrie/Options.hs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
--
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
module Retrie.Options
Expand Down Expand Up @@ -487,13 +488,28 @@ runGrepChain targetDir verbosity GrepCommands{..} = foldM (commandStep targetDir

-- | run a command with a list of files as quoted arguments
commandStep :: FilePath -> Verbosity -> [FilePath]-> CommandLine -> IO [FilePath]
commandStep targetDir verbosity files cmd = doCmd targetDir verbosity (cmd <> formatPaths files)
where
formatPaths [] = ""
formatPaths xs = " " <> unwords (map quotePath xs)
commandStep targetDir verbosity files cmd =
fmap concat $ forM (chunkifyArgs $ map quotePath files) $ \args ->
doCmd targetDir verbosity $ cmd <> " " <> unwords args

quotePath :: FilePath -> FilePath
quotePath x = "'" <> x <> "'"

-- Split arguments into chunks whose size does not exceed 'argMax'.
-- Note that @chunkifyArgs []@ returns @[[]]@ intentionally.
chunkifyArgs :: [String] -> [[String]]
chunkifyArgs = go 0 []
where
go _ acc [] = [reverse acc]
go n acc (arg: args)
| n <= 0 || n + len <= argMax = go (n + len) (arg: acc) args
| otherwise = reverse acc: go len [arg] args
where
len = length arg + 1

-- | Hardcoded default @--max-args=max-args@ used by @xargs@.
argMax :: Int
argMax = 128 * 1024

doCmd :: FilePath -> Verbosity -> String -> IO [FilePath]
doCmd targetDir verbosity shellCmd = do
Expand Down
Loading