{-|

The @get@ command fetches data for the journal:

1. Transactions, by running a @getdata@ helper script in the journal's
   @data/@ directory (creating the directory if missing).
2. Market prices, by running a @getprices@ helper script in the journal's
   @prices/@ directory (creating the directory if missing).

Each phase is skipped (with a notice) when its helper is not present.

-}

{-# LANGUAGE CPP                 #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell     #-}

module Hledger.Cli.Commands.Get (
  getmode
 ,getcmd
) where

import Control.Exception (IOException, try)
import Control.Monad (unless, when, (>=>))
import Data.List (nub, sortOn)
#if !MIN_VERSION_base(4,20,0)
import Data.List (foldl')
#endif
import Data.Map.Strict qualified as M
import Data.Maybe (catMaybes)
import Data.Set qualified as S
import Data.Text qualified as T
import Data.Text.IO qualified as T
import Data.Time.Calendar (Day)
import System.Console.CmdArgs.Explicit
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.Exit (ExitCode(..))
import System.FilePath (takeDirectory, (</>))
import System.IO (hPutStr, hPutStrLn, stderr)
import System.Process (cwd, proc, readCreateProcessWithExitCode)

import Hledger
import Hledger.Cli.CliOptions


-- ====================================================================
-- 1. Command entry point
-- ====================================================================

-- | Command line options for this command.
getmode :: Mode RawOpts
getmode = String
-> [Flag RawOpts]
-> [(String, [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Get.txt")
  [[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"transactions"] (String -> RawOpts -> RawOpts
setboolopt String
"transactions") String
"fetch transactions only"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"prices"]       (String -> RawOpts -> RawOpts
setboolopt String
"prices")       String
"fetch prices only"
  ,[String] -> (RawOpts -> RawOpts) -> String -> Flag RawOpts
forall a. [String] -> (a -> a) -> String -> Flag a
flagNone [String
"dry-run"] (String -> RawOpts -> RawOpts
setboolopt String
"dry-run") String
"just print the commands that would be run"
  -- The -o/--output flag is disabled for now: it only meaningfully applies
  -- to the prices phase, which is awkward in the combined command.
  -- The supporting code paths below are preserved so this can be re-enabled
  -- easily later.
  -- ,flagReq  ["output","o"] (\s opts -> Right $ setopt "output" s opts) "FILE"
  --    "write all prices to FILE (or - for stdout) instead of per-commodity prices/<COMM>.prices files"
  ]
  [(String, [Flag RawOpts])]
cligeneralflagsgroups2
  [Flag RawOpts]
hiddenflags
  ([], Maybe (Arg RawOpts)
forall a. Maybe a
Nothing)

-- | The get command. By default runs both phases (data then prices);
-- with -t/--transactions or -p/--prices, runs only the selected phase(s).
getcmd :: CliOpts -> Journal -> IO ()
getcmd :: CliOpts -> Journal -> IO ()
getcmd opts :: CliOpts
opts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts} Journal
j = do
  let
    txns :: Bool
txns    = String -> RawOpts -> Bool
boolopt String
"transactions" RawOpts
rawopts
    prices :: Bool
prices  = String -> RawOpts -> Bool
boolopt String
"prices" RawOpts
rawopts
    noflags :: Bool
noflags = Bool -> Bool
not Bool
txns Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
prices
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool
txns   Bool -> Bool -> Bool
|| Bool
noflags) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ CliOpts -> Journal -> IO ()
fetchData CliOpts
opts Journal
j
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool
prices Bool -> Bool -> Bool
|| Bool
noflags) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ CliOpts -> Journal -> IO ()
fetchPrices CliOpts
opts Journal
j

-- | Like 'warn' but throws away the trailing-action argument; for the common
-- "log a warning, then continue" pattern.
warn_ :: String -> IO ()
warn_ :: String -> IO ()
warn_ String
msg = String -> IO () -> IO ()
forall a. String -> a -> a
warn String
msg (() -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ())

-- | Show a helper script's command line on stderr (stdout is kept for data).
logCommand :: Bool -> String -> IO ()
logCommand :: Bool -> String -> IO ()
logCommand Bool
dryRun String
cmdline = Handle -> String -> IO ()
hPutStrLn Handle
stderr (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ (if Bool
dryRun then String
"would run: " else String
"running: ") String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
cmdline


-- ====================================================================
-- 2. Data fetching (transactions)
-- ====================================================================

dataScriptName :: FilePath
dataScriptName :: String
dataScriptName = String
"getdata"

-- | Run the data-fetching phase. Ensures the journal's data/ directory exists,
-- then if data/getdata is present, runs it with cwd = data/, forwarding both
-- its stdout and its stderr to our stderr (it saves its data in files, so its
-- output is progress information, and stdout is kept for data). If the helper
-- is missing, logs a skip notice and returns.
fetchData :: CliOpts -> Journal -> IO ()
fetchData :: CliOpts -> Journal -> IO ()
fetchData CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts} Journal
j = do
  let
    dryRun :: Bool
dryRun  = String -> RawOpts -> Bool
boolopt String
"dry-run" RawOpts
rawopts
    jdir :: String
jdir    = String -> String
takeDirectory (Journal -> String
journalFilePath Journal
j)
    dataDir :: String
dataDir = String
jdir String -> String -> String
</> String
dataDirName
    script :: String
script  = String
dataDir String -> String -> String
</> String
dataScriptName
  Bool -> String -> IO ()
createDirectoryIfMissing Bool
True String
dataDir
  exists <- String -> IO Bool
doesFileExist String
script
  if not exists
    then hPutStrLn stderr $ "no " <> script <> " script, skipping data fetch"
    else do
      let cmdline = String
"cd " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
dataDir String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" && " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
dataScriptName
      logCommand dryRun cmdline
      unless dryRun $ do
        eres <- try (readCreateProcessWithExitCode (proc script []){cwd = Just dataDir} "")
                  :: IO (Either IOException (ExitCode, String, String))
        case eres of
          Left IOException
e ->
            String -> IO ()
warn_ (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
dataScriptName String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" failed: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> IOException -> String
forall a. Show a => a -> String
show IOException
e
          Right (ExitCode
ec, String
out, String
err) -> do
            Handle -> String -> IO ()
hPutStr Handle
stderr String
out
            Handle -> String -> IO ()
hPutStr Handle
stderr String
err
            case ExitCode
ec of
              ExitFailure Int
n -> String -> IO ()
warn_ (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
dataScriptName String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" exited " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
n
              ExitCode
ExitSuccess   -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()


-- ====================================================================
-- 3. Prices fetching
-- ====================================================================

pricesScriptName :: FilePath
pricesScriptName :: String
pricesScriptName = String
"getprices"

pricesDirName :: FilePath
pricesDirName :: String
pricesDirName = String
"prices"

-- | The path of the per-commodity prices file in 'dir' for the given code.
pricesFileFor :: FilePath -> CurrencyCode -> FilePath
pricesFileFor :: String -> Text -> String
pricesFileFor String
dir Text
code = String
dir String -> String -> String
</> String
pricesDirName String -> String -> String
</> Text -> String
T.unpack Text
code String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
".prices"

-- | Parse a journal-format text blob and extract its P directives.
parsePrices :: T.Text -> IO (Either String [PriceDirective])
parsePrices :: Text -> IO (Either String [PriceDirective])
parsePrices Text
txt = do
  hdl <- Text -> IO Handle
textToHandle Text
txt
  fmap jpricedirectives <$> runExceptT (readJournal definputopts Nothing hdl)

-- | How the command's stdout will be presented, used only for logging.
-- The actual file write is done by the merge code at the end of the run.
data Redirect
  = ToStdout         -- ^ stdout (-o -); shown without any "> ..." suffix
  | ToFile FilePath  -- ^ collected into a file; shown as " >FILE"

redirSuffix :: Redirect -> String
redirSuffix :: Redirect -> String
redirSuffix Redirect
ToStdout    = String
""
redirSuffix (ToFile String
f)  = String
" >" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
f

-- | Run the prices-fetching phase. Ensures the journal's prices/ directory
-- exists, then if prices/getprices is present, iterates over journal commodities
-- and invokes the helper once per commodity, merging results into
-- prices/<COMM>.prices files. If the helper is missing, logs a skip notice
-- and returns.
fetchPrices :: CliOpts -> Journal -> IO ()
fetchPrices :: CliOpts -> Journal -> IO ()
fetchPrices CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts} Journal
j = do
  let
    dryRun :: Bool
dryRun  = String -> RawOpts -> Bool
boolopt String
"dry-run" RawOpts
rawopts
    moutput :: Maybe String
moutput = case String -> RawOpts -> String
stringopt String
"output" RawOpts
rawopts of
                String
"" -> Maybe String
forall a. Maybe a
Nothing
                String
s  -> String -> Maybe String
forall a. a -> Maybe a
Just String
s
    jdir :: String
jdir     = String -> String
takeDirectory (Journal -> String
journalFilePath Journal
j)
    pricesDir :: String
pricesDir = String
jdir String -> String -> String
</> String
pricesDirName
    script :: String
script    = String
pricesDir String -> String -> String
</> String
pricesScriptName
  Bool -> String -> IO ()
createDirectoryIfMissing Bool
True String
pricesDir
  exists <- String -> IO Bool
doesFileExist String
script
  if not exists
    then hPutStrLn stderr $ "no " <> script <> " script, skipping prices fetch"
    else do
      today <- getCurrentDay
      let
        base      = Journal -> Text
journalBaseCurrencyCode Journal
j
        commspans = [Posting] -> Map Text (Day, Day)
commodityDateSpansByCode (Journal -> [Posting]
journalPostings Journal
j)
        codes     = [Text] -> [Text]
forall a. Eq a => [a] -> [a]
nub ([Text] -> [Text]) -> ([Text] -> [Text]) -> [Text] -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Bool) -> [Text] -> [Text]
forall a. (a -> Bool) -> [a] -> [a]
filter (Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text
base) ([Text] -> [Text]) -> ([Text] -> [Text]) -> [Text] -> [Text]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
toCurrencyCode ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ Journal -> [Text]
journalCommoditiesUsed Journal
j
        runFor    = String
-> Text
-> Map Text (Day, Day)
-> Day
-> Bool
-> Redirect
-> Text
-> IO (Maybe Text)
runFetch String
script Text
base Map Text (Day, Day)
commspans Day
today Bool
dryRun
      case moutput of
        Just String
"-" ->
          (Text -> IO ()) -> [Text] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (\Text
code -> Redirect -> Text -> IO (Maybe Text)
runFor Redirect
ToStdout Text
code IO (Maybe Text) -> (Maybe Text -> IO ()) -> IO ()
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO () -> (Text -> IO ()) -> Maybe Text -> IO ()
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (() -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()) Text -> IO ()
T.putStr) [Text]
codes
        Just String
outfile -> do
          outs <- (Text -> IO (Maybe Text)) -> [Text] -> IO [Maybe Text]
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 (Redirect -> Text -> IO (Maybe Text)
runFor (String -> Redirect
ToFile String
outfile)) [Text]
codes
          let combined = [Text] -> Text
T.concat ([Maybe Text] -> [Text]
forall a. [Maybe a] -> [a]
catMaybes [Maybe Text]
outs)
          unless (T.null combined) $
            mergeAndWritePrices outfile combined >>= reportOutcome outfile
        Maybe String
Nothing ->
          (Text -> IO ()) -> [Text] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (\Text
code -> do
                  let outfile :: String
outfile = String -> Text -> String
pricesFileFor String
jdir Text
code
                  mout <- Redirect -> Text -> IO (Maybe Text)
runFor (String -> Redirect
ToFile String
outfile) Text
code
                  maybe (return ()) (mergeAndWritePrices outfile >=> reportOutcome outfile) mout)
                [Text]
codes

-- | Fetch prices for one commodity. Logs the command line (see 'logCommand'),
-- runs the script (unless dry-run), and forwards its stderr.
-- Returns 'Nothing' if there are no prices to write — either because the
-- script failed (in which case a warning has been logged to stderr) or
-- because it produced no output. Otherwise returns 'Just' the captured stdout.
runFetch :: FilePath -> CurrencyCode -> M.Map CurrencyCode (Day, Day) -> Day -> Bool
         -> Redirect -> CurrencyCode -> IO (Maybe T.Text)
runFetch :: String
-> Text
-> Map Text (Day, Day)
-> Day
-> Bool
-> Redirect
-> Text
-> IO (Maybe Text)
runFetch String
script Text
base Map Text (Day, Day)
commspans Day
today Bool
dryRun Redirect
redir Text
code =
  case Text -> Map Text (Day, Day) -> Maybe (Day, Day)
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Text
code Map Text (Day, Day)
commspans of
    Maybe (Day, Day)
Nothing -> Maybe Text -> IO (Maybe Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Text
forall a. Maybe a
Nothing
    Just (Day
start, Day
_end) -> do
      let code' :: String
code'   = Text -> String
T.unpack Text
code
          args :: [String]
args    = [Text -> String
T.unpack Text
base, String
code', Day -> String
forall a. Show a => a -> String
show Day
start, Day -> String
forall a. Show a => a -> String
show Day
today]
          cmdline :: String
cmdline = [String] -> String
unwords (String
pricesScriptName String -> [String] -> [String]
forall a. a -> [a] -> [a]
: [String]
args) String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Redirect -> String
redirSuffix Redirect
redir
      Bool -> String -> IO ()
logCommand Bool
dryRun String
cmdline
      if Bool
dryRun
        then Maybe Text -> IO (Maybe Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Text
forall a. Maybe a
Nothing
        else do
          eres <- IO (ExitCode, String, String)
-> IO (Either IOException (ExitCode, String, String))
forall e a. Exception e => IO a -> IO (Either e a)
try (CreateProcess -> String -> IO (ExitCode, String, String)
readCreateProcessWithExitCode (String -> [String] -> CreateProcess
proc String
script [String]
args) String
"")
                    :: IO (Either IOException (ExitCode, String, String))
          case eres of
            Left IOException
e -> do
              String -> IO ()
warn_ (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
pricesScriptName String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" failed for " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
code' String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
": " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> IOException -> String
forall a. Show a => a -> String
show IOException
e
              Maybe Text -> IO (Maybe Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Text
forall a. Maybe a
Nothing
            Right (ExitCode
ec, String
out, String
err) -> do
              Handle -> String -> IO ()
hPutStr Handle
stderr String
err
              case ExitCode
ec of
                ExitFailure Int
n -> do
                  String -> IO ()
warn_ (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
pricesScriptName String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" exited " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
n String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" for " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
code'
                  Maybe Text -> IO (Maybe Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Text
forall a. Maybe a
Nothing
                ExitCode
ExitSuccess ->
                  Maybe Text -> IO (Maybe Text)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Text -> IO (Maybe Text)) -> Maybe Text -> IO (Maybe Text)
forall a b. (a -> b) -> a -> b
$ if String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
out then Maybe Text
forall a. Maybe a
Nothing else Text -> Maybe Text
forall a. a -> Maybe a
Just (String -> Text
T.pack String
out)

-- | Key by which we deduplicate two P directives.
priceKey :: PriceDirective -> (Day, CommoditySymbol, CommoditySymbol)
priceKey :: PriceDirective -> (Day, Text, Text)
priceKey PriceDirective
pd = (PriceDirective -> Day
pddate PriceDirective
pd, PriceDirective -> Text
pdcommodity PriceDirective
pd, Amount -> Text
acommodity (PriceDirective -> Amount
pdamount PriceDirective
pd))

-- | Outcome of attempting to merge new prices into a file.
data MergeOutcome
  = MergedWritten Int Int       -- ^ wrote the file: existing kept, new added
  | NothingNew                  -- ^ no new keys; file untouched
  | NotPureFileRefused          -- ^ existing file has non-price content; refused
  | PriceParseError String      -- ^ couldn't parse a prices blob

-- | Quick textual safeguard: file contains only P directives and blank lines.
isPurePricesFile :: T.Text -> Bool
isPurePricesFile :: Text -> Bool
isPurePricesFile =
  (Text -> Bool) -> [Text] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (\Text
line -> let l :: Text
l = Text -> Text
T.strip Text
line in Text -> Bool
T.null Text
l Bool -> Bool -> Bool
|| Text
"P" Text -> Text -> Bool
`T.isPrefixOf` Text
l)
  ([Text] -> Bool) -> (Text -> [Text]) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Text]
T.lines

-- | Load existing P directives from a file. Empty list if file is missing.
-- Returns Left if the file exists but contains content other than P
-- directives / blank lines, or if it can't be parsed.
loadExistingPrices :: FilePath -> IO (Either MergeOutcome [PriceDirective])
loadExistingPrices :: String -> IO (Either MergeOutcome [PriceDirective])
loadExistingPrices String
f = do
  exists <- String -> IO Bool
doesFileExist String
f
  if not exists
    then return (Right [])
    else do
      txt <- T.readFile f
      if not (isPurePricesFile txt)
        then return (Left NotPureFileRefused)
        else either (Left . PriceParseError) Right <$> parsePrices txt

-- | Merge new prices into a destination file (creating if needed).
-- 'newcontent' is the raw text we'd otherwise write — a journal-format
-- blob produced by the helper. Existing prices win on key conflicts;
-- new prices on unseen keys are added. The merged set is written sorted
-- ascending by (date, from, to). If nothing new would be added, the file
-- is left untouched.
mergeAndWritePrices :: FilePath -> T.Text -> IO MergeOutcome
mergeAndWritePrices :: String -> Text -> IO MergeOutcome
mergeAndWritePrices String
outfile Text
newcontent = do
  eexisting <- String -> IO (Either MergeOutcome [PriceDirective])
loadExistingPrices String
outfile
  case eexisting of
    Left MergeOutcome
outcome -> MergeOutcome -> IO MergeOutcome
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return MergeOutcome
outcome
    Right [PriceDirective]
existing -> do
      enew <- Text -> IO (Either String [PriceDirective])
parsePrices Text
newcontent
      case enew of
        Left String
e -> MergeOutcome -> IO MergeOutcome
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> MergeOutcome
PriceParseError (String
"could not parse new prices: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
e))
        Right [PriceDirective]
newpds -> do
          let existingKeys :: Set (Day, Text, Text)
existingKeys = [(Day, Text, Text)] -> Set (Day, Text, Text)
forall a. Ord a => [a] -> Set a
S.fromList ((PriceDirective -> (Day, Text, Text))
-> [PriceDirective] -> [(Day, Text, Text)]
forall a b. (a -> b) -> [a] -> [b]
map PriceDirective -> (Day, Text, Text)
priceKey [PriceDirective]
existing)
              added :: [PriceDirective]
added        = (PriceDirective -> Bool) -> [PriceDirective] -> [PriceDirective]
forall a. (a -> Bool) -> [a] -> [a]
filter (((Day, Text, Text) -> Set (Day, Text, Text) -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.notMember` Set (Day, Text, Text)
existingKeys) ((Day, Text, Text) -> Bool)
-> (PriceDirective -> (Day, Text, Text)) -> PriceDirective -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PriceDirective -> (Day, Text, Text)
priceKey) [PriceDirective]
newpds
          if [PriceDirective] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [PriceDirective]
added
            then MergeOutcome -> IO MergeOutcome
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return MergeOutcome
NothingNew
            else do
              let merged :: [PriceDirective]
merged = (PriceDirective -> (Day, Text, Text))
-> [PriceDirective] -> [PriceDirective]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn PriceDirective -> (Day, Text, Text)
priceKey ([PriceDirective]
existing [PriceDirective] -> [PriceDirective] -> [PriceDirective]
forall a. Semigroup a => a -> a -> a
<> [PriceDirective]
added)
                  out :: Text
out    = [Text] -> Text
T.unlines ((PriceDirective -> Text) -> [PriceDirective] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map PriceDirective -> Text
showPriceDirective [PriceDirective]
merged)
              Bool -> String -> IO ()
createDirectoryIfMissing Bool
True (String -> String
takeDirectory String
outfile)
              String -> Text -> IO ()
T.writeFile String
outfile Text
out
              MergeOutcome -> IO MergeOutcome
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Int -> Int -> MergeOutcome
MergedWritten ([PriceDirective] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [PriceDirective]
existing) ([PriceDirective] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [PriceDirective]
added))

-- | Write a one-line summary of a merge outcome to stderr.
reportOutcome :: FilePath -> MergeOutcome -> IO ()
reportOutcome :: String -> MergeOutcome -> IO ()
reportOutcome String
outfile MergeOutcome
outcome = Handle -> String -> IO ()
hPutStrLn Handle
stderr (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ case MergeOutcome
outcome of
  MergedWritten Int
ex Int
ad ->
    String
"wrote " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
outfile String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" (existing " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
ex String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
", added " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show Int
ad String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
")"
  MergeOutcome
NothingNew ->
    String
outfile String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
": no new prices"
  MergeOutcome
NotPureFileRefused ->
    String
"Refusing to overwrite " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
outfile String -> String -> String
forall a. Semigroup a => a -> a -> a
<>
    String
": it contains content other than P directives, which would be lost."
  PriceParseError String
msg ->
    String
outfile String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
": could not read existing prices: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
msg

-- | Identify the (earliest, latest) posting date for each commodity used in these postings' main amounts.
commodityDateSpansByCode :: [Posting] -> M.Map CurrencyCode (Day, Day)
commodityDateSpansByCode :: [Posting] -> Map Text (Day, Day)
commodityDateSpansByCode = (Map Text (Day, Day) -> Posting -> Map Text (Day, Day))
-> Map Text (Day, Day) -> [Posting] -> Map Text (Day, Day)
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Map Text (Day, Day) -> Posting -> Map Text (Day, Day)
addPosting Map Text (Day, Day)
forall k a. Map k a
M.empty
  where
    addPosting :: Map Text (Day, Day) -> Posting -> Map Text (Day, Day)
addPosting Map Text (Day, Day)
m Posting
p = (Map Text (Day, Day) -> Text -> Map Text (Day, Day))
-> Map Text (Day, Day) -> [Text] -> Map Text (Day, Day)
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (Day -> Map Text (Day, Day) -> Text -> Map Text (Day, Day)
forall {k} {b}.
(Ord k, Ord b) =>
b -> Map k (b, b) -> k -> Map k (b, b)
addCode (Posting -> Day
postingDate Posting
p)) Map Text (Day, Day)
m (Posting -> [Text]
codesIn Posting
p)
    addCode :: b -> Map k (b, b) -> k -> Map k (b, b)
addCode b
d Map k (b, b)
m k
c  = ((b, b) -> (b, b) -> (b, b))
-> k -> (b, b) -> Map k (b, b) -> Map k (b, b)
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith (b, b) -> (b, b) -> (b, b)
forall {a} {b}. (Ord a, Ord b) => (a, b) -> (a, b) -> (a, b)
merge k
c (b
d, b
d) Map k (b, b)
m
    merge :: (a, b) -> (a, b) -> (a, b)
merge (a
s1, b
e1) (a
s2, b
e2) = (a -> a -> a
forall a. Ord a => a -> a -> a
min a
s1 a
s2, b -> b -> b
forall a. Ord a => a -> a -> a
max b
e1 b
e2)
    codesIn :: Posting -> [Text]
codesIn Posting
p      = (Amount -> Text) -> [Amount] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map (Text -> Text
toCurrencyCode (Text -> Text) -> (Amount -> Text) -> Amount -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> Text
acommodity) ([Amount] -> [Text]) -> [Amount] -> [Text]
forall a b. (a -> b) -> a -> b
$ MixedAmount -> [Amount]
amountsRaw (Posting -> MixedAmount
pamount Posting
p)