| 1 |
{-| |
| 2 |
|
| 3 |
Check and show the status of the hledger installation. |
| 4 |
|
| 5 |
-} |
| 6 |
{- |
| 7 |
Old design notes: |
| 8 |
|
| 9 |
## Goals |
| 10 |
- Make getting started with hledger and PTA easier and quicker, to |
| 11 |
(a) make this practical for more people (non techies, busy techies..) |
| 12 |
(b) free up more time and energy for learning and doing PTA and finance |
| 13 |
|
| 14 |
Subgoals: |
| 15 |
- Reduce the special knowledge and docs needed after install, to get a standard setup working (especially on windows) |
| 16 |
- Help with discovery and setup of advanced quality of life terminal features |
| 17 |
- Assist with setting up a first or new journal file |
| 18 |
- Deliver relevant install/setup/config expertise more efficiently, freeing up dev and support time |
| 19 |
|
| 20 |
## Design |
| 21 |
Why a built in command and not a shell script, haskell script, or docs ? |
| 22 |
So it is available and runs reliably anywhere a hledger executable runs, and so it can detect more context-specific advice. |
| 23 |
(Optionally use shell or haskell scripts for prototyping, if that's helpful) |
| 24 |
|
| 25 |
## Setup checks |
| 26 |
Somewhat ordered. |
| 27 |
These deal with the complexities of terminals, the shell, GHC, hledger, and the user's machine, locale, and data. |
| 28 |
Initially just informational hints. |
| 29 |
Later, add automated or interactive diagnosis and repair attempts, |
| 30 |
and semi-persistent state (invalidated at suitable times). |
| 31 |
These checks are a necessary evil/stopgap; long term, automate/replace/remove them whenever possible. |
| 32 |
|
| 33 |
-} |
| 34 |
|
| 35 |
-- {-# LANGUAGE DeriveGeneric #-} |
| 36 |
{-# LANGUAGE OverloadedStrings #-} |
| 37 |
-- {-# LANGUAGE NamedFieldPuns #-} |
| 38 |
-- {-# LANGUAGE RecordWildCards #-} |
| 39 |
{-# LANGUAGE ScopedTypeVariables #-} |
| 40 |
{-# LANGUAGE TemplateHaskell #-} |
| 41 |
|
| 42 |
{-# OPTIONS_GHC -Wno-name-shadowing #-} |
| 43 |
{-# OPTIONS_GHC -Wno-unused-top-binds #-} |
| 44 |
{-# LANGUAGE MultiWayIf #-} |
| 45 |
{-# LANGUAGE RecordWildCards #-} |
| 46 |
-- {-# OPTIONS_GHC -Wno-unused-matches #-} |
| 47 |
|
| 48 |
module Hledger.Cli.Commands.Setup ( |
| 49 |
setupmode |
| 50 |
,setup |
| 51 |
) |
| 52 |
where |
| 53 |
|
| 54 |
import Control.Concurrent (rtsSupportsBoundThreads) |
| 55 |
import Control.Exception |
| 56 |
import Control.Monad |
| 57 |
-- import Data.ByteString qualified as B |
| 58 |
import Data.Char |
| 59 |
import Data.Default (def) |
| 60 |
import Data.List |
| 61 |
import Data.Map qualified as M |
| 62 |
import Data.Maybe |
| 63 |
import Data.Text qualified as T |
| 64 |
import Data.Text.Encoding qualified as T |
| 65 |
import Data.Version qualified (showVersion) |
| 66 |
import Network.HTTP.Client |
| 67 |
import Network.HTTP.Types (statusCode, hLocation) |
| 68 |
import Network.HTTP.Req as R |
| 69 |
import Safe |
| 70 |
import System.Directory |
| 71 |
import System.Environment (getEnvironment, lookupEnv) |
| 72 |
import System.Exit |
| 73 |
import System.FilePath |
| 74 |
import System.Info |
| 75 |
import System.Process |
| 76 |
import Text.Printf (printf) |
| 77 |
|
| 78 |
import Hledger |
| 79 |
import Hledger.Cli.CliOptions |
| 80 |
import Hledger.Cli.Conf |
| 81 |
import Hledger.Cli.Version |
| 82 |
import System.IO (localeEncoding, stdout, hFlush) |
| 83 |
|
| 84 |
|
| 85 |
setupmode = hledgerCommandMode |
| 86 |
$(embedFileRelative "Hledger/Cli/Commands/Setup.txt") |
| 87 |
[] |
| 88 |
[generalflagsgroup3] |
| 89 |
[] |
| 90 |
([], Nothing) |
| 91 |
|
| 92 |
|
| 93 |
{- | Test and print the status of various aspects of the hledger installation. |
| 94 |
May also show extra info and hints on how to fix problems. |
| 95 |
The goal is to detect and show as much useful information as possible, |
| 96 |
and to complete this task reliably regardless of what we find, |
| 97 |
without premature termination or misformatting. |
| 98 |
|
| 99 |
The tests are grouped into setup* routines, so named because they might do more |
| 100 |
than just test in future. |
| 101 |
|
| 102 |
This is the second version of setup. If it finds that the currently |
| 103 |
running hledger is not the one installed in PATH (by comparing --version output), |
| 104 |
it refuses to proceed further until that has been done. |
| 105 |
This means it can rely on all the latest features and use the hledger API |
| 106 |
within this process, simplifying things greatly. |
| 107 |
-} |
| 108 |
setup :: CliOpts -> Journal -> IO () |
| 109 |
setup _opts@CliOpts{rawopts_=_rawopts, reportspec_=_rspec} _ignoredj = do |
| 110 |
-- This command is not given a journal and should not use _ignoredj; |
| 111 |
-- instead read it ourselves when we are ready. |
| 112 |
putStrLn "Checking your hledger setup.." |
| 113 |
color <- useColorOnStdout |
| 114 |
when color $ |
| 115 |
putStrLn $ "Legend: " <> intercalate ", " [ |
| 116 |
good "good" |
| 117 |
,neutral "neutral" |
| 118 |
,warning "unknown" |
| 119 |
,bad "warning" |
| 120 |
] |
| 121 |
meconf <- setupHledger |
| 122 |
setupTerminal meconf |
| 123 |
setupJournal meconf |
| 124 |
putStr "\n" |
| 125 |
|
| 126 |
------------------------------------------------------------------------------ |
| 127 |
|
| 128 |
-- Returns Nothing if no config file was found, |
| 129 |
-- or Just the read error or config if it was found. |
| 130 |
setupHledger :: IO (Maybe (Either String Conf)) |
| 131 |
setupHledger = do |
| 132 |
pgroup "hledger" |
| 133 |
|
| 134 |
let |
| 135 |
os' |
| 136 |
| os=="darwin" = "macos" |
| 137 |
| os=="mingw32" = "windows" |
| 138 |
| otherwise = os |
| 139 |
mosversion <- getOSVersion |
| 140 |
let osdesc = os' <> maybe "" (" "<>) mosversion |
| 141 |
pdesc "is running on" |
| 142 |
putStrLn $ " " <> osdesc <> " on " <> arch |
| 143 |
|
| 144 |
pdesc "is built with a supported compiler/RTS" |
| 145 |
p (if rtsSupportsBoundThreads then Y else N) $ |
| 146 |
compilerName <> " " <> Data.Version.showVersion fullCompilerVersion |
| 147 |
<> if rtsSupportsBoundThreads then ", using threaded RTS" else ", RTS does not have threads enabled" |
| 148 |
|
| 149 |
pdesc "is a native binary for this machine ?" |
| 150 |
case hbinArch binaryinfo of |
| 151 |
Nothing -> p U $ "couldn't detect this binary's architecture" |
| 152 |
Just a | a /= arch -> p N $ "binary is for " <> a <> ", system is " <> arch <> ", may run slowly" |
| 153 |
Just a -> p Y a |
| 154 |
|
| 155 |
pdesc "is a released version ?" |
| 156 |
if isReleaseVersion $ hbinPackageVersion binaryinfo |
| 157 |
then p Y prognameandversion |
| 158 |
else i N prognameandversion |
| 159 |
|
| 160 |
pdesc "is up to date ? checking latest..." >> hFlush stdout |
| 161 |
elatestversionnumstr <- getLatestHledgerVersion |
| 162 |
case elatestversionnumstr of |
| 163 |
Left e -> p U ("couldn't read " <> latestHledgerVersionUrlStr <> " " <> e) |
| 164 |
Right latestversionnumstr -> |
| 165 |
case toVersion latestversionnumstr of |
| 166 |
Nothing -> p U "couldn't parse latest version number" |
| 167 |
Just latestversion -> p |
| 168 |
(if hbinPackageVersion binaryinfo >= latestversion then Y else N) |
| 169 |
("latest is " <> latestversionnumstr <> ", " <> showVersion (hbinPackageVersion binaryinfo) <> " is installed") |
| 170 |
|
| 171 |
pdesc "is installed in PATH (this version) ?" |
| 172 |
pathexes <- findExecutables progname |
| 173 |
let |
| 174 |
(failaction, failmsg) = |
| 175 |
-- (exitFailure , "Please install this hledger in PATH then run setup again.") |
| 176 |
(return () , " Some of this info may not apply to that hledger version. Continuing anyway..") |
| 177 |
case pathexes of |
| 178 |
[] -> p N failmsg >> failaction |
| 179 |
exe:_ -> do |
| 180 |
eerrout <- tryHledgerArgs [["--version", "--no-conf"], ["--version"]] |
| 181 |
case eerrout of |
| 182 |
Left err -> p U (progname <> " --version failed: " <> err) >> failaction |
| 183 |
Right out -> do |
| 184 |
case parseHledgerVersion out of |
| 185 |
Left _ -> p U ("couldn't parse " <> progname <> " --version: " <> rstrip out) >> exitFailure |
| 186 |
Right pathbin -> do |
| 187 |
let pathversion = hbinVersionOutput pathbin |
| 188 |
if pathversion /= prognameandversion |
| 189 |
then p N (chomp $ unlines [ |
| 190 |
"" |
| 191 |
," A different hledger version was found in PATH: " <> pathversion |
| 192 |
," at: " <> exe |
| 193 |
,failmsg |
| 194 |
]) >> failaction |
| 195 |
else p Y exe |
| 196 |
|
| 197 |
pdesc "has a system text encoding configured ?" |
| 198 |
let encoding = localeEncoding -- the initial system encoding |
| 199 |
if map toLower (show encoding) == "ascii" |
| 200 |
then p N (show encoding <> ", please configure an encoding for non-ascii data") |
| 201 |
else p Y (show encoding <> ", data files must use this encoding") |
| 202 |
|
| 203 |
-- pdesc "can handle UTF-8 text ?" |
| 204 |
-- let |
| 205 |
-- eAcuteUtf8 = B.pack [0xC3, 0xA9] |
| 206 |
-- eAcuteLatin1 = B.pack [0xE9] |
| 207 |
-- case T.decodeUtf8' eAcuteUtf8 of |
| 208 |
-- Left _ -> p N "hledger's docs and examples use UTF-8" |
| 209 |
-- Right t -> p Y (T.unpack t) |
| 210 |
|
| 211 |
-- pdesc "can report text decoding failures ?" |
| 212 |
-- i U (T.unpack $ T.decodeUtf8 eAcuteLatin1) |
| 213 |
|
| 214 |
pdesc "has a user config file ?" |
| 215 |
muf <- activeUserConfFile |
| 216 |
mlf <- activeLocalConfFile |
| 217 |
let |
| 218 |
(ok, msg) = case muf of |
| 219 |
Just f -> (Y, f <> if isJust mlf then " (overridden)" else "") |
| 220 |
Nothing -> (N, "") |
| 221 |
i ok msg |
| 222 |
|
| 223 |
pdesc "has a local config file ?" |
| 224 |
let |
| 225 |
(ok, msg) = case mlf of |
| 226 |
Just f -> (Y, f) |
| 227 |
Nothing -> (N, "") |
| 228 |
i ok msg |
| 229 |
|
| 230 |
if (isJust muf || isJust mlf) then do |
| 231 |
pdesc "the config file is readable ?" |
| 232 |
econf <- getConf def |
| 233 |
case econf of |
| 234 |
Left e -> p N e >> return (Just $ Left e) |
| 235 |
Right (conf, _) -> do |
| 236 |
p Y "" |
| 237 |
|
| 238 |
-- pdesc "common general options are configured ?" |
| 239 |
-- --infer-costs" |
| 240 |
-- print --explicit --infer-costs" |
| 241 |
|
| 242 |
return $ Just $ Right conf |
| 243 |
else |
| 244 |
return Nothing |
| 245 |
|
| 246 |
------------------------------------------------------------------------------ |
| 247 |
|
| 248 |
setupTerminal meconf = do |
| 249 |
pgroup "terminal" |
| 250 |
let |
| 251 |
-- Find the last opt/arg matched by a predicate in the general config, if there is one. |
| 252 |
conflookup predicate = case meconf of |
| 253 |
Just (Right conf) -> find predicate $ reverse $ confLookup "general" conf |
| 254 |
_ -> Nothing |
| 255 |
|
| 256 |
pdesc "the NO_COLOR variable is defined ?" |
| 257 |
mnocolor <- lookupEnv "NO_COLOR" |
| 258 |
case mnocolor of |
| 259 |
Nothing -> i N "" |
| 260 |
Just _ -> i Y "" |
| 261 |
|
| 262 |
meconfigcolor <- do |
| 263 |
pdesc "--color is configured by config file ?" |
| 264 |
let mcolorarg = conflookup (\a -> any (`isPrefixOf` a) ["--color", "--colour"]) |
| 265 |
case mcolorarg of |
| 266 |
Nothing -> i N "" >> return Nothing |
| 267 |
Just a -> do |
| 268 |
i Y a |
| 269 |
let |
| 270 |
arg = reverse $ takeWhile (`notElem` ['=',' ']) $ reverse a |
| 271 |
return $ Just $ parseYNA arg |
| 272 |
|
| 273 |
pdesc "hledger will use color by default ?" |
| 274 |
case (meconfigcolor, isJust mnocolor) of |
| 275 |
(Just (Right Yes), _) -> p Y "" |
| 276 |
(Just (Right No), _) -> i N "" |
| 277 |
(_, True) -> i N "" |
| 278 |
(_, False) -> p Y "" |
| 279 |
|
| 280 |
pdesc "the PAGER variable is defined ?" |
| 281 |
mv <- lookupEnv "PAGER" |
| 282 |
case mv of |
| 283 |
Nothing -> i N "" |
| 284 |
Just v -> i Y v |
| 285 |
|
| 286 |
pdesc "--pager is configured by config file ?" |
| 287 |
let mpagerarg = conflookup ("--pager" `isPrefixOf`) |
| 288 |
meconfpager <- case mpagerarg of |
| 289 |
Nothing -> i N "" >> return Nothing |
| 290 |
Just a -> do |
| 291 |
i Y a |
| 292 |
let arg = reverse $ takeWhile (`notElem` ['=',' ']) $ reverse a |
| 293 |
return $ Just $ parseYNA arg |
| 294 |
|
| 295 |
pdesc "hledger will use a pager when needed ?" |
| 296 |
mpager <- findPager |
| 297 |
case mpager of |
| 298 |
Nothing -> i N "no pager was found" |
| 299 |
Just pager -> |
| 300 |
case meconfpager of |
| 301 |
Just (Right No) -> i N "disabled in config file" |
| 302 |
_ -> do |
| 303 |
p Y pager |
| 304 |
|
| 305 |
when (map toLower (takeBaseName pager) == "more") $ do |
| 306 |
pdesc "the MORE variable is defined ?" |
| 307 |
mv <- lookupEnv "MORE" |
| 308 |
case mv of |
| 309 |
Nothing -> i N "" |
| 310 |
Just v -> i Y v |
| 311 |
|
| 312 |
when (map toLower (takeBaseName pager) == "less") $ do |
| 313 |
mHLEDGER_LESS <- lookupEnv "HLEDGER_LESS" |
| 314 |
mLESS <- lookupEnv "LESS" |
| 315 |
|
| 316 |
pdesc "the LESS variable is defined ?" |
| 317 |
case mLESS of |
| 318 |
Nothing -> i N "" |
| 319 |
Just v -> i Y $ v <> if isJust mHLEDGER_LESS then " (overridden)" else "" |
| 320 |
|
| 321 |
pdesc "the HLEDGER_LESS variable is defined ?" |
| 322 |
case mHLEDGER_LESS of |
| 323 |
Nothing -> i N "" |
| 324 |
Just v -> i Y v |
| 325 |
|
| 326 |
when (isNothing mHLEDGER_LESS) $ do |
| 327 |
pdesc "adjusting LESS var for consistent UX ?" |
| 328 |
usecolor <- useColorOnStdout |
| 329 |
i Y $ lessVarValue mHLEDGER_LESS mLESS usecolor |
| 330 |
|
| 331 |
pdesc "less is working with these options ?" |
| 332 |
usecolor <- useColorOnStdout |
| 333 |
let newlessvar = lessVarValue mHLEDGER_LESS mLESS usecolor |
| 334 |
env <- getEnvironment |
| 335 |
let customEnv = ("LESS", newlessvar) : filter ((/= "LESS") . fst) env |
| 336 |
lessHasError <- lessIsWorking (Just customEnv) |
| 337 |
if lessHasError |
| 338 |
then p N "less --version shows a problem, check LESS/HLEDGER_LESS settings" |
| 339 |
else p Y "" |
| 340 |
|
| 341 |
pdesc "box-drawing chars are used by default ?" |
| 342 |
if isJust $ conflookup ("--pretty"==) |
| 343 |
then p Y "" |
| 344 |
else i N "you can use --pretty to enable them" |
| 345 |
|
| 346 |
-- pdesc "bash shell completions are installed ?" >> p U "" |
| 347 |
-- pdesc "zsh shell completions are installed ?" >> p U "" |
| 348 |
|
| 349 |
------------------------------------------------------------------------------ |
| 350 |
|
| 351 |
setupJournal meconf = do |
| 352 |
pgroup "journal" |
| 353 |
let |
| 354 |
-- Find the last opt/arg matched by a predicate in the general config, if there is one. |
| 355 |
conflookup predicate = case meconf of |
| 356 |
Just (Right conf) -> find predicate $ reverse $ confLookup "general" conf |
| 357 |
_ -> Nothing |
| 358 |
|
| 359 |
-- pdesc "a home directory journal file exists ?" |
| 360 |
-- mh <- getHomeSafe |
| 361 |
-- (ok,msg) <- case mh of |
| 362 |
-- Just h -> do |
| 363 |
-- let f = h </> journalDefaultFilename |
| 364 |
-- e <- doesFileExist f |
| 365 |
-- return (if e then Y else N, if e then f else "") |
| 366 |
-- Nothing -> return (N, "") |
| 367 |
-- i ok msg |
| 368 |
|
| 369 |
pdesc "the LEDGER_FILE variable is defined ?" |
| 370 |
mf <- lookupEnv journalEnvVar |
| 371 |
let |
| 372 |
(ok, msg) = case mf of |
| 373 |
Just f -> (Y, f) |
| 374 |
Nothing -> (N, "") |
| 375 |
i ok msg |
| 376 |
|
| 377 |
-- case mf of |
| 378 |
-- Nothing -> return () |
| 379 |
-- Just f -> do |
| 380 |
-- pdesc "$LEDGER_FILE journal exists ?" |
| 381 |
-- e <- doesFileExist f |
| 382 |
-- i e "" "" |
| 383 |
|
| 384 |
-- when (isJust mh && isJust mf) $ do |
| 385 |
-- pdesc "$LEDGER_FILE is masking home journal ?" |
| 386 |
-- i Y "" |
| 387 |
|
| 388 |
pdesc "a default journal file is readable ?" |
| 389 |
ef <- defaultJournalPathSafely |
| 390 |
-- let |
| 391 |
-- args = concat [ |
| 392 |
-- ["print"], |
| 393 |
-- ["--ignore-assertions" | supportsIgnoreAssertions version], |
| 394 |
-- ["--no-conf" | supportsConfigFiles version] |
| 395 |
-- ] |
| 396 |
-- (exit, _, err) <- readProcessWithExitCode progname args "" |
| 397 |
-- XXX can this ignore assertions and config files, like the above ? |
| 398 |
ej <- defaultJournalSafely |
| 399 |
let trim s = either (const s) id $ regexReplace (toRegex' "^Error: ") "" s |
| 400 |
case (ef, ej) of |
| 401 |
(Left err, _) -> p N $ trim err |
| 402 |
(Right f, Left err) -> p N (f <> ":\n" <> trim err) |
| 403 |
(Right f, Right j@Journal{..}) -> do |
| 404 |
p Y f |
| 405 |
|
| 406 |
pdesc "it includes additional files ?" |
| 407 |
let numfiles = length jfiles |
| 408 |
if numfiles > 1 |
| 409 |
then i Y (show (numfiles - 1) <> " files") |
| 410 |
else i N "" |
| 411 |
|
| 412 |
pdesc "all commodities are declared ?" |
| 413 |
let |
| 414 |
numcommodities = length $ journalCommodities j |
| 415 |
undeclaredcommodities = journalCommoditiesUsed j \\ journalCommoditiesDeclared j |
| 416 |
if null undeclaredcommodities |
| 417 |
then p Y (show numcommodities <> " commodities") |
| 418 |
else p N (show (length undeclaredcommodities) <> " undeclared commodities") |
| 419 |
|
| 420 |
let |
| 421 |
accttypes = [Asset, Liability, Equity, Revenue, Expense, Cash, Conversion] |
| 422 |
typesdeclaredorinferred = nub $ M.elems jaccounttypes |
| 423 |
typesnotfound = filter (not.(`elem` typesdeclaredorinferred)) accttypes |
| 424 |
acctswithdeclaredorinferredtype = nub (M.keys jaccounttypes) |
| 425 |
numaccts = length $ journalAccountNames j |
| 426 |
untypedaccts = journalAccountNames j \\ acctswithdeclaredorinferredtype |
| 427 |
undeclaredaccts = journalAccountNamesUsed j \\ journalAccountNamesDeclared j |
| 428 |
-- hasdeclaredaccts t = case M.lookup t jdeclaredaccounttypes of |
| 429 |
-- Just (_ : _) -> True |
| 430 |
-- _ -> False |
| 431 |
|
| 432 |
-- pdesc "Asset accounts declared ?" |
| 433 |
-- if hasdeclaredaccts Asset then i Y "" else i N "" |
| 434 |
|
| 435 |
-- pdesc "Liability accounts declared ?" |
| 436 |
-- if hasdeclaredaccts Liability then i Y "" else i N "" |
| 437 |
|
| 438 |
-- pdesc "Equity accounts declared ?" |
| 439 |
-- if hasdeclaredaccts Equity then i Y "" else i N "" |
| 440 |
|
| 441 |
-- pdesc "Revenue accounts declared ?" |
| 442 |
-- if hasdeclaredaccts Revenue then i Y "" else i N "" |
| 443 |
|
| 444 |
-- pdesc "Expense accounts declared ?" |
| 445 |
-- if hasdeclaredaccts Expense then i Y "" else i N "" |
| 446 |
|
| 447 |
-- pdesc "Cash accounts declared ?" |
| 448 |
-- if hasdeclaredaccts Cash then i Y "" else i N "" |
| 449 |
|
| 450 |
-- pdesc "Conversion accounts declared ?" |
| 451 |
-- if hasdeclaredaccts Conversion then i Y "" else i N "" -- ("--infer-equity will use a default conversion account name") |
| 452 |
|
| 453 |
-- XXX hard to detect accounts where type was inferred from name |
| 454 |
-- unless arealltypesdeclared $ do |
| 455 |
-- let |
| 456 |
-- acctswithdeclaredtype = concat (M.elems jdeclaredaccounttypes) |
| 457 |
-- acctswithinferredtype = acctswithdeclaredorinferredtype \\ acctswithdeclaredtype |
| 458 |
-- arealltypesdeclared = all hasdeclaredaccts accttypes |
| 459 |
-- typesinferredfromnames = |
| 460 |
-- if arealltypesdeclared then [] |
| 461 |
-- else sort $ nub $ catMaybes $ map (flip M.lookup jaccounttypes) acctswithinferredtype |
| 462 |
-- pdesc "types detected from account names ?" |
| 463 |
-- if null typesinferredfromnames then i N "" else i Y (concatMap show typesinferredfromnames) |
| 464 |
|
| 465 |
pdesc "all accounts are declared ?" |
| 466 |
if null undeclaredaccts then p Y (show numaccts <> " accounts") else i N (show (length undeclaredaccts) <> " undeclared accounts") |
| 467 |
|
| 468 |
pdesc "all accounts have types ?" |
| 469 |
if null untypedaccts then p Y "" else i N (show (length untypedaccts) <> " accounts without types") |
| 470 |
|
| 471 |
pdesc "accounts of all types exist ?" |
| 472 |
if null typesnotfound |
| 473 |
then p Y (concatMap show accttypes <> " accounts detected") |
| 474 |
else p N (concatMap show typesnotfound <> " accounts not found; some reports may not work") |
| 475 |
|
| 476 |
pdesc "commodities/accounts are being checked ?" |
| 477 |
let strict = isJust $ conflookup (\a -> any (==a) ["-s", "--strict"]) |
| 478 |
if strict |
| 479 |
then i Y "commodities and accounts must be declared" |
| 480 |
else i N "you can use -s to check them" |
| 481 |
|
| 482 |
pdesc "balance assertions are being checked ?" |
| 483 |
let ignoreassertions = isJust $ conflookup (\a -> any (==a) ["-I", "--ignore-assertions"]) |
| 484 |
if |
| 485 |
| ignoreassertions && not strict -> i N "you can use -s to check them" |
| 486 |
| not strict -> i Y "you can use -I to ignore them" |
| 487 |
| otherwise -> i Y "can't ignore assertions (-s in config file)" |
| 488 |
|
| 489 |
------------------------------------------------------------------------------ |
| 490 |
|
| 491 |
-- Test a hledger version for support of various features. |
| 492 |
ver >=! str = ver >= (fromJust $ toVersion str) |
| 493 |
supportsIgnoreAssertions = (>=! "0.24") -- --ignore-assertions (2014) |
| 494 |
supportsCommodityDirective = (>=! "1.0") -- commodity directive (2016) |
| 495 |
supportsPretty = (>=! "1.2") -- --pretty, to use box-drawing characters (2017) |
| 496 |
supportsAccountDirective = (>=! "1.9") -- account directive (2018) |
| 497 |
supportsAccountTypes = (>=! "1.13") -- ALERX account types, type: tag (2019) |
| 498 |
supportsCashAccountType = (>=! "1.19") -- C/Cash account type (2020) |
| 499 |
supportsBasicColor = (>=! "1.19") -- basic color detection/control (2020) |
| 500 |
supportsConversionAccountType = (>=! "1.25") -- V/Conversion account type, accounts --types (2022) |
| 501 |
supportsConfigFiles = (>=! "1.40") -- config files (2024) |
| 502 |
supportsColor = (>=! "1.41") -- robust color detection/control (2024) |
| 503 |
supportsPager = (>=! "1.41") -- use a pager for all output (2024) |
| 504 |
supportsBashCompletions = (>=! "1.41") -- up to date bash shell completions (2024) |
| 505 |
|
| 506 |
-- yes, no, unknown |
| 507 |
data YNU = Y | N | U deriving (Eq) |
| 508 |
|
| 509 |
-- ANSI styles |
| 510 |
good = bold' . brightGreen' |
| 511 |
neutral = bold' . brightBlue' |
| 512 |
warning = bold' . brightYellow' |
| 513 |
bad = bold' . brightRed' |
| 514 |
|
| 515 |
-- Show status, in red/green/yellow if supported. |
| 516 |
instance Show YNU where |
| 517 |
show Y = good "yes" -- ✅ apple emojis - won't work everywhere |
| 518 |
show N = bad " no" -- ❌ |
| 519 |
show U = warning " ?" |
| 520 |
|
| 521 |
-- Show status, in blue/yellow if supported. |
| 522 |
showInfo Y = neutral "yes" -- ℹ️ |
| 523 |
showInfo N = neutral " no" -- ℹ️ |
| 524 |
showInfo U = warning " ?" |
| 525 |
|
| 526 |
-- | Print a test's pass or fail status, as "yes" or "no" or "", |
| 527 |
-- in green/red if supported, and the (possibly empty) provided message. |
| 528 |
p :: YNU -> String -> IO () |
| 529 |
p ok msg = putStrLn $ unwords ["", show ok, "", msg] |
| 530 |
|
| 531 |
-- | Like p, but display the status as info, in neutral blue. |
| 532 |
i :: YNU -> String -> IO () |
| 533 |
i ok msg = putStrLn $ unwords ["", showInfo ok, "", msg] |
| 534 |
|
| 535 |
-- | Print a setup test groups heading. |
| 536 |
pgroup :: String -> IO () |
| 537 |
pgroup s = putStrLn $ "\n" <> bold' s |
| 538 |
|
| 539 |
-- | Print a setup test's description, formatting and padding it to a fixed width. |
| 540 |
pdesc :: String -> IO () |
| 541 |
pdesc s = printf "* %-40s" s |
| 542 |
|
| 543 |
(getLatestHledgerVersion, latestHledgerVersionUrlStr) = |
| 544 |
-- (getLatestHledgerVersionFromHackage, "https://hackage.haskell.org/package/hledger/docs") |
| 545 |
(getLatestHledgerVersionFromHledgerOrg, "https://hledger.org/install.html") |
| 546 |
|
| 547 |
httptimeout = 10000000 -- 10s |
| 548 |
|
| 549 |
-- | Get the current hledger release version from the internet. |
| 550 |
-- Currently requests the latest doc page from Hackage and inspects the redirect path. |
| 551 |
-- Should catch all normal errors, and time out after 10 seconds. |
| 552 |
getLatestHledgerVersionFromHackage :: IO (Either String String) |
| 553 |
getLatestHledgerVersionFromHackage = do |
| 554 |
let url = https "hackage.haskell.org" /: "package" /: "hledger" /: "docs" /: "" |
| 555 |
result <- try $ runReq defaultHttpConfig{httpConfigRedirectCount=0} $ |
| 556 |
req HEAD url NoReqBody bsResponse (R.responseTimeout httptimeout) |
| 557 |
case result of |
| 558 |
Right _ -> return $ Left "expected a redirect" |
| 559 |
Left (VanillaHttpException (HttpExceptionRequest _ (StatusCodeException rsp _))) -> do |
| 560 |
let status = statusCode $ responseStatus rsp |
| 561 |
if status >= 300 && status < 400 |
| 562 |
then do |
| 563 |
let locationHeader = lookup hLocation (responseHeaders rsp) |
| 564 |
case fmap T.decodeUtf8 locationHeader of |
| 565 |
Nothing -> return $ Left "no Location header" |
| 566 |
Just location -> do |
| 567 |
let packagename = take 1 $ drop 1 $ reverse $ T.splitOn "/" location |
| 568 |
case packagename of |
| 569 |
[n] -> return $ Right $ dropWhile (`notElem` ['0'..'9']) $ T.unpack n |
| 570 |
_ -> return $ Left "couldn't parse Location" |
| 571 |
else return $ Left $ "HTTP status " ++ show status |
| 572 |
Left err -> return $ Left $ "other exception: " ++ show err |
| 573 |
|
| 574 |
-- | Like the above, but get the version from the first number on the hledger.org Install page. |
| 575 |
getLatestHledgerVersionFromHledgerOrg :: IO (Either String String) |
| 576 |
getLatestHledgerVersionFromHledgerOrg = do |
| 577 |
let url = https "hledger.org" /: "install.html" |
| 578 |
do |
| 579 |
result <- try $ runReq defaultHttpConfig $ req GET url NoReqBody bsResponse (R.responseTimeout httptimeout) |
| 580 |
case result of |
| 581 |
Left (_ :: R.HttpException) -> return $ Left "(HTTP failure)" |
| 582 |
Right rsp -> case T.decodeUtf8' $ R.responseBody rsp of |
| 583 |
Left e -> return $ Left $ show e |
| 584 |
Right t -> return $ |
| 585 |
if null version then Left "couldn't parse version" else Right version |
| 586 |
where |
| 587 |
-- keep synced |
| 588 |
versionline = take 1 $ dropWhile (not . ("current hledger release" `isInfixOf`)) $ lines $ T.unpack t |
| 589 |
version = takeWhile (`elem` ("0123456789."::[Char])) $ dropWhile (not . isDigit) $ headDef "" $ versionline |
| 590 |
-- work around potential failure on mac (& possible security issue, reported upstream) |
| 591 |
`catch` (\(_ :: IOError) -> return $ Left $ "(IO error" <> if os=="darwin" then " - mac PATH issue ?)" else ")") |
| 592 |
|
| 593 |
-- | Try to run the hledger in PATH with one or more sets of command line arguments. |
| 594 |
-- Returns the output from the first set of arguments that runs successfully, |
| 595 |
-- or the error output from the last set. |
| 596 |
tryHledgerArgs :: [[String]] -> IO (Either String String) |
| 597 |
tryHledgerArgs [] = pure $ Left "tryHledgerArgs: no arguments provided" |
| 598 |
tryHledgerArgs (args:rest) = do |
| 599 |
eresult <- runHledger args |
| 600 |
case eresult of |
| 601 |
Right out -> pure $ Right out |
| 602 |
Left err -> if null rest then pure $ Left err else tryHledgerArgs rest |
| 603 |
|
| 604 |
-- | Run the hledger in PATH with the given command line arguments, |
| 605 |
-- returning the output on success or the error output on failure. |
| 606 |
runHledger :: [String] -> IO (Either String String) |
| 607 |
runHledger args = do |
| 608 |
(exit, out, err) <- readProcessWithExitCode "hledger" args "" |
| 609 |
pure $ case exit of |
| 610 |
ExitSuccess -> Right out |
| 611 |
ExitFailure _ -> Left err |
| 612 |
|
| 613 |
-- | Get the operating system version string, if possible. |
| 614 |
-- Uses platform-specific commands to detect the OS version. |
| 615 |
getOSVersion :: IO (Maybe String) |
| 616 |
getOSVersion = case os of |
| 617 |
"darwin" -> tryCommand "sw_vers" ["-productVersion"] |
| 618 |
"mingw32" -> tryCommand "cmd" ["/c", "ver"] |
| 619 |
"linux" -> tryCommand "uname" ["-r"] |
| 620 |
_ -> return Nothing |
| 621 |
where |
| 622 |
tryCommand cmd args = |
| 623 |
(Just . strip <$> readProcess cmd args "") |
| 624 |
`catch` (\(_ :: SomeException) -> return Nothing) |