@@ -18,6 +18,9 @@ import Data.List (intercalate)
1818import Data.Semigroup ((<>) )
1919import qualified Data.Set as Set
2020import Data.Version (showVersion )
21+ import Data.Time.Clock
22+
23+ import Control.Monad (when )
2124
2225import Options.Applicative
2326import Paths_tldr (version )
@@ -26,6 +29,8 @@ import System.Directory
2629 , createDirectory
2730 , removePathForcibly
2831 , doesFileExist
32+ , doesDirectoryExist
33+ , getModificationTime
2934 , getXdgDirectory
3035 )
3136import System.Environment (lookupEnv , getExecutablePath )
@@ -68,6 +73,8 @@ handleTldrOpts opts@TldrOpts {..} =
6873 UpdateIndex -> updateTldrPages
6974 About -> handleAboutFlag
7075 ViewPage voptions pages -> do
76+ performUpdate <- updateNecessary
77+ when performUpdate updateTldrPages
7178 let npage = intercalate " -" pages
7279 locale <-
7380 case languageOption voptions of
@@ -87,6 +94,21 @@ handleTldrOpts opts@TldrOpts {..} =
8794 ViewPage (englishViewOptions voptions) pages
8895 })
8996
97+ -- We update if the data directory does not exist.
98+ -- We also update if the cached pages version is older than 7 days.
99+ -- TODO: Make the auto-update interval configurable.
100+ -- TODO: Add command line option to skip auto update.
101+ updateNecessary :: IO Bool
102+ updateNecessary = do
103+ dataDir <- getXdgDirectory XdgData tldrDirName
104+ dataDirExists <- doesDirectoryExist dataDir
105+ if not dataDirExists
106+ then return True
107+ else do
108+ lastCachedTime <- getModificationTime dataDir
109+ currentTime <- getCurrentTime
110+ return $ currentTime `diffUTCTime` lastCachedTime > 7 * nominalDay
111+
90112updateTldrPages :: IO ()
91113updateTldrPages = do
92114 dataDir <- getXdgDirectory XdgData tldrDirName
0 commit comments