Debian Codegraph @

Hledger/Cli/Commands/Demo.hs

raw
1 {-|
2 The @demo@ command lists and plays small hledger demos in the terminal, using asciinema.
3 -}
4 {-
5 PROJECTS
6 improve cast output
7 install
8 command line editing glitches
9 shrink / compress ?
10 help
11 screen corrupted by pager
12 demo
13 update (or drop till stable)
14 add
15 print
16 balance
17 document cast production tips
18 always clear screen after running pager/curses apps ?
19 record with tall window to avoid showing pager in playback ?
20 improve functionality
21 show "done" in final red line ?
22 mirror common asciinema flags like -s, -i and/or set speed/max idle with optional arguments
23 support other asciinema operations (cat)
24 show hledger.org player urls
25 windows/PowerSession support
26 attract/continuous play mode
27 more casts
28 clarify goals/target user(s)/scenarios
29 identify and prioritise some casts needed
30 -}
31
32 {-# LANGUAGE OverloadedStrings #-}
33 {-# LANGUAGE ScopedTypeVariables #-}
34 {-# LANGUAGE TemplateHaskell #-}
35
36 module Hledger.Cli.Commands.Demo (
37 demomode
38 ,demo
39 ) where
40
41 import Text.Printf
42 import Control.Concurrent (threadDelay)
43 import System.Process (callProcess)
44 import System.IO.Error (catchIOError)
45 import Safe (readMay, atMay, headMay)
46 import Data.List (isPrefixOf, find, findIndex, isInfixOf, dropWhileEnd)
47 import Control.Applicative ((<|>))
48 import Data.ByteString as B (ByteString)
49 import Data.Maybe
50 import Data.ByteString.Char8 qualified as B
51 import Safe (tailMay)
52 import System.IO.Temp (withSystemTempFile)
53 import System.IO (hClose)
54 import System.Console.CmdArgs.Explicit (flagReq)
55
56 import Hledger
57 import Hledger.Cli.CliOptions
58 import System.Directory (findExecutable)
59 import Control.Monad (when)
60
61 demos :: [Demo]
62 demos = map readDemo [
63 -- XXX these are confusing, redo
64 -- (embedFileRelative "embeddedfiles/help.cast"), -- https://asciinema.org/a/568112 Getting help
65 -- (embedFileRelative "embeddedfiles/demo.cast"), -- https://asciinema.org/a/567944 Watching the built-in demos
66 $(embedFileRelative "embeddedfiles/add.cast"), -- https://asciinema.org/a/567935 The easiest way to start a journal (add)
67 $(embedFileRelative "embeddedfiles/print.cast"), -- https://asciinema.org/a/567936 Show full transactions (print)
68 $(embedFileRelative "embeddedfiles/balance.cast"), -- https://asciinema.org/a/567937 Show account balances and changes (balance)
69 $(embedFileRelative "embeddedfiles/install.cast") -- https://asciinema.org/a/567934 Installing hledger from source with hledger-install
70 ]
71
72 -- | An embedded asciinema cast, with some of the metadata separated out.
73 -- The original file name is not preserved.
74 data Demo = Demo {
75 dtitle :: String, -- asciinema title field
76 _dcontent :: ByteString -- asciinema v2 content
77 }
78
79 -- | Command line options for this command.
80 demomode = hledgerCommandMode
81 $(embedFileRelative "Hledger/Cli/Commands/Demo.txt")
82 [
83 flagReq ["speed","s"] (\s opts -> Right $ setopt "speed" s opts) "SPEED"
84 ("playback speed (1 is original speed, .5 is half, 2 is double, etc (default: 2))")
85 ]
86 [generalflagsgroup3]
87 []
88 ([], Just $ argsFlag optsstr)
89
90 optsstr = "[NUM|PREFIX|SUBSTR]"
91 -- optsstr = "[NUM|PREFIX|SUBSTR] [-- ASCIINEMAOPTS]"
92 usagestr = "Usage: hledger demo " <> optsstr
93
94 -- | The demo command.
95 demo :: CliOpts -> Journal -> IO ()
96 demo CliOpts{rawopts_=rawopts, reportspec_=ReportSpec{_rsQuery=_query}} _j = do
97 -- demos <- getCurrentDirectory >>= readDemos
98 case listofstringopt "args" rawopts of
99 [] -> putStrLn usagestr >> putStr listDemos
100 (a:as) ->
101 case findDemo demos a of
102 Nothing -> error' $ unlines
103 ["No demo \"" <> a <> "\" was found."
104 ,usagestr
105 ,listDemos
106 ]
107 Just (Demo t c) -> do
108 -- check if asciinema is installed, first
109 masciinema <- findExecutable "asciinema"
110 when (isNothing masciinema) $ error' "Could not find 'asciinema'; please install that first."
111 let
112 -- try to preserve the original pauses a bit while also moving things along
113 defidlelimit = 10
114 defspeed = 2
115 speed =
116 case maybestringopt "speed" rawopts of
117 Nothing -> defspeed
118 Just s -> fromMaybe err $ readMay s
119 where err = error' $ "could not parse --speed " <> s <> ", numeric argument expected"
120 idx = maybe 0 (1+) $ findIndex (\(Demo t2 _) -> t2 == t) demos -- should succeed
121 mw <- getTerminalWidth
122 let line = red' $ replicate w '.' where w = fromMaybe (length t) mw
123 printf "playing: %d) %s\nspace to pause, . to step, ctrl-c to quit\n" idx (bold' t)
124 putStrLn line
125 putStrLn ""
126 threadDelay 1000000
127 -- XXX this used to see asciinema options after --, currently it doesn't
128 runAsciinemaPlay speed defidlelimit c as
129 putStrLn ""
130 putStrLn line
131
132 readDemo :: ByteString -> Demo
133 readDemo content = Demo title content
134 where
135 title = maybe "" (readTitle . B.unpack) $ headMay $ B.lines content
136 where
137 readTitle s
138 | "\"title\":" `isPrefixOf` s = takeWhile (/='"') $ drop 1 $ lstrip $ drop 8 s
139 | otherwise = maybe "" readTitle $ tailMay s
140
141 findDemo :: [Demo] -> String -> Maybe Demo
142 findDemo ds s =
143 (readMay s >>= atMay ds . subtract 1) -- try to find by number
144 <|> find ((sl `isPrefixOf`).lowercase.dtitle) ds -- or by title prefix (ignoring case)
145 <|> find ((sl `isInfixOf`) .lowercase.dtitle) ds -- or by title substring (ignoring case)
146 where
147 sl = lowercase s
148
149 listDemos :: String
150 listDemos = unlines $
151 "Demos:" :
152 -- "" :
153 [show i <> ") " <> bold' t | (i, Demo t _) <- zip [(1::Int)..] demos]
154
155 -- | Run asciinema play with the given speed and idle limit, passing the given content to its stdin.
156 runAsciinemaPlay :: Float -> Float -> ByteString -> [String] -> IO ()
157 runAsciinemaPlay speed idlelimit content args = do
158 -- XXX try piping to stdin also
159 withSystemTempFile "hledger-cast" $ \f h -> do
160 -- don't add an extra newline here, it breaks asciinema 2.3.0 (#2094).
161 -- XXX we could try harder and strip excess newlines/carriage returns+linefeeds here
162 B.hPutStr h content >> hClose h
163 callProcess "asciinema" (dbg8With (("asciinema: "++).unwords) $ concat [
164 ["play"]
165 ,["-s"<> showwithouttrailingzero speed]
166 ,if idlelimit == 0 then [] else ["-i"<>showwithouttrailingzero idlelimit]
167 ,[f]
168 ,args
169 ])
170 `catchIOError` \err -> do
171 printError $ unlines
172 [""
173 ,show err
174 ,"Running asciinema failed. Trying 'asciinema --version':"
175 ]
176 callProcess "asciinema" ["--version"]
177 `catchIOError` \_ -> error' "This also failed."
178 where
179 showwithouttrailingzero = dropWhileEnd (=='.') . dropWhileEnd (=='0') . show
180