+ rc_cfg <- OC.from_rc
+ cmd_cfg <- get_args
+
+ -- Merge the config file options with the command-line ones,
+ -- prefering the command-line ones.
+ let opt_config = rc_cfg <> cmd_cfg
+
+ -- Update a default config with any options that have been set in
+ -- either the config file or on the command-line. We initialize
+ -- logging before the missing parameter checks below so that we can
+ -- log the errors.
+ let cfg = (def :: Configuration) `merge_optional` opt_config
+ init_logging (log_level cfg) (log_file cfg) (syslog cfg)
+
+ -- Check the optional config for missing required options.
+ when (null $ OC.xml_files opt_config) $ do
+ report_error "No XML files given."
+ exitWith (ExitFailure exit_no_xml_files)
+
+ -- We don't do this in parallel (for now?) to keep the error
+ -- messages nice and linear.
+ results <- mapM (import_file cfg) (OC.xml_files opt_config)
+
+ -- Zip the results with the files list to find out which ones can be
+ -- deleted.
+ let result_pairs = zip (OC.xml_files opt_config) results
+ let victims = [ (p,c) | (p, Just c) <- result_pairs ]
+ let imported_count = sum $ map snd victims
+ report_info $ "Imported " ++ (show imported_count) ++ " records total."
+ mapM_ ((kill True) . fst) victims
+
+ where
+ -- | Wrap these two actions into one function so that we don't
+ -- report that the file was removed if the exception handler is
+ -- run.
+ remove_and_report path = do
+ removeFile path
+ report_info $ "Removed processed file " ++ path ++ "."
+
+ -- | Try to remove @path@ and potentially try again.
+ kill try_again path =
+ (remove_and_report path) `catchIOError` exception_handler
+ where
+ -- | A wrapper around threadDelay which takes seconds instead of
+ -- microseconds as its argument.
+ thread_sleep :: Int -> IO ()
+ thread_sleep seconds = do
+ let microseconds = seconds * (10 ^ (6 :: Int))
+ threadDelay microseconds
+
+ -- | If we can't remove the file, report that, and try once
+ -- more after waiting a few seconds.
+ exception_handler :: IOError -> IO ()
+ exception_handler e = do
+ report_error (show e)
+ report_error $ "Failed to remove imported file " ++ path ++ "."
+ if try_again then do
+ report_info "Waiting 5 seconds to attempt removal again..."
+ thread_sleep 5
+ kill False path
+ else
+ report_info $ "Giving up on " ++ path ++ "."