├── Setup.hs
├── example.png
├── test
├── Spec.hs
├── Test.hs
└── GlobalSpec.hs
├── .gitignore
├── stack.yaml
├── src
├── OrgStat
│ ├── Outputs.hs
│ ├── Outputs
│ │ ├── Class.hs
│ │ ├── Summary.hs
│ │ ├── Block.hs
│ │ ├── Script.hs
│ │ ├── Types.hs
│ │ └── Timeline.hs
│ ├── CLI.hs
│ ├── WorkMonad.hs
│ ├── Logic.hs
│ ├── IO.hs
│ ├── Logging.hs
│ ├── Util.hs
│ ├── Parser.hs
│ ├── Scope.hs
│ ├── Ast.hs
│ ├── Helpers.hs
│ └── Config.hs
├── cli
│ └── Main.hs
└── arch
│ └── Main.hs
├── shell.nix
├── .travis.yml
├── .stylish-haskell.yaml
├── .orgstat.yaml
├── CHANGES.md
├── orgstatExample.yaml
├── orgstat.cabal
├── README.md
└── LICENSE
/Setup.hs:
--------------------------------------------------------------------------------
1 | import Distribution.Simple
2 | main = defaultMain
3 |
--------------------------------------------------------------------------------
/example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/volhovm/orgstat/HEAD/example.png
--------------------------------------------------------------------------------
/test/Spec.hs:
--------------------------------------------------------------------------------
1 | {-# OPTIONS_GHC -F -pgmF hspec-discover -optF --module-name=Spec #-}
2 |
--------------------------------------------------------------------------------
/test/Test.hs:
--------------------------------------------------------------------------------
1 | import Spec (spec)
2 | import Test.Hspec (hspec)
3 | import Universum
4 |
5 | main :: IO ()
6 | main = hspec spec
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .stack-work
2 | stack.yaml.lock
3 | *#
4 | \#*
5 | *~
6 | .#*
7 | tmp/
8 | some.svg
9 | .hpc/
10 | *.tix
11 | dist/
12 | TAGS
13 |
--------------------------------------------------------------------------------
/stack.yaml:
--------------------------------------------------------------------------------
1 | resolver: lts-15.2
2 | #resolver: nightly-2020-12-14
3 |
4 | nix:
5 | shell-file: shell.nix
6 |
7 | extra-deps:
8 | - fmt-0.6
9 | - universum-1.5.0
10 | - orgmode-parse-0.2.3
11 | - thyme-0.3.5.5 # required by orgmode-parse
12 |
13 |
--------------------------------------------------------------------------------
/src/OrgStat/Outputs.hs:
--------------------------------------------------------------------------------
1 | -- | Re-exporting output functionality
2 |
3 | module OrgStat.Outputs
4 | ( module Exports
5 | ) where
6 |
7 | import OrgStat.Outputs.Block as Exports
8 | import OrgStat.Outputs.Class as Exports
9 | import OrgStat.Outputs.Script as Exports
10 | import OrgStat.Outputs.Summary as Exports
11 | import OrgStat.Outputs.Timeline as Exports
12 | import OrgStat.Outputs.Types as Exports
13 |
--------------------------------------------------------------------------------
/shell.nix:
--------------------------------------------------------------------------------
1 | with import (builtins.fetchGit {
2 | url = https://github.com/NixOS/nixpkgs;
3 | ref = "nixos-20.09";
4 | rev = "cd63096d6d887d689543a0b97743d28995bc9bc3";
5 | }) {};
6 | haskell.lib.buildStackProject {
7 | #ghc = haskell.packages.ghc8102.ghc;
8 | ghc = haskell.packages.ghc882.ghc;
9 | name = "orgstat";
10 | # firefox for xdg-open
11 | buildInputs = [ zlib git openssh gnupg gnupg1compat xdg_utils firefox gmp ];
12 | LANG = "en_US.UTF-8";
13 | }
14 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | language: c
3 | cache:
4 | directories:
5 | - "$HOME/.stack"
6 | - "$HOME/build/volhovm/orgstat/.stack-work"
7 | addons:
8 | apt:
9 | packages:
10 | - libgmp-dev
11 | before_install:
12 | - mkdir -p ~/.local/bin
13 | - export PATH=$HOME/.local/bin:$PATH
14 | - travis_retry curl -L https://www.stackage.org/stack/linux-x86_64 | tar xz --wildcards
15 | --strip-components=1 -C ~/.local/bin '*/stack'
16 | install:
17 | - stack --no-terminal --install-ghc build --only-dependencies --jobs=4
18 | script:
19 | - stack --no-terminal build --test --haddock --no-haddock-deps --bench --jobs=4
20 | notifications:
21 | email: true
22 |
23 |
--------------------------------------------------------------------------------
/src/OrgStat/Outputs/Class.hs:
--------------------------------------------------------------------------------
1 | -- | Common things among reports
2 |
3 | module OrgStat.Outputs.Class
4 | ( ReportOutput (..)
5 | ) where
6 |
7 | import Universum
8 |
9 | import qualified Data.Text.IO as T
10 | import qualified Diagrams.Backend.SVG as DB
11 | import qualified Diagrams.Prelude as D
12 | import System.FilePath (replaceExtension)
13 |
14 | import OrgStat.Outputs.Types (BlockOutput(..), SummaryOutput(..), TimelineOutput(..))
15 |
16 | -- | Things that reporters output an what we can do with them.
17 | class ReportOutput a where
18 | -- | Writes report to the disk, given path to file.
19 | writeReport :: (MonadIO m) => FilePath -> a -> m ()
20 |
21 | instance ReportOutput TimelineOutput where
22 | writeReport path (TimelineOutput diagram) =
23 | liftIO $ DB.renderSVG (replaceExtension path "svg") size diagram
24 | where
25 | size = D.dims2D (D.width diagram) (D.height diagram)
26 |
27 | instance ReportOutput SummaryOutput where
28 | writeReport path (SummaryOutput text) =
29 | liftIO $ T.writeFile (replaceExtension path "txt") text
30 |
31 | instance ReportOutput BlockOutput where
32 | writeReport path (BlockOutput text) =
33 | liftIO $ T.writeFile (replaceExtension path "txt") text
34 |
--------------------------------------------------------------------------------
/.stylish-haskell.yaml:
--------------------------------------------------------------------------------
1 | # Taken from serokell metatemplates
2 |
3 | steps:
4 | - simple_align:
5 | cases: false
6 | top_level_patterns: false
7 | records: false
8 | - imports:
9 | align: none
10 | list_align: after_alias
11 | pad_module_names: false
12 | long_list_align: new_line
13 | empty_list_align: inherit
14 | list_padding: 2
15 | separate_lists: false
16 | space_surround: false
17 | - language_pragmas:
18 | style: compact
19 | remove_redundant: true
20 | - trailing_whitespace: {}
21 | columns: 100
22 | newline: native
23 | language_extensions:
24 | - BangPatterns
25 | - ConstraintKinds
26 | - DataKinds
27 | - DefaultSignatures
28 | - DeriveDataTypeable
29 | - DeriveGeneric
30 | - DerivingStrategies
31 | - EmptyCase
32 | - ExistentialQuantification
33 | - ExplicitNamespaces
34 | - FlexibleContexts
35 | - FlexibleInstances
36 | - FunctionalDependencies
37 | - GADTs
38 | - GeneralizedNewtypeDeriving
39 | - LambdaCase
40 | - MultiParamTypeClasses
41 | - MultiWayIf
42 | - NamedFieldPuns
43 | - NoImplicitPrelude
44 | - OverloadedLabels
45 | - OverloadedStrings
46 | - PatternSynonyms
47 | - RecordWildCards
48 | - RecursiveDo
49 | - ScopedTypeVariables
50 | - StandaloneDeriving
51 | - TemplateHaskell
52 | - TupleSections
53 | - TypeApplications
54 | - TypeFamilies
55 | - ViewPatterns
56 |
--------------------------------------------------------------------------------
/src/OrgStat/CLI.hs:
--------------------------------------------------------------------------------
1 | -- | Common args and parser.
2 |
3 | module OrgStat.CLI
4 | ( CommonArgs (..)
5 | , parseCommonArgs
6 | ) where
7 |
8 | import Universum
9 |
10 | import Options.Applicative.Simple (Parser, help, long, metavar, strOption, switch)
11 |
12 | -- | Read-only arguments that inner application needs (in contrast to,
13 | -- say, logging severity).
14 | data CommonArgs = CommonArgs
15 | { caXdgOpen :: !Bool
16 | -- ^ Open report types using xdg-open
17 | , caOutputs :: ![Text]
18 | -- ^ Single output can be selected instead of running all of them.
19 | , caOutputDir :: !(Maybe FilePath)
20 | -- ^ Output directory for all ... outputs.
21 | } deriving Show
22 |
23 | parseCommonArgs :: Parser CommonArgs
24 | parseCommonArgs =
25 | CommonArgs <$>
26 | switch (long "xdg-open" <> help "Open each report using xdg-open") <*>
27 | many (
28 | fromString <$>
29 | strOption (long "output" <>
30 | long "select-output" <>
31 | help ("Output name(s) you want to process " <>
32 | "(default: all outputs are processed)"))) <*>
33 | optional (
34 | strOption (long "output-dir" <>
35 | metavar "FILEPATH" <>
36 | help ("Final output directory that overrides one in config. " <>
37 | "No extra subdirectories will be created")))
38 |
--------------------------------------------------------------------------------
/.orgstat.yaml:
--------------------------------------------------------------------------------
1 | scopes:
2 | - paths: ['/home/volhovm/org/work.org', '/home/volhovm/org/private.org']
3 | timelineDefault:
4 | colorSalt: 9
5 | colorStrategy:
6 | - tagMatches: [A]
7 | color: "#AAAAAA"
8 | - tagMatches: [B]
9 | color: hash
10 | legend: true
11 | legendColWidth: 0.6
12 | colWidth: 0.7
13 | colHeight: 1.1
14 | reports:
15 | - name: lastWeekWork
16 | range: week-1
17 | modifiers:
18 | - type: filterbytag
19 | tags: [M,H,sleep]
20 |
21 | - name: last7Days
22 | range:
23 | from: day-6
24 | to: now
25 |
26 | - name: thisWeekMytag
27 | range: week
28 | modifiers:
29 | - type: filterbytag
30 | tag: mytag
31 |
32 | - name: todayMytag
33 | range: day
34 | modifiers:
35 | - type: filterbytag
36 | tag: mytag
37 |
38 |
39 | outputs:
40 | - name: thisWeekTimeline
41 | report: thisWeekTimelineReport
42 | type: timeline
43 | - name: thisWeekTimelineAll
44 | report: last7Days
45 | type: timeline
46 | - name: thisWeekStats
47 | type: summary
48 | template: "mytag: %thisWeekMytag% "
49 | - name: thisWeekStatsScript
50 | type: script
51 | interpreter: "/bin/env sh"
52 | scriptPath: ~/dotfiles/scripts/orgstat_format_bar.sh
53 | reports: [thisWeekMytag, todayMytag]
54 |
55 | # For debug
56 | - name: debugBlock
57 | type: block
58 | report: todayMytag
59 |
60 | outputDir: /home/volhovm/code/orgstat/
61 | todoKeywords: [ TD, ST, WT, CL, DN ]
62 |
--------------------------------------------------------------------------------
/src/OrgStat/WorkMonad.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE TemplateHaskell #-}
2 |
3 | -- | Definition for main work scope
4 |
5 | module OrgStat.WorkMonad
6 | ( WorkConfig (..)
7 | , wcConfig
8 | , wcCommonArgs
9 | , WorkData
10 | , wdReadFiles
11 | , wdResolvedScopes
12 | , wdResolvedReports
13 | , WorkM (..)
14 | , runWorkM
15 | ) where
16 |
17 | import Universum
18 |
19 | import Control.Lens (makeLenses)
20 | import Data.Default (Default(def))
21 |
22 | import OrgStat.Ast (Org)
23 | import OrgStat.CLI (CommonArgs)
24 | import OrgStat.Config (OrgStatConfig)
25 |
26 | -- | Read-only app configuration.
27 | data WorkConfig = WorkConfig
28 | { _wcConfig :: OrgStatConfig
29 | , _wcCommonArgs :: CommonArgs
30 | }
31 |
32 | makeLenses ''WorkConfig
33 |
34 | -- | State component of application.
35 | data WorkData = WorkData
36 | { _wdReadFiles :: HashMap FilePath (Text, Org)
37 | -- ^ Org files that were read. Elements are pairs of type (file
38 | -- basename, content). Keys are paths.
39 | , _wdResolvedScopes :: HashMap Text Org
40 | -- ^ Scope is just plain read files.
41 | , _wdResolvedReports :: HashMap Text Org
42 | -- ^ Report is a filtered (with scope modifiers and clock
43 | -- limitations) scope.
44 | }
45 |
46 | makeLenses ''WorkData
47 |
48 | instance Default WorkData where
49 | def = WorkData mempty mempty mempty
50 |
51 | newtype WorkM a = WorkM
52 | { getWorkM :: StateT WorkData (ReaderT WorkConfig IO) a
53 | } deriving ( Functor
54 | , Applicative
55 | , Monad
56 | , MonadIO
57 | , MonadReader WorkConfig
58 | , MonadState WorkData
59 | , MonadThrow
60 | , MonadCatch
61 | )
62 |
63 | runWorkM :: MonadIO m => WorkConfig -> WorkM a -> m a
64 | runWorkM config action =
65 | liftIO $ runReaderT (evalStateT (getWorkM action) def) config
66 |
--------------------------------------------------------------------------------
/src/OrgStat/Outputs/Summary.hs:
--------------------------------------------------------------------------------
1 | -- | Summary output type.
2 |
3 | module OrgStat.Outputs.Summary
4 | ( genSummaryOutput
5 | ) where
6 |
7 | import Universum
8 |
9 | import Control.Lens (views)
10 | import qualified Data.Attoparsec.ByteString.Char8 as A
11 |
12 | import OrgStat.Ast (filterHasClock, orgTotalDuration)
13 | import OrgStat.Config (confReports, crName)
14 | import OrgStat.Helpers (resolveReport)
15 | import OrgStat.Outputs.Types (SummaryOutput(..), SummaryParams(..))
16 | import OrgStat.Util (timeF)
17 | import OrgStat.WorkMonad (WorkM, wcConfig)
18 |
19 |
20 | -- | Tokenizes summary template string.
21 | data InputToken
22 | = ReportTemplate Text -- ^ Valid template name surrounded by two '%'
23 | | OtherInfo Text -- ^ Anything in between
24 | deriving Show
25 |
26 | tokenize :: [Text] -> Text -> [InputToken]
27 | tokenize keywords (encodeUtf8 -> input) =
28 | case A.parseOnly toplvl input of
29 | Left err -> error $ fromString err
30 | Right res -> res
31 | where
32 | keyword = A.try $ do
33 | void $ A.char '%'
34 | between <- fromString <$> some (A.satisfy (/= '%'))
35 | void $ A.char '%'
36 | guard $ between `elem` keywords
37 | pure $ ReportTemplate between
38 | randomtext = do
39 | h <- A.anyChar
40 | t <- fromString <$> many (A.satisfy (/= '%'))
41 | pure $ OtherInfo $ fromString $ h:t
42 | toplvl = many (keyword <|> randomtext)
43 |
44 | -- | Generates summary using provided params.
45 | genSummaryOutput :: SummaryParams -> WorkM SummaryOutput
46 | genSummaryOutput SummaryParams{..} = do
47 | declaredReports <- views wcConfig $ map crName . confReports
48 | let tokens = tokenize declaredReports spTemplate
49 | res <- fmap mconcat $ forM tokens $ \case
50 | OtherInfo t -> pure t
51 | ReportTemplate reportName -> do
52 | report <- filterHasClock <$> resolveReport reportName
53 | pure $ timeF $ orgTotalDuration report
54 | pure $ SummaryOutput res
55 |
--------------------------------------------------------------------------------
/src/cli/Main.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE ApplicativeDo, ScopedTypeVariables #-}
2 |
3 | module Main where
4 |
5 | import Universum
6 |
7 | import Data.Version (showVersion)
8 | import Options.Applicative.Simple
9 | (Parser, help, long, metavar, simpleOptions, strOption, switch, value)
10 | import Paths_orgstat (version)
11 | import System.Directory (getHomeDirectory)
12 | import System.FilePath ((>))
13 |
14 | import OrgStat.CLI (CommonArgs, parseCommonArgs)
15 | import OrgStat.IO (readConfig)
16 | import OrgStat.Logging (Severity(..), initLogging, logDebug, logError)
17 | import OrgStat.Logic (runOrgStat)
18 | import OrgStat.WorkMonad (WorkConfig(..), runWorkM)
19 |
20 | data Args = Args
21 | { configPath :: !FilePath
22 | -- ^ Path to configuration file.
23 | , debug :: !Bool
24 | -- ^ Enable debug logging.
25 | , commonArgs :: CommonArgs
26 | -- ^ Other arguments.
27 | } deriving Show
28 |
29 | argsParser :: FilePath -> Parser Args
30 | argsParser homeDir = do
31 | configPath <-
32 | strOption
33 | (long "conf-path" <> metavar "FILEPATH" <> value (homeDir > ".orgstat.yaml") <>
34 | help "Path to the configuration file")
35 | debug <- switch (long "debug" <> help "Enable debug logging")
36 | commonArgs <- parseCommonArgs
37 | pure Args {..}
38 |
39 | getNodeOptions :: FilePath -> IO Args
40 | getNodeOptions homeDir = do
41 | (res, ()) <-
42 | simpleOptions
43 | ("orgstat-" <> showVersion version)
44 | "----- OrgStat ------"
45 | "Statistic reports visualizer for org-mode"
46 | (argsParser homeDir)
47 | empty
48 | pure res
49 |
50 | main :: IO ()
51 | main = do
52 | args@Args{..} <- getNodeOptions =<< getHomeDirectory
53 | let sev = if debug then Debug else Info
54 | initLogging sev
55 | config <- readConfig configPath
56 | runWorkM (WorkConfig config commonArgs) $ do
57 | logDebug $ "Just started with options: " <> show args
58 | runOrgStat `catch` topHandler
59 | where
60 | topHandler (e :: SomeException) = do
61 | logError $ "Top level error occured: " <> show e
62 |
--------------------------------------------------------------------------------
/CHANGES.md:
--------------------------------------------------------------------------------
1 | 0.1.10
2 | ==========
3 | * Compatibility with base-4.14
4 |
5 | 0.1.9
6 | ==========
7 | * Introduced passing the list of report durations into the script type output.
8 | * Added a simple archiving tool.
9 | * Fixed a small bug with `mergeClocks` which was causing multiple irrelevant tasks to inter-merge improperly.
10 | * Improved README.
11 |
12 | 0.1.8
13 | ==========
14 | * Switched to ghc 8.8
15 |
16 | 0.1.7
17 | ==========
18 | * Switch "script" output interpreter from "sh" to "/bin/env sh".
19 | * Update universum and orgmode-parse version (includes
20 | https://github.com/ixmatus/orgmode-parse/pull/53)
21 |
22 | 0.1.6
23 | ==========
24 | * Support "or" tags -- now it's possible to specify "t1 | t2 | t3" as a modifier by
25 | providing a list of tags in config.
26 | * Support of file-level tags: "#+FILETAGS: :tagA:tagB:tagC:" is correctly parsed
27 | and tags are propagated to all the file tree headers.
28 | * Added new output type -- script output.
29 | * Improved documentation, in particular in the orgstatExample.yaml.
30 | * Breaking: Configuration changes:
31 | * Simplified the configuration, now there's only one default timeline config,
32 | which cannot be overridden on a per-output basis.
33 | * Config parameter `colorSalt` was removed, use `timelineDefault.colorSalt` instead.
34 | * Timeline default color is now white.
35 | * timelineDefault renamed into timelineParams.
36 |
37 | 0.1.5
38 | =====
39 |
40 | * Support selecting multiple outputs in cli: --select-output can be used several times,
41 | also it's renamed into --output.
42 | * Remove log-warper dependency replacing with simple local logging.
43 | * Update deps: universum-1.4.0, fmt-0.6, orgmode-parse-0.2.2, also update lts to 12.5
44 |
45 | 0.1.4
46 | =====
47 |
48 | * Updated orgmode-parse which fixes parsing issue: https://github.com/ixmatus/orgmode-parse/issues/35
49 |
50 | 0.1.3
51 | =====
52 |
53 | * Updated universum to 1.7.1, universum to 0.8.0. Switched to nightly/ghc-8.2.1.
54 |
55 |
56 | 0.1.2
57 | =====
58 |
59 | * Add pretty block output.
60 |
61 | 0.1.1
62 | =====
63 |
64 | * Introduce concise report feature.
65 | * Change report hierarchy: separate reports from outputs.
66 | * Fix minor bugs.
67 |
68 | 0.0.4
69 | =====
70 |
71 | * Update universum to 0.5.1.1
72 | * Update log-warper to 1.1.4
73 |
74 | 0.0.3
75 | =====
76 |
77 | * Update universum/log-warper dependencies.
78 |
79 | 0.0.2
80 | =====
81 |
82 | * Add support for log-waprer 0.4.*
83 |
84 | 0.0.1
85 | =====
86 |
87 | * Initial release having timeline report type only.
88 |
--------------------------------------------------------------------------------
/src/OrgStat/Outputs/Block.hs:
--------------------------------------------------------------------------------
1 | -- | Block output similar to default org reporting. This is stub
2 | -- version which is to be improved later.
3 |
4 | module OrgStat.Outputs.Block
5 | ( genBlockOutput
6 | ) where
7 |
8 | import Universum
9 |
10 | import qualified Data.List as L
11 | import qualified Data.Text as T
12 | import Text.PrettyPrint.Boxes (center1, hsep, left, render, right, text, vcat)
13 |
14 | import OrgStat.Ast (Org, filterHasClock, orgSubtrees, orgTitle, orgTotalDuration)
15 | import OrgStat.Outputs.Types (BlockOutput(..), BlockParams(..))
16 | import OrgStat.Util (dropEnd, timeF)
17 |
18 | data BlockFrames = BlockFrames
19 | { bfAngle1 :: Text
20 | , bfAngle2 :: Text
21 | , bfHorizontal :: Text
22 | , bfVertical :: Text
23 | } deriving Show
24 |
25 | unicodeBlockFrames,asciiBlockFrames :: BlockFrames
26 | unicodeBlockFrames = BlockFrames "├" "└" "─" "│"
27 | asciiBlockFrames = BlockFrames "|" "\\" "-" "|"
28 |
29 | -- | Generate block output (emacs table-like).
30 | genBlockOutput :: BlockParams -> Org -> BlockOutput
31 | genBlockOutput BlockParams{..} (filterHasClock -> o0) = do
32 | BlockOutput $ fromString $ render $
33 | hsep 2 center1 [vsep,col1,vsep,col2,vsep]
34 | where
35 | BlockFrames{..} = if _bpUnicode then unicodeBlockFrames else asciiBlockFrames
36 | text' = text . toString
37 | elems' = withDepth (0::Int) o0
38 | col1 = vcat left $ map (text' . trimTitle . fst) elems'
39 | col2 = vcat right $ map (text' . snd) elems'
40 | vsep = vcat center1 $ replicate (length elems') (text $ toString bfVertical)
41 |
42 | trimTitle t | T.length t > _bpMaxLength = T.take (_bpMaxLength - 3) t <> "..."
43 | | otherwise = t
44 | formatter o =
45 | let dur = orgTotalDuration o
46 | titleRaw = T.take _bpMaxLength $ o ^. orgTitle
47 | in (titleRaw, timeF dur)
48 |
49 | withDepth :: Int -> Org -> [(Text,Text)]
50 | withDepth i o = do
51 | let (name,dur) = formatter o
52 | let children = map (withDepth (i+1)) (o ^. orgSubtrees)
53 | let processChild,processLastChild :: [(Text,Text)] -> [(Text,Text)]
54 | processChild [] = []
55 | processChild (pair0:pairs) =
56 | first ((bfAngle1 <> bfHorizontal <> " ") <>) pair0 :
57 | map (first ((bfVertical <> " ") <>)) pairs
58 | processLastChild [] = []
59 | processLastChild (pair0:pairs) =
60 | first ((bfAngle2 <> bfHorizontal <> " ") <>) pair0 :
61 | map (first (" " <>)) pairs
62 | let childrenProcessed
63 | | null children = []
64 | | otherwise =
65 | concat $
66 | map processChild (dropEnd 1 children) ++
67 | [processLastChild (L.last children)]
68 | (name,dur) : childrenProcessed
69 |
--------------------------------------------------------------------------------
/src/OrgStat/Outputs/Script.hs:
--------------------------------------------------------------------------------
1 | -- | Script output type. We launch the executable asked after
2 | -- injecting the environment variables related to the report.
3 |
4 | module OrgStat.Outputs.Script
5 | ( processScriptOutput
6 | ) where
7 |
8 | import Universum
9 |
10 | import Control.Lens (views)
11 | import qualified Data.Map.Strict as M
12 | import System.Environment (lookupEnv, setEnv, unsetEnv)
13 | import System.Process (callCommand)
14 |
15 | import OrgStat.Ast
16 | import OrgStat.Config (confReports, crName)
17 | import OrgStat.Helpers (resolveReport)
18 | import OrgStat.Outputs.Types (ScriptParams(..))
19 | import OrgStat.Util (timeF)
20 | import OrgStat.WorkMonad (WorkM, wcConfig)
21 |
22 | -- | Processes script output.
23 | processScriptOutput :: ScriptParams -> WorkM ()
24 | processScriptOutput ScriptParams{..} = do
25 | -- Considering all the reports if none are specified.
26 | reportsToConsider <- case spReports of
27 | [] -> views wcConfig (map crName . confReports)
28 | xs -> pure xs
29 | allReports <- mapM (\r -> (r,) <$> resolveReport r) reportsToConsider
30 |
31 | -- Set env variables
32 | prevVars <- forM allReports $ \(toString -> reportName,org) -> do
33 | let duration = timeF $ orgTotalDuration $ filterHasClock org
34 | let mean = timeF $ orgMeanDuration $ filterHasClock org
35 | let median = timeF $ orgMedianDuration $ filterHasClock org
36 | let pomodoro = orgPomodoroNum $ filterHasClock org
37 | let toMinutes x = round x `div` 60
38 | -- logWarning $ "1: " <> show org
39 | -- logWarning $ "2: " <> show (filterHasClock org)
40 | -- logWarning $ "3: " <> show (orgDurations $ filterHasClock org)
41 | let durationsPyth :: [Int] = map toMinutes $ orgDurations $ filterHasClock org
42 | (prevVar :: Maybe String) <- liftIO $ lookupEnv reportName
43 | liftIO $ setEnv reportName (toString duration)
44 | liftIO $ setEnv (reportName <> "Mean") (toString mean)
45 | liftIO $ setEnv (reportName <> "Median") (toString median)
46 | liftIO $ setEnv (reportName <> "Pomodoro") (show pomodoro)
47 | liftIO $ setEnv (reportName <> "DurationsList") (show durationsPyth)
48 | pure $ (reportName,) <$> prevVar
49 | let prevVarsMap :: Map String String
50 | prevVarsMap = M.fromList $ catMaybes prevVars
51 |
52 | -- Execute script
53 | let cmdArgument = either id (\t -> "-c \"" <> toString t <> "\"") spScript
54 | liftIO $ callCommand $
55 | spInterpreter <> " " <> cmdArgument
56 | --"/bin/env sh " <> cmdArgument
57 |
58 | -- Restore the old variables, clean new.
59 | forM_ (map fst allReports) $ \(toString -> reportName) -> do
60 | liftIO $ case M.lookup reportName prevVarsMap of
61 | Nothing -> unsetEnv reportName
62 | Just prevValue -> setEnv reportName prevValue
63 | where
64 |
--------------------------------------------------------------------------------
/src/OrgStat/Logic.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE ScopedTypeVariables #-}
2 |
3 | -- | Main logic combining all components
4 |
5 | module OrgStat.Logic
6 | ( runOrgStat
7 | ) where
8 |
9 | import Universum
10 |
11 | import Control.Lens (views)
12 | import qualified Data.Text as T
13 | import Data.Time (defaultTimeLocale, formatTime, getZonedTime)
14 | import System.Directory (createDirectoryIfMissing)
15 | import System.FilePath ((>))
16 | import Turtle (shell)
17 |
18 | import OrgStat.CLI (CommonArgs(..))
19 | import OrgStat.Config (ConfOutput(..), ConfOutputType(..), OrgStatConfig(..))
20 | import OrgStat.Helpers (resolveOutput, resolveReport)
21 | import OrgStat.Logging (logDebug, logInfo)
22 | import OrgStat.Outputs
23 | (genBlockOutput, genSummaryOutput, processScriptOutput, processTimeline, writeReport)
24 | import OrgStat.WorkMonad (WorkM, wcCommonArgs, wcConfig)
25 |
26 | -- | Main application logic.
27 | runOrgStat :: WorkM ()
28 | runOrgStat = do
29 | conf@OrgStatConfig{..} <- view wcConfig
30 | logDebug $ "Config: \n" <> show conf
31 |
32 | curTime <- liftIO getZonedTime
33 | let getOutputDir = do
34 | let createDir = do
35 | let reportDir =
36 | confOutputDir >
37 | formatTime defaultTimeLocale "%F-%H-%M-%S" curTime
38 | liftIO $ createDirectoryIfMissing True reportDir
39 | pure reportDir
40 | maybe createDir pure =<< views wcCommonArgs caOutputDir
41 | let writeOutput coName res = do
42 | reportDir <- getOutputDir
43 | let prePath = reportDir > T.unpack coName
44 | logInfo $ "This output will be written into: " <> fromString reportDir
45 | writeReport prePath res
46 |
47 | cliOuts <- views wcCommonArgs caOutputs
48 | outputsToProcess <-
49 | bool (mapM resolveOutput cliOuts) (pure confOutputs) (null cliOuts)
50 |
51 | forM_ outputsToProcess $ \ConfOutput{..} -> do
52 | logInfo $ "Processing output " <> coName
53 | case coType of
54 | TimelineOutput {..} -> do
55 | resolved <- resolveReport toReport
56 | let timeline = processTimeline confTimelineParams resolved
57 | logDebug $ "Generating timeline report " <> coName <> "..."
58 | writeOutput coName timeline
59 | SummaryOutput params -> do
60 | summary <- genSummaryOutput params
61 | writeOutput coName summary
62 | ScriptOutput params ->
63 | processScriptOutput params
64 | BlockOutput {..} -> do
65 | resolved <- resolveReport boReport
66 | let res = genBlockOutput boParams resolved
67 | writeOutput coName res
68 |
69 | whenM (views wcCommonArgs caXdgOpen) $ do
70 | reportDir <- getOutputDir
71 | logInfo "Opening reports using xdg-open..."
72 | void $ shell ("for i in $(ls "<>T.pack reportDir<>"/*); do xdg-open $i; done") empty
73 | logInfo "Done"
74 |
--------------------------------------------------------------------------------
/src/OrgStat/IO.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE ScopedTypeVariables #-}
2 |
3 | -- | Operations with files mostly.
4 |
5 | module OrgStat.IO
6 | ( readOrgFile
7 | , readConfig
8 | ) where
9 |
10 | import qualified Prelude
11 | import Universum
12 |
13 | import qualified Data.ByteString as BS
14 | import qualified Data.Text as T
15 | import qualified Data.Text.IO as TIO
16 | import Data.Yaml (decodeEither')
17 | import System.Directory (doesFileExist)
18 | import System.FilePath (takeBaseName, takeExtension)
19 | import Turtle (ExitCode(..), procStrict)
20 |
21 | import OrgStat.Ast (Org)
22 | import OrgStat.Config (ConfigException(ConfigParseException), OrgStatConfig)
23 | import OrgStat.Logging
24 | import OrgStat.Parser (runParser)
25 | import OrgStat.Util (dropEnd)
26 |
27 | data OrgIOException
28 | = OrgIOException Text
29 | -- ^ All exceptions related to reading files
30 | | ExternalException Text
31 | -- ^ Failed to run some external app (gpg)
32 | deriving (Typeable)
33 |
34 | instance Show OrgIOException where
35 | show (OrgIOException r) = "IOException: " <> T.unpack r
36 | show (ExternalException r) = "ExternalException: " <> T.unpack r
37 |
38 | instance Exception OrgIOException
39 |
40 | -- | Attempts to read a file. If extension is ".gpg", asks a user to
41 | -- decrypt it first. Returns a pair @(filename, content)@. It also
42 | -- takes a list of TODO-keywords to take header names correctly.
43 | readOrgFile
44 | :: (MonadIO m, MonadCatch m)
45 | => [Text] -> FilePath -> m (Text, Org)
46 | readOrgFile todoKeywords fp = do
47 | logDebug $ "Reading org file " <> fpt
48 | unlessM (liftIO $ doesFileExist fp) $
49 | throwM $ OrgIOException $ "Org file " <> fpt <> " doesn't exist"
50 | (content, fname) <- case takeExtension fp of
51 | ".gpg" -> (,dropEnd 4 fp) <$> decryptGpg
52 | ".org" -> (,fp) <$> liftIO (TIO.readFile fp)
53 | _ -> throwM $ OrgIOException $
54 | "File " <> fpt <> " has unknown extension. Need to be .org or .org.gpg"
55 | let filename = T.pack $ takeBaseName fname
56 | logDebug $ "Parsing org file " <> fpt
57 | parsed <- runParser todoKeywords content
58 | pure (filename, parsed)
59 | where
60 | fpt = T.pack fp
61 | failExternal = throwM . ExternalException
62 | decryptGpg = do
63 | logDebug $ "Decrypting gpg file: " <> fpt
64 | (exCode, output) <-
65 | (procStrict "gpg" ["--quiet", "--decrypt", fpt] empty)
66 | `catch`
67 | (\(e :: SomeException) -> failExternal $ "gpg procStrict failed: " <> show e)
68 | case exCode of
69 | ExitSuccess -> pass
70 | ExitFailure n -> failExternal $ "Gpg failed with code " <> show n
71 | pure output
72 |
73 | -- | Reads yaml config
74 | readConfig :: (MonadIO m, MonadThrow m) => FilePath -> m OrgStatConfig
75 | readConfig fp = do
76 | unlessM (liftIO $ doesFileExist fp) $
77 | throwM $ OrgIOException $ "Config file " <> fpt <> " doesn't exist"
78 | res <- liftIO $ BS.readFile fp
79 | either (throwM . ConfigParseException . show) pure $ decodeEither' res
80 | where
81 | fpt = T.pack fp
82 |
--------------------------------------------------------------------------------
/src/OrgStat/Outputs/Types.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE RankNTypes, TemplateHaskell #-}
2 | -- | Types common among reports.
3 |
4 | module OrgStat.Outputs.Types
5 | ( TimelineParams (..)
6 | , tpColorSalt
7 | , tpLegend
8 | , tpTopDay
9 | , tpColumnWidth
10 | , tpColumnHeight
11 | , tpBackground
12 | , TimelineOutput (..)
13 |
14 | , SummaryParams (..)
15 | , SummaryOutput (..)
16 |
17 | , ScriptParams (..)
18 |
19 | , BlockParams (..)
20 | , bpMaxLength
21 | , bpUnicode
22 | , BlockOutput (..)
23 | ) where
24 |
25 | import Universum
26 |
27 | import Control.Lens (makeLenses)
28 |
29 | import Data.Default (Default(..))
30 | import Diagrams.Backend.SVG (B)
31 | import qualified Diagrams.Prelude as D
32 |
33 | ----------------------------------------------------------------------------
34 | -- Timeline
35 | ----------------------------------------------------------------------------
36 |
37 | data TimelineParams = TimelineParams
38 | { _tpColorSalt :: !Int
39 | -- ^ Salt added when getting color out of task name.
40 | , _tpLegend :: !Bool
41 | -- ^ Include map legend?
42 | , _tpTopDay :: !Int
43 | -- ^ How many items to include in top day (under column)
44 | , _tpColumnWidth :: !Double
45 | -- ^ Column width in percent
46 | , _tpColumnHeight :: !Double
47 | -- ^ Column height
48 | , _tpBackground :: !(D.Colour Double)
49 | -- ^ Color of background
50 | } deriving (Show)
51 |
52 | makeLenses ''TimelineParams
53 |
54 |
55 | -- | SVG timeline image.
56 | newtype TimelineOutput = TimelineOutput (D.Diagram B)
57 |
58 | ----------------------------------------------------------------------------
59 | -- Summary
60 | ----------------------------------------------------------------------------
61 |
62 | -- | Parameters of the summary output
63 | data SummaryParams = SummaryParams
64 | { spTemplate :: !Text
65 | -- ^ Formatting template.
66 | } deriving Show
67 |
68 | -- | Some text (supposed to be single line or something).
69 | newtype SummaryOutput = SummaryOutput Text
70 |
71 | ----------------------------------------------------------------------------
72 | -- Script
73 | ----------------------------------------------------------------------------
74 |
75 | -- | Parameters of the summary output
76 | data ScriptParams = ScriptParams
77 | { spScript :: !(Either FilePath Text)
78 | -- ^ Either path to the script to execute, or a script text itself.
79 | , spReports :: ![Text]
80 | -- ^ Reports to consider.
81 | , spInterpreter :: !String
82 | -- ^ Interpreter to use.
83 | } deriving Show
84 |
85 | ----------------------------------------------------------------------------
86 | -- Block
87 | ----------------------------------------------------------------------------
88 |
89 | -- | Parameters for block output. Stub (for now).
90 | data BlockParams = BlockParams
91 | { _bpMaxLength :: !Int
92 | -- ^ Maximum title length (together with indentation).
93 | , _bpUnicode :: !Bool
94 | -- ^ Should unicode symbols be used for box borders.
95 | } deriving (Show)
96 |
97 | makeLenses ''BlockParams
98 |
99 | instance Default BlockParams where
100 | def = BlockParams 80 True
101 |
102 | -- | Output of block type is text file, basically.
103 | newtype BlockOutput = BlockOutput Text
104 |
--------------------------------------------------------------------------------
/src/OrgStat/Logging.hs:
--------------------------------------------------------------------------------
1 | -- | Basic logging, copied from log-warper (it has too many
2 | -- dependencies).
3 | module OrgStat.Logging
4 | (
5 | Severity (..)
6 | , initLogging
7 |
8 | , logDebug
9 | , logInfo
10 | , logNotice
11 | , logWarning
12 | , logError
13 |
14 | , logMessage
15 | ) where
16 |
17 | import Universum
18 |
19 | import Control.Concurrent.MVar (modifyMVar_, withMVar)
20 | import qualified Data.Text as T
21 | import Data.Time.Clock (UTCTime(..), getCurrentTime)
22 | import Fmt (fmt, padRightF, (+|), (|+), (|++|))
23 | import Fmt.Time (dateDashF, hmsF, subsecondF, tzNameF)
24 | import System.Console.ANSI
25 | (Color(Blue, Green, Magenta, Red, Yellow), ColorIntensity(Vivid), ConsoleLayer(Foreground),
26 | SGR(Reset, SetColor), setSGRCode)
27 | import System.IO.Unsafe (unsafePerformIO)
28 |
29 |
30 | -- | Severity is level of log message importance. It uniquely
31 | -- determines which messages to print.
32 | data Severity
33 | = Debug -- ^ Debug messages
34 | | Info -- ^ Information
35 | | Notice -- ^ Important (more than average) information
36 | | Warning -- ^ General warnings
37 | | Error -- ^ General errors/severe errors
38 | deriving (Eq, Ord, Show)
39 |
40 | -- | Internal information about logging.
41 | data LogInternalState = LogInternalState
42 | { lisMinSeverity :: Severity
43 | } deriving Show
44 |
45 | -- | Internal logging state.
46 | {-# NOINLINE loggingState #-}
47 | loggingState :: MVar LogInternalState
48 | loggingState = unsafePerformIO $ newMVar $ LogInternalState Debug
49 |
50 | -- | Initialise logging state.
51 | initLogging :: Severity -> IO ()
52 | initLogging sev = modifyMVar_ loggingState $ const $ pure $ LogInternalState sev
53 |
54 | -- | Colorizes "Text".
55 | colorizer :: Severity -> Text -> Text
56 | colorizer pr s =
57 | let (before, after) = table pr
58 | in toText before <> s <> toText after
59 | where
60 | -- | Defines pre- and post-printed characters for printing colorized text.
61 | table :: Severity -> (String, String)
62 | table severity = case severity of
63 | Error -> (setColor Red , reset)
64 | Debug -> (setColor Green , reset)
65 | Notice -> (setColor Magenta , reset)
66 | Warning -> (setColor Yellow , reset)
67 | Info -> (setColor Blue , reset)
68 | where
69 | setColor color = setSGRCode [SetColor Foreground Vivid color]
70 | reset = setSGRCode [Reset]
71 |
72 | -- | Formats UTC time in next format: "%Y-%m-%d %H:%M:%S%Q %Z"
73 | -- but %Q part show only in centiseconds (always 2 digits).
74 | centiUtcTimeF :: UTCTime -> Text
75 | centiUtcTimeF t =
76 | dateDashF t |+ " " +| hmsF t |++| centiSecondF t |+ " " +| tzNameF t |+ ""
77 | where
78 | centiSecondF = padRightF 3 '0' . T.take 3 . fmt . subsecondF
79 |
80 | -- | Logs message with specified severity using logger name in context.
81 | logMessage
82 | :: (MonadIO m)
83 | => Severity
84 | -> Text
85 | -> m ()
86 | logMessage severity msg =
87 | liftIO $ withMVar loggingState $ \LogInternalState{..} -> do
88 | time <- liftIO $ getCurrentTime
89 | let text = format time
90 | when (severity >= lisMinSeverity) $ putStrLn text
91 | where
92 | format time = mconcat
93 | [ colorizer severity $ "[" <> show severity <> "]"
94 | , " ["
95 | , centiUtcTimeF time
96 | , "] "
97 | , msg
98 | ]
99 |
100 | -- | Shortcuts for 'logMessage' to use according severity.
101 | logDebug, logInfo, logNotice, logWarning, logError
102 | :: MonadIO m
103 | => Text -> m ()
104 | logDebug = logMessage Debug
105 | logInfo = logMessage Info
106 | logNotice = logMessage Notice
107 | logWarning = logMessage Warning
108 | logError = logMessage Error
109 |
--------------------------------------------------------------------------------
/src/OrgStat/Util.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE RankNTypes #-}
2 | -- | Different utilities
3 |
4 | module OrgStat.Util
5 | ( dropLowerOptions
6 | , dropEnd
7 | , addLocalTime
8 | , fromJustM
9 | , parseColour
10 | , hashColour
11 | , (??~)
12 | , timeF
13 | ) where
14 |
15 | import Control.Lens (ASetter, ix)
16 | import Data.Aeson.TH (defaultOptions)
17 | import Data.Aeson.Types (Options, fieldLabelModifier)
18 | import Data.Char (isLower, toLower)
19 | import Data.Colour (Colour)
20 | import Data.Colour.CIE (luminance)
21 | import Data.Colour.SRGB (RGB(..), sRGB24, toSRGBBounded)
22 | import Data.List (nub)
23 | import Data.List ((!!))
24 | import Data.Time (LocalTime(..), NominalDiffTime, addUTCTime, localTimeToUTC, utc, utcToLocalTime)
25 | import Universum
26 |
27 | -- | JSON/Yaml TH modifier. Each field of type "aoeuKek" turns into
28 | -- "kek". Placed here because it can't be defined near json TH
29 | -- deriving (ghc restriction).
30 | dropLowerOptions :: Options
31 | dropLowerOptions =
32 | defaultOptions
33 | { fieldLabelModifier = \x -> (dropWhile isLower x) & ix 0 %~ toLower
34 | }
35 |
36 | fromJustM :: Monad m => m b -> m (Maybe b) -> m b
37 | fromJustM e m = maybe e pure =<< m
38 |
39 | -- | Drops n items from the end.
40 | dropEnd :: Int -> [x] -> [x]
41 | dropEnd n xs = take (length xs - n) xs
42 |
43 | -- | Same as 'addUTCTime', but for local
44 | addLocalTime :: (Integral n) => n -> LocalTime -> LocalTime
45 | addLocalTime n a =
46 | utcToLocalTime utc $ fromIntegral n `addUTCTime` localTimeToUTC utc a
47 |
48 | -- | Parses colour from format '#rrggbb' or just 'rrggbb'
49 | parseColour :: forall s a. (ToString s, Floating a, Ord a) => s -> Maybe (Colour a)
50 | parseColour (toString -> s) = toColour $ dropWhile (== '#') s
51 | where
52 | toColour [r1,r2,g1,g2,b1,b2] = do
53 | r <- toWord8 r1 r2
54 | g <- toWord8 g1 g2
55 | b <- toWord8 b1 b2
56 | pure $ sRGB24 r g b
57 | toColour _ = Nothing
58 | toWord8 a b = readMaybe $ "0x"++[a,b]
59 |
60 | -- | Generates a colour given salt and anything hashable. Doesn't return
61 | -- too dark or too light colors.
62 | hashColour :: (Hashable a) => Int -> a -> Colour Double
63 | hashColour salt item = colours !! (hashWithSalt salt item `mod` length colours)
64 | where
65 | broken = error "Util#hashColour is broken"
66 | range = [-5,0,5]
67 | colours = filter (\c -> luminance c < 0.8 && luminance c > 0.06) mutate
68 | ac :: Word8 -> Integer -> Word8
69 | ac a b = fromIntegral $ (fromIntegral a) + b `mod` 255
70 | mutate = nub $ concatMap
71 | (\(r,g,b) -> [sRGB24 (r `ac` i) (g `ac` j) (b `ac` k)
72 | | i <- range, j <- range, k <- range])
73 | coloursBasic
74 | coloursBasic =
75 | map (toTriple . fromMaybe broken . parseColour @[Char] @Double) popularColours
76 | toTriple c = let RGB{..} = toSRGBBounded c in (channelRed, channelGreen, channelBlue)
77 | popularColours :: [[Char]]
78 | popularColours = ["00FF00","01FFFE","FFA6FE","FFDB66","006401","010067","95003A","007DB5","FF00F6","FFEEE8","774D00","90FB92","0076FF","D5FF00","FF937E","6A826C","FF029D","FE8900","7A4782","7E2DD2","85A900","FF0056","A42400","00AE7E","683D3B","BDC6FF","263400","BDD393","00B917","9E008E","001544","C28C9F","FF74A3","01D0FF","004754","E56FFE","788231","0E4CA1","91D0CB","BE9970","968AE8","BB8800","43002C","DEFF74","00FFC6","FFE502","620E00","008F9C","98FF52","7544B1","B500FF","00FF78","FF6E41","005F39","6B6882","5FAD4E","A75740","A5FFD2","FFB167","009BFF","E85EBE"];
79 |
80 | -- | Maybe setter that does nothing on Nothing.
81 | (??~) :: ASetter s s a b -> Maybe b -> s -> s
82 | (??~) _ Nothing = id
83 | (??~) l (Just k) = l .~ k
84 |
85 | -- | Time formatter in form HH:MM
86 | timeF :: NominalDiffTime -> Text
87 | timeF n = do
88 | let totalTimeMin :: Integer
89 | totalTimeMin = round $ (/ 60) $ toRational n
90 | let hours = totalTimeMin `div` 60
91 | let minutes = totalTimeMin `mod` 60
92 | let showTwo x = (if x < 10 then "0" else "") <> show x
93 | fromString $ show hours <> ":" <> showTwo minutes
94 |
--------------------------------------------------------------------------------
/src/OrgStat/Parser.hs:
--------------------------------------------------------------------------------
1 | -- | Org-mode format parsing.
2 |
3 | module OrgStat.Parser
4 | ( ParsingException (..)
5 | , parseOrg
6 | , runParser
7 | ) where
8 |
9 | import Universum
10 |
11 | import qualified Data.Attoparsec.Text as A
12 | import Data.Char (isSpace)
13 | import qualified Data.OrgMode.Parse as O
14 | import qualified Data.OrgMode.Types as O
15 | import qualified Data.Text as T
16 | import Data.Time (LocalTime(..), TimeOfDay(..), fromGregorian, getZonedTime, zonedTimeToLocalTime)
17 | import Data.Time.Calendar ()
18 |
19 | import OrgStat.Ast (Clock(..), Org(..), orgTags, traverseTree)
20 |
21 | ----------------------------------------------------------------------------
22 | -- Exceptions
23 | ----------------------------------------------------------------------------
24 |
25 | data ParsingException = ParsingException Text
26 | deriving (Show, Typeable)
27 |
28 | instance Exception ParsingException
29 |
30 | ----------------------------------------------------------------------------
31 | -- Parsing
32 | ----------------------------------------------------------------------------
33 |
34 | parseOrg :: LocalTime -> [Text] -> A.Parser Org
35 | parseOrg curTime todoKeywords = convertDocument <$> O.parseDocument todoKeywords
36 | where
37 | convertDocument :: O.Document -> Org
38 | convertDocument (O.Document textBefore headings) =
39 | let fileLvlTags = extractFileTags textBefore
40 | addTags t = ordNub $ fileLvlTags <> t
41 | o = Org { _orgTitle = ""
42 | , _orgTags = []
43 | , _orgClocks = []
44 | , _orgSubtrees = map convertHeading headings
45 | }
46 | in o & traverseTree . orgTags %~ addTags
47 |
48 | convertHeading :: O.Headline -> Org
49 | convertHeading headline = Org
50 | { _orgTitle = O.title headline
51 | , _orgTags = O.tags headline
52 | , _orgClocks = getClocks $ O.section headline
53 | , _orgSubtrees = map convertHeading $ O.subHeadlines headline
54 | }
55 |
56 | mapEither :: (a -> Either e b) -> ([a] -> [b])
57 | mapEither f xs = rights $ map f xs
58 |
59 | getClocks :: O.Section -> [Clock]
60 | getClocks section =
61 | mapMaybe convertClock $ concat
62 | [ O.sectionClocks section
63 | , O.unLogbook (O.sectionLogbook section)
64 | , mapEither (A.parseOnly O.parseClock) $ concat
65 | [ concatMap lines $ map O.contents $ O.sectionDrawers section
66 | , lines $ O.sectionParagraph section
67 | ]
68 | ]
69 |
70 | -- convert clocks from orgmode-parse format, returns Nothing for clocks
71 | -- without end time or time-of-day
72 | convertClock :: O.Clock -> Maybe Clock
73 | convertClock (O.Clock (Just (O.Timestamp start _active (Just end)), _duration)) =
74 | Clock <$> convertDateTime start <*> convertDateTime end
75 | convertClock (O.Clock (Just (O.Timestamp start _active Nothing), _duration)) =
76 | Clock <$> convertDateTime start <*> pure curTime
77 | convertClock _ = Nothing
78 |
79 | -- Nothing for DateTime without time-of-day
80 | convertDateTime :: O.DateTime -> Maybe LocalTime
81 | convertDateTime
82 | O.DateTime
83 | { yearMonthDay = O.YearMonthDay year month day
84 | , hourMinute = Just (hour, minute)
85 | }
86 | = Just $ LocalTime
87 | (fromGregorian (toInteger year) month day)
88 | (TimeOfDay hour minute 0)
89 | convertDateTime _ = Nothing
90 |
91 | extractFileTags (T.lines -> inputLines) =
92 | let prfx = "#+FILETAGS: "
93 | matching =
94 | map (T.drop (length prfx)) $
95 | (filter (prfx `T.isPrefixOf`) inputLines)
96 | toTags (T.strip -> line) =
97 | let parts = filter (not . T.null) $ T.splitOn ":" line
98 | -- Correct tag shouldn't contain spaces inside
99 | correctPart p = not $ T.any isSpace p
100 | in if all correctPart parts then parts else []
101 | in ordNub $ concatMap toTags matching
102 |
103 | -- Throw parsing exception if it can't be parsed (use Control.Monad.Catch#throwM)
104 | runParser :: (MonadIO m, MonadThrow m) => [Text] -> Text -> m Org
105 | runParser todoKeywords t = do
106 | localTime <- liftIO $ zonedTimeToLocalTime <$> getZonedTime
107 | case A.parseOnly (parseOrg localTime todoKeywords) t of
108 | Left err -> throwM $ ParsingException $ T.pack err
109 | Right res -> pure res
110 |
--------------------------------------------------------------------------------
/orgstatExample.yaml:
--------------------------------------------------------------------------------
1 | ## This is example orgstat configuration file. Sadly it's still
2 | ## poorly documented, so check out Config.hs for more options in
3 | ## case something is missing.
4 |
5 |
6 | # Scopes are sets of org-mode files you consider as one single
7 | # working tree. Different possible scopes are possible, but
8 | # in general it's convenient to work with a single one, controlling
9 | # output with scope modifiers.
10 | scopes:
11 | # Scope without name is given the name "default".
12 | # In this particular example, the scope is represented by tree with
13 | # three root directories: /study/, /work/, and /private/.
14 | - paths: [/home/username/org/study.org, /home/username/org/work.org, /home/username/org/private.org.gpg]
15 | # This creates a tree with only one /secretAgentLife/ root directory.
16 | - name: alternative
17 | paths: [/home/username/secretAgentLife.org]
18 |
19 | # Reports are temporary internal representations of summaries that
20 | # we want to later output. Report works within the scope, applying
21 | # modifiers that change the working tree.
22 | reports:
23 | # Current week, all tasks
24 | - name: curWeekFull
25 | range: week # month-1, week-5, day-3 are possible (as in org-mode)
26 | # Current week, only work/study
27 | - name: curWeekTop
28 | range: week
29 | # scope: default # 'default' is the default scope, but you
30 | # can chose another one
31 | modifiers:
32 | # Prune modifier goes to node on path and transforms all
33 | # noes at depth 'depth' into leaves, collecting their
34 | # timestamps into one
35 | - type: prune
36 | path: /study/
37 | depth: 1
38 | - type: prune
39 | path: /work/
40 | depth: 1
41 | # Only study, previous week
42 | - name: prevWeekStudy
43 | range: week-1
44 | modifiers:
45 | # Select does 'cd' into the chosen node.
46 | - type: select
47 | path: study
48 | - type: prune
49 | path: /
50 | depth: 2
51 | - name: prevWeekWork
52 | range: week-1
53 | modifiers:
54 | - type: filterbytag
55 | tag: work # Tag name
56 | # Multiple tags are supported (as in "a|b")
57 | # tags: [work,study] #
58 |
59 | # Outputs are the ways to represent/materialise the reports. One report can
60 | # be outputed in several different ways. There is a discrete number of
61 | # outputs available.
62 | outputs:
63 |
64 | # Timeline output, it outputs the timeline svg from the report.
65 | - name: curWeekFullTimeline
66 | type: timeline
67 | report: curWeekFull
68 | - name: curWeekTopTimeline
69 | report: curWeekTop
70 | type: timeline
71 |
72 | # Statistics output accumulates total report durations into variable
73 | # and injects them into the given template. Finally, it writes the
74 | # resulting string into the file.
75 | - name: thisWeekStats
76 | type: summary
77 | template: "work: %prevWeekWork%, study: %prevWeekStudy%"
78 |
79 | # Script output is the generalisation of the previous one.
80 | # It will take a script and execute it with durations of
81 | # reports injected as environment variable with the same name.
82 | - name: scriptOutput
83 | type: script
84 | # One can choose between inline script or a path to the file
85 | inline: "echo $prevWeekWork > file.txt"
86 | # scriptPath: /path/to/script.sh
87 |
88 | # Reports to consider. Since we don't know generally what reports
89 | # are used inside the script, they can be specified here.
90 | # If this list is empty (default), then *all* reports will
91 | # be ran and injected!
92 | reports: [prevWeekWork]
93 |
94 | # Block output is something similar to the org-report -- it builds
95 | # a table with items and durations. Is useful for debugging.
96 | - name: blockOutput
97 | type: block
98 | unicode: true # Optional, default true
99 | maxLength: 60 # Optional, default 80
100 | report: curWeekTop
101 |
102 |
103 |
104 | # Must contain all todo keywords you use in files, because
105 | # otherwise parsed headings' titles will contain them prepended.
106 | todoKeywords: [ TODO, STARTED, WAITING, DONE, CANCELED ]
107 |
108 | # Default outputs parent folder. Subfolder for the particular output
109 | # will be auto-generated.
110 | outputDir: /home/username/reps/orgstat/
111 |
112 |
113 | # Optional parameters controlling timeline output:
114 | timelineDefault:
115 | colorSalt: 3 # Salt that controls coloring of report items, default 0
116 | colWidth: 1.2 # Width of single timeline column, default 1
117 | colHeight: 1.1 # Height of single timeline column, default 1
118 | topDay: 8 # Number of items in per-day longest-top list, default 5
119 | legend: true # Should legend be shown, default true
120 | background: '#ff00aa' # Background color, default white
121 |
122 |
--------------------------------------------------------------------------------
/src/OrgStat/Scope.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE DeriveGeneric, RankNTypes, ScopedTypeVariables, TemplateHaskell #-}
2 |
3 | -- | This module defines how report input is formed.
4 |
5 | module OrgStat.Scope
6 | ( AstPath (..)
7 | , isSubPath
8 | , existsPath
9 | , ScopeModifier (..)
10 | , applyModifiers
11 | ) where
12 |
13 | import qualified Prelude
14 | import Universum
15 |
16 | import Control.Lens (to)
17 | import Control.Monad.Except (throwError)
18 | import qualified Data.Text as T
19 |
20 | import OrgStat.Ast (Org, atDepth, orgClocks, orgSubtrees, orgTags, orgTitle, traverseTree)
21 |
22 | -- | Path in org AST is just a list of paths, head ~ closer to tree
23 | -- root.
24 | newtype AstPath = AstPath
25 | { getAstPath :: [Text]
26 | } deriving (Eq, Ord)
27 |
28 | instance Show AstPath where
29 | show (AstPath path)
30 | | null path = ""
31 | | otherwise = intercalate "/" (map T.unpack path)
32 |
33 | isSubPath :: AstPath -> AstPath -> Bool
34 | isSubPath (AstPath l1) (AstPath l2) = l1 `isPrefixOf` l2
35 |
36 | -- | Lens to a org node at path.
37 | atPath :: AstPath -> Lens' Org (Maybe Org)
38 | atPath (AstPath []) f o = fromMaybe o <$> f (Just o)
39 | atPath (AstPath p) f o = atPathDo p o
40 | where
41 | atPathDo [] org = f Nothing $> org
42 | atPathDo (x:xs) org =
43 | let match = find ((== x) . view orgTitle) $ org ^. orgSubtrees
44 | modified foo = org & orgSubtrees %~ foo . filter ((/= match) . Just)
45 | fmapFoo Nothing = modified id
46 | fmapFoo (Just o') = modified (o' :)
47 | in case (xs,match) of
48 | (_,Nothing) -> f Nothing $> org
49 | ([],_) -> fmap fmapFoo $ f match
50 | (cont,Just m) -> fmap (\new -> modified (new:)) $ atPathDo cont m
51 |
52 | -- | Checks if something is on that path in given 'Org'.
53 | existsPath :: AstPath -> Org -> Bool
54 | existsPath p o = o ^. atPath p . to isJust
55 |
56 | -- | Modificicators of org tree. They remove some subtrees
57 | data ScopeModifier
58 | = ModPruneSubtree AstPath Int
59 | -- ^ Turns all subtrees starting with @path@ and then on depth @d@ into leaves.
60 | | ModFilterTags [Text]
61 | -- ^ Given text tag names, it leaves only those subtrees that
62 | -- have one of these tag (tags are inherited).
63 | | ModSquash AstPath
64 | -- ^ Starting at node on path A and depth n, turn A into set of
65 | -- nodes A/a1/a2/.../an. Doesn't work/make sense for empty path.
66 | | ModSelectSubtree AstPath
67 | -- ^ Leaves only node at @path@, deletes all other subtrees.
68 | deriving (Show,Eq,Ord)
69 |
70 | -- | Errors related to modifiers application
71 | data ModifierError
72 | = MEConflicting ScopeModifier ScopeModifier Text
73 | -- ^ Modifiers can't be applied together (del/sel)
74 | | MEWrongParam ScopeModifier Text
75 | -- ^ Modifier doesn't support this parameter
76 | deriving (Show,Typeable)
77 |
78 | instance Exception ModifierError
79 |
80 | -- | Applies modifier to org tree
81 | applyModifier :: ScopeModifier -> Org -> Either ModifierError Org
82 | applyModifier m@(ModPruneSubtree path depth) org = do
83 | unless (depth >= 0) $ throwError $ MEWrongParam m "Depth should be >= 0"
84 | unless (existsPath path org) $
85 | throwError $ MEWrongParam m $ "Path " <> show path <> " doesn't exist"
86 | let subclocks o' = o' & orgClocks .~ (concatMap (view orgClocks) $ o' ^.. traverseTree)
87 | & orgSubtrees .~ []
88 | let pruneChildren o = o & atDepth depth %~ subclocks
89 | pure $ org & atPath path %~ (\x -> maybe x (Just . pruneChildren) x)
90 | applyModifier m@(ModSelectSubtree path) org = do
91 | unless (existsPath path org) $
92 | throwError $ MEWrongParam m $ "Path " <> show path <> " doesn't exist"
93 | pure $
94 | fromMaybe (error "applyModifier@ModSelectSubtree is broken") $
95 | org ^. atPath path
96 | applyModifier (ModFilterTags tags) o0 = do
97 | let matchesTag o = any (`elem` tags) (o ^. orgTags)
98 | let dfs :: Org -> Maybe Org
99 | dfs o | matchesTag o = Just o
100 | | otherwise = case mapMaybe dfs (o ^. orgSubtrees) of
101 | [] -> Nothing
102 | xs -> Just $ o & orgSubtrees .~ xs
103 | Right $ o0 & orgSubtrees %~ mapMaybe dfs
104 | applyModifier _ org = pure org -- TODO
105 |
106 | -- | Generates an org to be processed by report generators from 'Scope'.
107 | applyModifiers :: Org -> [ScopeModifier] -> Either ModifierError Org
108 | applyModifiers org s = do
109 | -- whenList addDelConflicts $ \(m1,m2) ->
110 | -- throwError $ MEConflicting m1 m2 "Path of first modifier is subpath of second one"
111 | foldrM applyModifier org mods
112 | where
113 | -- whenList ls foo = case ls of
114 | -- [] -> pass
115 | -- (h:_) -> foo h
116 | -- addDelConflicts =
117 | -- let addDelConflict (ModPruneSubtree a _) (ModSelectSubtree b) = a `isSubPath` b
118 | -- addDelConflict _ _ = False
119 | -- in filter (uncurry addDelConflict) modsPairs
120 | -- modsPairs = [(a,b) | a <- mods, b <- mods, a < b]
121 | mods = sort s
122 |
--------------------------------------------------------------------------------
/orgstat.cabal:
--------------------------------------------------------------------------------
1 | name: orgstat
2 | version: 0.1.10
3 | synopsis: Statistics visualizer for org-mode
4 | license: GPL-3
5 | license-file: LICENSE
6 | extra-source-files: CHANGES.md
7 | homepage: https://github.com/volhovM/orgstat
8 | author: Mikhail Volkhov , Zhenya Vinogradov
9 | maintainer: volhovm.cs@gmail.com
10 | build-type: Simple
11 | cabal-version: >=1.10
12 |
13 | library
14 | exposed-modules: OrgStat.Ast
15 | , OrgStat.Config
16 | , OrgStat.CLI
17 | , OrgStat.Helpers
18 | , OrgStat.IO
19 | , OrgStat.Logging
20 | , OrgStat.Logic
21 | , OrgStat.Parser
22 | , OrgStat.Scope
23 | , OrgStat.Outputs
24 | , OrgStat.Outputs.Block
25 | , OrgStat.Outputs.Class
26 | , OrgStat.Outputs.Summary
27 | , OrgStat.Outputs.Script
28 | , OrgStat.Outputs.Timeline
29 | , OrgStat.Outputs.Types
30 | , OrgStat.Util
31 | , OrgStat.WorkMonad
32 | , Paths_orgstat
33 | build-depends: aeson >= 0.11.2.0
34 | , attoparsec
35 | , ansi-terminal
36 | , base >=4.13 && <4.15
37 | , boxes >= 0.1.4
38 | , bytestring
39 | , colour >= 2.3.3
40 | , containers >= 0.5.7.1
41 | , data-default >= 0.7.1.1
42 | , diagrams-lib
43 | , diagrams-svg
44 | , directory
45 | , exceptions >= 0.8.3
46 | , filepath
47 | , formatting
48 | , fmt >= 0.6
49 | , hashable >= 1.2.4.0
50 | , lens >= 4.14
51 | , mtl >= 2.2.1
52 | , optparse-simple
53 | , orgmode-parse >= 0.2.3 && < 0.3
54 | , process >= 1.6.3.0
55 | , text >= 1.2.2.1
56 | , time >= 1.6.0.1
57 | , turtle >= 1.2.8
58 | , universum >= 1.5.0
59 | , yaml >= 0.8.21.1
60 | hs-source-dirs: src
61 | default-language: Haskell2010
62 | ghc-options: -Wall
63 | default-extensions: GeneralizedNewtypeDeriving
64 | StandaloneDeriving
65 | FlexibleContexts
66 | FlexibleInstances
67 | MultiParamTypeClasses
68 | FunctionalDependencies
69 | NoImplicitPrelude
70 | OverloadedStrings
71 | ScopedTypeVariables
72 | RecordWildCards
73 | TypeApplications
74 | TupleSections
75 | ViewPatterns
76 | LambdaCase
77 | MultiWayIf
78 |
79 | executable orgstat
80 | main-is: Main.hs
81 | other-modules: Paths_orgstat
82 | build-depends: base
83 | , bytestring
84 | , directory
85 | , exceptions
86 | , filepath
87 | , formatting
88 | , optparse-simple
89 | , orgstat
90 | , universum
91 | hs-source-dirs: src/cli
92 | default-language: Haskell2010
93 | ghc-options: -threaded -Wall -O2
94 | default-extensions: NoImplicitPrelude
95 | OverloadedStrings
96 | RecordWildCards
97 | TypeApplications
98 |
99 | executable orgstatarch
100 | main-is: Main.hs
101 | other-modules: Paths_orgstat
102 | build-depends: base
103 | , attoparsec
104 | , bytestring
105 | , directory
106 | , exceptions
107 | , filepath
108 | , formatting
109 | , optparse-simple
110 | , orgstat
111 | , time
112 | , turtle
113 | , text
114 | , orgmode-parse
115 | , unordered-containers
116 | , universum
117 | hs-source-dirs: src/arch
118 | default-language: Haskell2010
119 | ghc-options: -threaded -Wall -O2
120 | default-extensions: NoImplicitPrelude
121 | OverloadedStrings
122 | RecordWildCards
123 | LambdaCase
124 | TypeApplications
125 | TupleSections
126 |
127 | test-suite orgstat-test
128 | main-is: Test.hs
129 | other-modules: Spec
130 | , GlobalSpec
131 | build-depends: HUnit >= 1.3.1.2
132 | , QuickCheck
133 | , base
134 | , colour >= 2.3.3
135 | , hspec
136 | , orgstat
137 | , lens
138 | , quickcheck-text >= 0.1.2.1
139 | , time >= 1.6.0.1
140 | , text
141 | , transformers
142 | , universum >= 0.5.1.1
143 | type: exitcode-stdio-1.0
144 | hs-source-dirs: test
145 | default-language: Haskell2010
146 | ghc-options: -threaded -rtsopts
147 | -Wall
148 | -fno-warn-orphans
149 | -O2
150 | default-extensions: NoImplicitPrelude
151 | OverloadedStrings
152 | RecordWildCards
153 | TypeApplications
154 | GeneralizedNewtypeDeriving
155 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # orgstat
2 |
3 | [](https://travis-ci.org/volhovM/orgstat)
4 | [](http://hackage.haskell.org/package/orgstat)
5 |
6 | Orgstat is a statistics visualizer tool for org-mode. Given a set of org-mode files (gpg supported!),
7 | it parses their AST, applies modifications such as tag filtering, pruning or selecting a subtree (which yields a _report_) and generates an _output_ of a specific type. Currently supported output types are:
8 | * Timeline output: an SVG image that plots time intervals as horizontal bars on a vertical day-bar, for every day of the selected report range (e.g. for a week).
9 | * Summary output: for a template string, `orgstat` replaces each `%reportName%` substring in it by the duration spent on the corresponding report. This is useful for outputting progress info into the status bar, e.g. to keep track of number of hours spent on work today/this week.
10 | * Script output: a generalization of summary output. Instead of outputting a single string with substitutions, selected reports' durations are set as the environment variables and passed to the user-specified script that is run in this new environment.
11 | * Block output: similar to the default `org-clock-report`, though formatting is more similar to one that `tree` Unix utility provides. I am using it primarily for debugging.
12 |
13 | ## Building/installing
14 |
15 | `orgstat` uses haskell build tool [stack](https://docs.haskellstack.org/en/stable/README/). In order to build the project, run `stack build` in the project directory. Then, `stack exec orgstat -- --help` is the way to run the executable.
16 |
17 | Since `orgstat` is also available on hackage, you can use `cabal install orgstat` to obtain it. If you are using `nix` package manager you can find `orgstat` in `nixpkgs` as `haskellPackages.orgstat` since `nixpkgs` has effectively everything available on hackage directly.
18 |
19 | To install `orgstat` with `nix`:
20 | ```
21 | nix-env -f "" -iA haskellPackages.orgstat
22 | ```
23 |
24 | ## Running
25 |
26 | Check out [orgstatExample.yaml](./orgstatExample.yaml) sample configuration file (or my [personal](https://github.com/volhovm/dotfiles/blob/master/config/.orgstat.yaml) config) and `orgstat --help`:
27 | ```
28 | $> orgstat --help
29 | ----- OrgStat ------
30 |
31 | Usage: orgstat [--version] [--help] [--conf-path FILEPATH] [--debug]
32 | [--xdg-open] [--output|--select-output ARG]
33 | [--output-dir FILEPATH]
34 | Statistic reports visualizer for org-mode
35 |
36 | Available options:
37 | --version Show version
38 | --help Show this help text
39 | --conf-path FILEPATH Path to the configuration file
40 | --debug Enable debug logging
41 | --xdg-open Open each report using xdg-open
42 | --output,--select-output ARG
43 | Output name(s) you want to process (default: all
44 | outputs are processed)
45 | --output-dir FILEPATH Final output directory that overrides one in config.
46 | No extra subdirectories will be created
47 | ```
48 | ## Examples
49 |
50 | See the [orgstatExample.yaml](./orgstatExample.yaml) configuration file.
51 |
52 | Here is how a timeline report output looks like:
53 | 
54 |
55 | To use `script` type output to put current progress reports into `xmobar`:
56 | ```
57 | # all the reports are defined with a week range and a single filterbytag modifier with an appropriate tag
58 | - name: curWeekStats
59 | type: summary
60 | template: "%thisWeekWork%/%thisWeekStudy% %thisWeekA1%/%thisWeekA2%/%thisWeekA3% %thisWeekI%/%thisWeekE%"
61 | ```
62 |
63 | Then by running `stack exec orgstat -- --select-output resolveOutput --output-dir ~/`, `orgstat` puts the report into `~/curWeekStats.txt` yielding something like `0:57/0:09 2:03/2:48/3:16 1:57/2:34` inside. Next add a bit of cron and an xmobar task to read the text out of this file.
64 |
65 | Alternatively, it is possible to use a more involved `script` type output, which passes all the relevant report length variables to the interpreter program, via environment variables. It is configured in the following way:
66 | ```
67 | - name: thisWeekStatsScript
68 | type: script
69 | interpreter: "/bin/env sh"
70 | scriptPath: ~/dotfiles/scripts/orgstat_format_bar.sh
71 | reports: [thisWeekM,thisWeekH,thisWeekA,thisWeekE,todayM,todayH,todayA,todayE]
72 | ```
73 | For the report `x`, `orgstat` will inject variable `x` containing the sum of intervals in the report (this is useful to summarise how many time was spent on a particular task category), and additionally it will inject a `xDurationsList` variable containing the list of all durations (which I personally use to count all 25min-long intervals, in a pomodoro-like fashion).
74 | For the interpreter script example, see [my dotfiles](https://github.com/volhovm/dotfiles/blob/master/scripts/orgstat_format_bar.sh).
75 |
76 | ## Archiving tool
77 |
78 | The executable `orgstatarch` provides a simple script that accepts a file as an input, and splits it in two according to the date provided.
79 | The old file is an archive, and the new file is intended to be a refreshed version of the file passed.
80 | The main difference from the default archiving tools org-mode provides is that `orgstatarch` tries to keep the current tree structure intact; that is, the archive structure is the same as the structure of the original file.
81 | In particular, for the tasks that are never marked as done, but only accumulate logging intervals, `orgstatarch` will put two versions of this task in both files, with intervals split correspondingly.
82 | This is quite helpful to get rid of massive `LOGBOOK` drawers.
83 |
84 | The tool is highly work-in-progress (e.g. it assumes the specific output formatting, so one might want to apply `org-indent-region` on the outputs of `orgstatarch`), but it nevertheless illustrates how simple writing scripts with `orgstat` and `orgmode-parse` can be.
85 |
86 | ## Bugs and issues
87 |
88 | If you experience any problems with the application, you can use `block` output and `--debug` to see, first of all, whether the org file is parsed correctly. And, of course, feel free to leave issues.
89 |
--------------------------------------------------------------------------------
/src/OrgStat/Ast.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE RankNTypes, TemplateHaskell #-}
2 |
3 | -- | Abstract syntax tree for org.
4 |
5 | module OrgStat.Ast
6 | ( Clock (..)
7 | , Org (..)
8 | , orgTitle
9 | , orgTags
10 | , orgClocks
11 | , orgSubtrees
12 |
13 | , clockDuration
14 | , orgDurations
15 | , orgTotalDuration
16 | , orgMeanDuration
17 | , orgMedianDuration
18 | , orgPomodoroNum
19 | , filterHasClock
20 | , cutFromTo
21 | , fmapOrgLens
22 | , traverseTree
23 | , atDepth
24 | , mergeClocks
25 | ) where
26 |
27 | import Control.Lens (ASetter', makeLenses)
28 | import Data.List ((!!))
29 | import Data.Time (LocalTime, NominalDiffTime, diffUTCTime, localTimeToUTC, utc)
30 |
31 | import Universum
32 |
33 | ----------------------------------------------------------------------------
34 | -- Types
35 | ----------------------------------------------------------------------------
36 |
37 | -- | Org clock representation -- a pair of time in UTC. Should be
38 | -- local time in fact, but we'll assume that UTC timestamps support in
39 | -- org will be added at some point. For now all tags are to be read in
40 | -- local time.
41 | data Clock = Clock
42 | { cFrom :: LocalTime
43 | , cTo :: LocalTime
44 | } deriving (Show,Eq,Ord)
45 |
46 | -- | Main datatype of org AST. It may contain some metadata if needed
47 | -- (e.g. current node depth, children number etc). Content of headers
48 | -- is ignored.
49 | data Org = Org
50 | { _orgTitle :: Text
51 | , _orgTags :: [Text]
52 | , _orgClocks :: [Clock]
53 | , _orgSubtrees :: [Org]
54 | } deriving (Show,Eq)
55 |
56 | makeLenses ''Org
57 |
58 | ----------------------------------------------------------------------------
59 | -- Helpers and lenses
60 | ----------------------------------------------------------------------------
61 |
62 | -- | Merge adjacent clocks from the list into one, return sorted list.
63 | glueAdjacent :: [Clock] -> [Clock]
64 | glueAdjacent clocks = go (sort clocks)
65 | where
66 | go [] = []
67 | go [x] = [x]
68 | go (a:b:xs) = if cTo a >= cFrom b then go (Clock (cFrom a) (cTo b) : xs)
69 | else a : go (b:xs)
70 |
71 | -- | Duration of the clock
72 | clockDuration :: Clock -> NominalDiffTime
73 | clockDuration (Clock (localTimeToUTC utc -> from) (localTimeToUTC utc -> to)) =
74 | diffUTCTime to from
75 |
76 | -- | All durations of a single org file
77 | orgDurations :: Org -> [NominalDiffTime]
78 | orgDurations org =
79 | map clockDuration $ glueAdjacent $ concat $ org ^.. traverseTree . orgClocks
80 |
81 | -- | Calculate total clocks duration in org tree.
82 | orgTotalDuration :: Org -> NominalDiffTime
83 | orgTotalDuration = sum . orgDurations
84 |
85 | -- | Calculate mean duration of clocks in the given org tree.
86 | orgMeanDuration :: Org -> NominalDiffTime
87 | orgMeanDuration = mean . orgDurations
88 | where
89 | mean [] = 0
90 | mean xs = sum xs / fromIntegral (length xs)
91 |
92 | -- | Calculate mean duration of clocks in the given org tree.
93 | orgMedianDuration :: Org -> NominalDiffTime
94 | orgMedianDuration = median . orgDurations
95 | where
96 | median [] = 0
97 | median [a] = a
98 | median xs = let sorted = sort xs in
99 | let n = length xs in
100 | if odd n then sorted !! (n `div` 2)
101 | else (sorted !! (n `div` 2 - 1) + sorted !! (n `div` 2)) / 2
102 |
103 | -- | Number of intervals \geq 25min. Intervals that are (25 * n + p)
104 | -- mins long with p < 25 count as n pomodoros.
105 | orgPomodoroNum :: Org -> Int
106 | orgPomodoroNum =
107 | sum . map (\dur -> truncate dur `div` (25 * 60 :: Int)) . orgDurations
108 |
109 | -- | Remove subtrees that have zero total duration.
110 | filterHasClock :: Org -> Org
111 | filterHasClock = orgSubtrees %~ mapMaybe dfs
112 | where
113 | dfs :: Org -> Maybe Org
114 | dfs o = do
115 | let children = mapMaybe dfs (o ^. orgSubtrees)
116 | let ownDur = sum $ map clockDuration (o ^. orgClocks)
117 | if ownDur == 0 && null children
118 | then Nothing
119 | else Just $ o & orgSubtrees .~ children
120 |
121 | cutFromTo :: (LocalTime, LocalTime) -> Org -> Org
122 | cutFromTo (from, to) o
123 | | from >= to = error "cutFromTo: from >= to"
124 | | otherwise = o & traverseTree %~ filterClocks
125 | where
126 | -- Cuts clock relatively to from/to or discards if it's not in the
127 | -- interval.
128 | fitClock :: Clock -> Maybe Clock
129 | fitClock Clock{..} = do
130 | guard $ cFrom <= to
131 | guard $ cTo >= from
132 | pure $ Clock (max cFrom from) (min cTo to)
133 |
134 | filterClocks :: Org -> Org
135 | filterClocks = orgClocks %~ mapMaybe fitClock
136 |
137 | -- | Functor-like 'fmap' on field chosen by lens.
138 | fmapOrgLens :: ASetter' Org a -> (a -> a) -> Org -> Org
139 | fmapOrgLens l f o = o & l %~ f & orgSubtrees %~ map (fmapOrgLens l f)
140 |
141 | -- | Traverses node and subnodes, all recursively. Bottom-top.
142 | traverseTree :: Traversal' Org Org
143 | traverseTree f o = o'
144 | where
145 | o' = liftA2 (\org x -> org & orgSubtrees .~ x) (f o) traversedChildren
146 | traversedChildren = traverse (traverseTree f) $ o ^. orgSubtrees
147 |
148 | atDepth :: Int -> Traversal' Org Org
149 | atDepth i _ o | i < 0 = pure o
150 | atDepth 0 f o = f o
151 | atDepth n f o =
152 | (\x -> o & orgSubtrees .~ x) <$> traverse (atDepth (n-1) f) (o ^. orgSubtrees)
153 |
154 | -- TODO This should consider the following situation:
155 | -- Task A: 00:03 - 00:10
156 | -- Task B: 00:10 - 00:11
157 | -- Task A: 00:11 - 00:12
158 | --
159 | -- It will merge A, and thus A will interlap with B, which is undesirable.
160 | -- | Merges task clocks that have less then 2m delta between them into
161 | -- one.
162 | mergeClocks :: Org -> Org
163 | mergeClocks = fmapOrgLens orgClocks (mergeClocksDo . sort)
164 | where
165 | toUTC = localTimeToUTC utc
166 | mergeClocksDo [] = []
167 | mergeClocksDo [x] = [x]
168 | mergeClocksDo (a:b:xs)
169 | | toUTC (cFrom b) `diffUTCTime ` toUTC (cTo a) < 2*60 =
170 | mergeClocksDo $ (Clock (cFrom a) (cTo b)):xs
171 | | otherwise = a : mergeClocksDo (b:xs)
172 |
--------------------------------------------------------------------------------
/src/OrgStat/Helpers.hs:
--------------------------------------------------------------------------------
1 | -- | Different logic-related components.
2 |
3 | module OrgStat.Helpers
4 | ( convertRange
5 | , resolveInputOrg
6 | , resolveScope
7 | , resolveReport
8 | , resolveOutput
9 | ) where
10 |
11 | import Universum
12 |
13 | import Control.Lens (at, views, (.=))
14 | import qualified Data.List.NonEmpty as NE
15 | import Data.Time
16 | (LocalTime(..), TimeOfDay(..), addDays, getZonedTime, toGregorian, zonedTimeToLocalTime)
17 | import Data.Time.Calendar (addGregorianMonthsRollOver)
18 | import Data.Time.Calendar.WeekDate (toWeekDate)
19 |
20 | import OrgStat.Ast (Org(..), cutFromTo, orgTitle)
21 | import OrgStat.Config
22 | (ConfDate(..), ConfOutput(..), ConfRange(..), ConfReport(..), ConfScope(..), ConfigException(..),
23 | OrgStatConfig(..))
24 | import OrgStat.IO (readOrgFile)
25 | import OrgStat.Scope (applyModifiers)
26 | import OrgStat.WorkMonad (WorkM, wcConfig, wdReadFiles, wdResolvedReports, wdResolvedScopes)
27 |
28 |
29 | -- | Converts config range to a pair of 'UTCTime', right bound not inclusive.
30 | convertRange :: (MonadIO m) => ConfRange -> m (LocalTime, LocalTime)
31 | convertRange range = case range of
32 | (ConfFromTo f t) -> (,) <$> fromConfDate f <*> fromConfDate t
33 | (ConfBlockDay i) | i < 0 -> error $ "ConfBlockDay i is <0: " <> show i
34 | (ConfBlockDay 0) -> (,) <$> (localFromDay <$> startOfDay) <*> curTime
35 | (ConfBlockDay i) -> do
36 | d <- (negate (i - 1) `addDays`) <$> startOfDay
37 | pure $ localFromDayPair ((negate 1) `addDays` d, d)
38 | (ConfBlockWeek i) | i < 0 -> error $ "ConfBlockWeek i is <0: " <> show i
39 | (ConfBlockWeek 0) -> (,) <$> (localFromDay <$> startOfWeek) <*> curTime
40 | (ConfBlockWeek i) -> do
41 | d <- (negate (i - 1) `addWeeks`) <$> startOfWeek
42 | pure $ localFromDayPair ((negate 1) `addWeeks` d, d)
43 | (ConfBlockMonth i) | i < 0 -> error $ "ConfBlockMonth i is <0: " <> show i
44 | (ConfBlockMonth 0) -> (,) <$> (localFromDay <$> startOfMonth) <*> curTime
45 | (ConfBlockMonth i) -> do
46 | d <- addGregorianMonthsRollOver (negate $ i-1) <$> startOfMonth
47 | pure $ localFromDayPair ((negate 1) `addGregorianMonthsRollOver` d, d)
48 | where
49 | localFromDay d = LocalTime d $ TimeOfDay 0 0 0
50 | localFromDayPair = bimap localFromDay localFromDay
51 | curTime = liftIO $ zonedTimeToLocalTime <$> getZonedTime
52 | curDay = localDay <$> curTime
53 | addWeeks i d = (i*7) `addDays` d
54 | startOfDay = curDay
55 | startOfWeek = do
56 | d <- curDay
57 | let weekDay = pred $ view _3 $ toWeekDate d
58 | pure $ fromIntegral (negate weekDay) `addDays` d
59 | startOfMonth = do
60 | d <- curDay
61 | let monthDate = pred $ view _3 $ toGregorian d
62 | pure $ fromIntegral (negate monthDate) `addDays` d
63 | fromConfDate ConfNow = curTime
64 | fromConfDate (ConfLocal x) = pure x
65 |
66 | -- | Resolves org file: reads from path and puts into state or just
67 | -- gets out of state if was read before.
68 | resolveInputOrg :: FilePath -> WorkM (Text, Org)
69 | resolveInputOrg fp = use (wdReadFiles . at fp) >>= \case
70 | Just x -> pure x
71 | Nothing -> do
72 | todoKeywords <- views wcConfig confTodoKeywords
73 | o <- readOrgFile todoKeywords fp
74 | wdReadFiles . at fp .= Just o
75 | pure o
76 |
77 | -- A lot of copy-paste here... 2 bad, though no time to fix
78 |
79 | -- | Return scope with requested name or fail. It will be either
80 | -- constructed on the spot or taken from the state if it had been
81 | -- created previously.
82 | resolveScope :: Text -> WorkM Org
83 | resolveScope scopeName = use (wdResolvedScopes . at scopeName) >>= \case
84 | Just x -> pure x
85 | Nothing -> constructScope
86 | where
87 | constructScope = do
88 | let filterScopes = filter (\x -> csName x == scopeName)
89 | views wcConfig (filterScopes . confScopes) >>= \case
90 | [] ->
91 | throwM $ ConfigLogicException $
92 | "Scope "<> scopeName <> " is not declared"
93 | [sc] -> resolveFoundScope sc
94 | scopes ->
95 | throwM $ ConfigLogicException $
96 | "Multple scopes with name "<> scopeName <>
97 | " are declared " <> show scopes
98 | resolveFoundScope ConfScope{..} = do
99 | orgs <- NE.toList <$> forM csPaths resolveInputOrg
100 | let orgTop = Org "/" [] [] $ map (\(fn,o) -> o & orgTitle .~ fn) orgs
101 | wdResolvedScopes . at scopeName .= Just orgTop
102 | pure orgTop
103 |
104 | -- | Same as resolveScope but related to reports.
105 | resolveReport :: Text -> WorkM Org
106 | resolveReport reportName = use (wdResolvedReports . at reportName) >>= \case
107 | Just x -> pure x
108 | Nothing -> constructReport
109 | where
110 | constructReport = do
111 | let filterReports = filter (\x -> crName x == reportName)
112 | views wcConfig (filterReports . confReports) >>= \case
113 | [] ->
114 | throwM $ ConfigLogicException $
115 | "Report " <> reportName <> " is not declared"
116 | [rep] -> resolveFoundReport rep
117 | reports ->
118 | throwM $ ConfigLogicException $
119 | "Multple reports with name "<> reportName <>
120 | " are declared " <> show reports
121 | resolveFoundReport ConfReport{..} = do
122 | orgTop <- resolveScope crScope
123 | fromto <- convertRange crRange
124 | withModifiers <-
125 | either throwM pure $
126 | applyModifiers orgTop crModifiers
127 | --let finalOrg = cutFromTo fromto $ mergeClocks withModifiers
128 | let finalOrg = cutFromTo fromto withModifiers
129 | wdResolvedReports . at reportName .= Just finalOrg
130 | pure finalOrg
131 |
132 | resolveOutput :: Text -> WorkM ConfOutput
133 | resolveOutput outputName =
134 | views wcConfig (filterOutputs . confOutputs) >>= \case
135 | [] ->
136 | throwM $ ConfigLogicException $
137 | "Report " <> outputName <> " is not declared"
138 | [rep] -> pure rep
139 | reports ->
140 | throwM $ ConfigLogicException $
141 | "Multple outputs with name "<> outputName <>
142 | " are declared " <> show reports
143 | where
144 | filterOutputs = filter (\x -> coName x == outputName)
145 |
--------------------------------------------------------------------------------
/test/GlobalSpec.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE ScopedTypeVariables #-}
2 |
3 | module GlobalSpec (spec) where
4 |
5 | import Control.Lens (to)
6 | import Data.Colour.SRGB (sRGB24show)
7 | import qualified Data.List as L
8 | import qualified Data.Text as T
9 | import Data.Text.Arbitrary ()
10 | import Data.Time (LocalTime(..), TimeOfDay(..), getZonedTime, zonedTimeToLocalTime)
11 | import Data.Time.Calendar (addGregorianMonthsClip, fromGregorian)
12 | import Test.Hspec (Spec, describe, runIO)
13 | import Test.Hspec.QuickCheck (prop)
14 | import Test.QuickCheck
15 | (Arbitrary(arbitrary), Gen, NonNegative(..), Positive(..), Small(..), choose, forAll, ioProperty,
16 | oneof, (.&&.), (===), (==>))
17 | import Universum
18 |
19 | import OrgStat.Ast (Clock(..), Org(..), atDepth, mergeClocks, orgClocks)
20 | import OrgStat.Config (ConfDate(..), ConfRange(..))
21 | import OrgStat.Helpers (convertRange)
22 | import OrgStat.Util (addLocalTime, parseColour)
23 |
24 |
25 | spec :: Spec
26 | spec = do
27 | astSpec
28 | parseColourSpec
29 | convertRangeSpec
30 |
31 | ----------------------------------------------------------------------------
32 | -- AST
33 | ----------------------------------------------------------------------------
34 |
35 | instance Arbitrary LocalTime where
36 | arbitrary = do
37 | d <- choose (1, 28)
38 | m <- choose (1, 12)
39 | y <- choose (2015, 2016)
40 | todHour <- choose (0, 23)
41 | todMin <- choose (0, 59)
42 | todSec <- fromIntegral <$> (choose (0, 60) :: Gen Int)
43 | return $ LocalTime (fromGregorian y m d) TimeOfDay{..}
44 |
45 | instance Arbitrary Clock where
46 | arbitrary = do
47 | a <- arbitrary
48 | b <- arbitrary
49 | pure . (uncurry Clock) $ if a < b then (a,b) else (b,a)
50 |
51 | genOrgDepth :: Int -> Gen Org
52 | genOrgDepth n = do
53 | childrenN <- choose (1,2)
54 | clock <- arbitrary
55 | name <- T.take 10 <$> arbitrary
56 | children <-
57 | if n == 0
58 | then pure []
59 | else replicateM childrenN (genOrgDepth $ n - 1)
60 | pure $ Org name [] [clock] children
61 |
62 | instance Arbitrary Org where
63 | arbitrary = genOrgDepth 5
64 |
65 | newtype OrgWrapper = OrgWrapper Org deriving Show
66 |
67 | -- Generates an org file with almost-fitting intervals that should be
68 | -- merged in one
69 | contOrg :: Int -> Int -> Gen Org
70 | contOrg dfrom dto = do
71 | (Positive i) <- arbitrary
72 | (checkpoints :: [LocalTime]) <- sort <$> replicateM (i+1) arbitrary
73 | pairs <- forM (checkpoints `zip` L.tail checkpoints) $ \(c,c') -> do
74 | delta <- choose (dfrom,dto)
75 | pure (c, negate delta `addLocalTime` c')
76 | let clocks = map (uncurry Clock) pairs
77 | pure $ Org "ShouldHaveOneSubclock" [] clocks []
78 |
79 | astSpec :: Spec
80 | astSpec = do
81 | describe "Ast#mergeClocks" $ do
82 | prop "merges a set of clocks when needed into one" $
83 | forAll (contOrg 0 90) $ \o ->
84 | mergeClocks o ^. orgClocks . to length === 1
85 | prop "doesn't modify big deltas" $
86 | forAll (contOrg 120 240) $ \o -> mergeClocks o === o
87 | describe "Ast#lenses" $ do
88 | prop "atDepth 0 is always the same" $
89 | forAll arbitrary $ \o -> o ^.. atDepth 0 === [o]
90 | prop "atDepth i for i-tree is not empty" $
91 | forAll arbitrary $ \(Positive (Small i)) ->
92 | forAll (genOrgDepth i) $ \o ->
93 | i < 10 ==> (o ^.. atDepth i /= [])
94 | prop "atDepth (i+1) for i-tree is empty" $
95 | forAll arbitrary $ \(Positive (Small i)) ->
96 | forAll (genOrgDepth i) $ \o ->
97 | i < 10 ==> (o ^.. atDepth (i+1) === [])
98 |
99 | ----------------------------------------------------------------------------
100 | -- Ranges
101 | ----------------------------------------------------------------------------
102 |
103 | convertRangeSpec :: Spec
104 | convertRangeSpec = describe "Logic#convertRange" $ do
105 | curTime <- runIO $ zonedTimeToLocalTime <$> getZonedTime
106 | let subDays a i = (negate i * 60 * 60 * 24) `addLocalTime` a
107 | let subWeeks a i = (negate i * 60 * 60 * 24 * 7) `addLocalTime` a
108 | let subMonths a i = a { localDay = (negate i) `addGregorianMonthsClip` (localDay a) }
109 | let inRange c (a,b) = c >= a && c <= b
110 | let convert = liftIO . convertRange
111 | prop "(now-1h, now) is correctly parsed" $
112 | forAll arbitrary $ \(Positive (Small (i :: Integer))) ->
113 | let hourAgo = (negate i * 60 * 60) `addLocalTime` curTime
114 | in ioProperty (inRange curTime <$> convert (ConfFromTo (ConfLocal hourAgo) ConfNow))
115 | prop "Today -N days is exactly in day-N range" $
116 | forAll arbitrary $ \(NonNegative (Small i)) ->
117 | ioProperty (inRange (subDays curTime i) <$> convert (ConfBlockDay i)) .&&.
118 | ioProperty (not . inRange (subDays curTime $ i+1) <$> convert (ConfBlockDay i)) .&&.
119 | ioProperty (not . inRange (subDays curTime $ i) <$> convert (ConfBlockDay $ i+1))
120 | prop "Today -N weeks is exactly in week-N range" $
121 | forAll arbitrary $ \(NonNegative (Small i)) ->
122 | ioProperty (inRange (subWeeks curTime i) <$> convert (ConfBlockWeek i)) .&&.
123 | ioProperty (not . inRange (subWeeks curTime $ i+1) <$> convert (ConfBlockWeek i)) .&&.
124 | ioProperty (not . inRange (subWeeks curTime $ i) <$> convert (ConfBlockWeek $ i+1))
125 | prop "Today -N months is excatly in month-N range" $
126 | forAll arbitrary $ \(NonNegative (Small i)) ->
127 | ioProperty (inRange (subMonths curTime i) <$> convert (ConfBlockMonth i)) .&&.
128 | ioProperty (not . inRange (subMonths curTime $ i+1) <$> convert (ConfBlockMonth i)) .&&.
129 | ioProperty (not . inRange (subMonths curTime i) <$> convert (ConfBlockMonth $ i+1))
130 |
131 |
132 | ----------------------------------------------------------------------------
133 | -- Utils
134 | ----------------------------------------------------------------------------
135 |
136 | newtype ColorWrapper = ColorWrapper Text deriving Show
137 |
138 | instance Arbitrary ColorWrapper where
139 | arbitrary = do
140 | nums <- replicateM 6 $ oneof $ map pure "0123456789abcdef"
141 | pref <- oneof $ map pure ["#", mempty]
142 | pure $ ColorWrapper $ pref <> T.pack nums
143 |
144 | parseColourSpec :: Spec
145 | parseColourSpec = describe "Util#parseColour" $ do
146 | prop "Doesn't fail on correct inputs" $
147 | forAll arbitrary $ \(ColorWrapper s) ->
148 | let s' = T.unpack $ if "#" `T.isPrefixOf` s then s else "#" <> s
149 | in (sRGB24show <$> (parseColour @Text @Double s)) === Just s'
150 | prop "Fails on incorrect inputs" $
151 | forAll arbitrary $ \s ->
152 | length s > 6 ==> (parseColour @Text @Double s) === Nothing
153 |
--------------------------------------------------------------------------------
/src/OrgStat/Config.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE RecordWildCards, TemplateHaskell, TypeApplications #-}
2 | {-# OPTIONS_GHC -Wno-orphans #-}
3 |
4 | -- | Configuration file types, together with json instances.
5 |
6 | module OrgStat.Config
7 | ( ConfigException (..)
8 | , ConfDate (..)
9 | , ConfRange (..)
10 | , ConfOutputType (..)
11 | , ConfOutput (..)
12 | , ConfScope (..)
13 | , ConfReport (..)
14 | , OrgStatConfig (..)
15 | ) where
16 |
17 | import Data.Aeson (FromJSON(..), Value(Object, String), withObject, withText, (.!=), (.:), (.:?))
18 | import Data.Aeson.Types (typeMismatch)
19 | import qualified Data.Text as T
20 | import Data.Time (LocalTime)
21 | import Data.Time.Format (defaultTimeLocale, parseTimeM)
22 | import Universum
23 |
24 | import OrgStat.Outputs.Types
25 | (BlockParams(..), ScriptParams(..), SummaryParams(..), TimelineParams(..))
26 | import OrgStat.Scope (AstPath(..), ScopeModifier(..))
27 | import OrgStat.Util (parseColour)
28 |
29 | -- | Exception type for everything bad that happens with config,
30 | -- starting from parsing to logic errors.
31 | data ConfigException
32 | = ConfigParseException Text
33 | | ConfigLogicException Text
34 | deriving (Show, Typeable)
35 |
36 | instance Exception ConfigException
37 |
38 | data ConfDate
39 | = ConfNow
40 | | ConfLocal !LocalTime
41 | deriving (Show)
42 |
43 | data ConfRange
44 | = ConfFromTo !ConfDate !ConfDate
45 | | ConfBlockDay !Integer
46 | | ConfBlockWeek !Integer
47 | | ConfBlockMonth !Integer
48 | deriving (Show)
49 |
50 | data ConfOutputType
51 | = TimelineOutput { toParams :: !TimelineParams
52 | , toReport :: !Text }
53 | | SummaryOutput !SummaryParams
54 | | ScriptOutput !ScriptParams
55 | | BlockOutput { boParams :: !BlockParams
56 | , boReport :: !Text }
57 | deriving (Show)
58 |
59 | data ConfScope = ConfScope
60 | { csName :: !Text -- default is "default"
61 | , csPaths :: !(NonEmpty FilePath)
62 | } deriving (Show)
63 |
64 | data ConfOutput = ConfOutput
65 | { coType :: !ConfOutputType
66 | , coName :: !Text
67 | } deriving (Show)
68 |
69 | data ConfReport = ConfReport
70 | { crName :: !Text
71 | , crScope :: !Text
72 | , crRange :: !ConfRange
73 | , crModifiers :: ![ScopeModifier]
74 | } deriving (Show)
75 |
76 | data OrgStatConfig = OrgStatConfig
77 | { confScopes :: ![ConfScope]
78 | , confReports :: ![ConfReport]
79 | , confOutputs :: ![ConfOutput]
80 | , confTimelineParams :: !TimelineParams
81 | , confTodoKeywords :: ![Text]
82 | , confOutputDir :: !FilePath -- default is "./orgstat"
83 | } deriving (Show)
84 |
85 | instance FromJSON AstPath where
86 | parseJSON = withText "AstPath" $ \s ->
87 | pure $ AstPath $ filter (not . T.null) $ T.splitOn "/" s
88 |
89 | instance FromJSON ScopeModifier where
90 | parseJSON = withObject "ScopeModifier" $ \o -> do
91 | o .: "type" >>= \case
92 | (String "prune") -> ModPruneSubtree <$> o .: "path" <*> o .:? "depth" .!= 0
93 | (String "select") -> ModSelectSubtree <$> o .: "path"
94 | (String "filterbytag") ->
95 | (ModFilterTags . (\x -> [x]) <$> o .: "tag") <|>
96 | (ModFilterTags <$> o .: "tags")
97 | other -> fail $ "Unsupported scope modifier type: " ++ show other
98 |
99 | instance FromJSON ConfDate where
100 | parseJSON (String "now") = pure $ ConfNow
101 | parseJSON (String s) =
102 | case parseTimeM True defaultTimeLocale "%Y-%m-%d %H:%M" (T.unpack s) of
103 | Nothing -> fail $
104 | "Couldn't read date " <> show s <>
105 | ". Correct format is 2016-01-01 23:59"
106 | Just ut -> pure $ ConfLocal ut
107 | parseJSON invalid = typeMismatch "ConfDate" invalid
108 |
109 | instance FromJSON ConfRange where
110 | parseJSON (String s) | any (`T.isPrefixOf` s) ["day", "week", "month"] = do
111 | let splitted = T.splitOn "-" $ if "-" `T.isInfixOf` s then s else s <> "-"
112 | [range, number] = splitted
113 | constructor :: (Monad m, MonadFail m) => Integer -> m ConfRange
114 | constructor i = case range of
115 | "day" -> pure $ ConfBlockDay i
116 | "week" -> pure $ ConfBlockWeek i
117 | "month" -> pure $ ConfBlockMonth i
118 | t -> fail $ "ConfRange@parseJSON can't parse " <> T.unpack t <>
119 | " should be [day|week|month]"
120 | numberParsed
121 | | number == "" = pure 0
122 | | otherwise = case readMaybe (T.unpack number) of
123 | Nothing -> fail $ "Couldn't parse number modifier of " <> T.unpack s
124 | Just x -> pure x
125 | when (length splitted /= 2) $
126 | fail $ "Couldn't parse range " <> T.unpack s <>
127 | ", splitted is " <> show splitted
128 | constructor =<< numberParsed
129 | parseJSON (Object v) = ConfFromTo <$> v .: "from" <*> v .: "to"
130 | parseJSON invalid = typeMismatch "ConfRange" invalid
131 |
132 | instance FromJSON TimelineParams where
133 | parseJSON = withObject "TimelineParams" $ \v -> do
134 | _tpColorSalt <- v .:? "colorSalt" .!= 0
135 | _tpLegend <- v .:? "legend" .!= True
136 | _tpTopDay <- v .:? "topDay" .!= 5
137 | _tpColumnWidth <- v .:? "colWidth" .!= 1.0
138 | _tpColumnHeight <- v .:? "colHeight" .!= 1.0
139 | _tpBackground <-
140 | (fromMaybe (error "Can't parse colour") . parseColour @Text . T.strip) <$>
141 | v .:? "background" .!= "#ffffff"
142 | pure TimelineParams{..}
143 |
144 | instance FromJSON ConfOutputType where
145 | parseJSON = withObject "ConfOutputType" $ \o ->
146 | o .: "type" >>= \case
147 | (String "timeline") -> do
148 | toReport <- o .: "report"
149 | toParams <- parseJSON (Object o)
150 | pure $ TimelineOutput {..}
151 | (String "summary") -> do
152 | soTemplate <- o .: "template"
153 | pure $ SummaryOutput $ SummaryParams soTemplate
154 | (String "script") -> do
155 | spScript <-
156 | fmap Left (o .: "scriptPath") <|>
157 | fmap Right (o .: "inline")
158 | spReports <- o .: "reports"
159 | spInterpreter <- o .:? "interpreter" .!= "sh"
160 | pure $ ScriptOutput $ ScriptParams spScript spReports spInterpreter
161 | (String "block") -> do
162 | boReport <- o .: "report"
163 | _bpMaxLength <- o .:? "maxLength" .!= 80
164 | _bpUnicode <- o .:? "unicode" .!= True
165 | let boParams = BlockParams{..}
166 | pure $ BlockOutput {..}
167 | other -> fail $ "Unsupported output type: " ++ show other
168 |
169 | instance FromJSON ConfOutput where
170 | parseJSON = withObject "ConfOutput" $ \o -> do
171 | coName <- o .: "name"
172 | coType <- parseJSON (Object o)
173 | pure $ ConfOutput{..}
174 |
175 | instance FromJSON ConfScope where
176 | parseJSON = withObject "ConfScope" $ \o ->
177 | ConfScope <$> o .:? "name" .!= "default"
178 | <*> o .: "paths"
179 |
180 | instance FromJSON ConfReport where
181 | parseJSON = withObject "ConfReport" $ \o ->
182 | ConfReport <$> o .: "name"
183 | <*> o .:? "scope" .!= "default"
184 | <*> o .: "range"
185 | <*> o .:? "modifiers" .!= []
186 |
187 | instance FromJSON OrgStatConfig where
188 | parseJSON = withObject "OrgStatConfig" $ \o ->
189 | OrgStatConfig <$> o .: "scopes"
190 | <*> o .: "reports"
191 | <*> o .: "outputs"
192 | -- timelineDefault is deprecated
193 | <*> ((o .: "timelineParams" <|> o .: "timelineDefault")
194 | <|> parseJSON (Object mempty))
195 | <*> o .:? "todoKeywords" .!= []
196 | <*> (o .:? "outputDir" <|> o .:? "output") .!= "./orgstat"
197 |
--------------------------------------------------------------------------------
/src/OrgStat/Outputs/Timeline.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE RankNTypes, ScopedTypeVariables, TemplateHaskell #-}
2 |
3 | -- | Timeline reporting output. Prouces a svg with columns.
4 |
5 | module OrgStat.Outputs.Timeline
6 | ( processTimeline
7 | ) where
8 |
9 | import Data.Colour.CIE (luminance)
10 | import Data.List (lookup, nub)
11 | import qualified Data.List as L
12 | import qualified Data.Text as T
13 | import Data.Time (Day, DiffTime, LocalTime(..), defaultTimeLocale, formatTime, timeOfDayToTime)
14 | import Diagrams.Backend.SVG (B)
15 | import qualified Diagrams.Prelude as D
16 | import qualified Prelude
17 | import Text.Printf (printf)
18 | import Universum
19 |
20 | import OrgStat.Ast (Clock(..), Org(..), orgClocks, traverseTree)
21 | import OrgStat.Outputs.Types
22 | (TimelineOutput(..), TimelineParams, tpBackground, tpColorSalt, tpColumnHeight, tpColumnWidth,
23 | tpLegend, tpTopDay)
24 | import OrgStat.Util (addLocalTime, hashColour)
25 |
26 |
27 |
28 | ----------------------------------------------------------------------------
29 | -- Processing clocks
30 | ----------------------------------------------------------------------------
31 |
32 | -- [(a, [b])] -> [(a, b)]
33 | allClocks :: [(Text, [(DiffTime, DiffTime)])] -> [(Text, (DiffTime, DiffTime))]
34 | allClocks tasks = do
35 | (label, clocks) <- tasks
36 | clock <- clocks
37 | pure (label, clock)
38 |
39 | -- separate list for each day
40 | selectDays :: [Day] -> [(Text, [Clock])] -> [[(Text, [(DiffTime, DiffTime)])]]
41 | selectDays days tasks =
42 | flip map days $ \day ->
43 | filter (not . null . snd) $
44 | map (second (selectDay day)) tasks
45 | where
46 | selectDay :: Day -> [Clock] -> [(DiffTime, DiffTime)]
47 | selectDay day clocks = do
48 | Clock (LocalTime dFrom tFrom) (LocalTime dTo tTo) <- clocks
49 | guard $ any (== day) [dFrom, dTo]
50 | let tFrom' = if dFrom == day then timeOfDayToTime tFrom else fromInteger 0
51 | let tTo' = if dTo == day then timeOfDayToTime tTo else fromInteger (24*60*60)
52 | pure (tFrom', tTo')
53 |
54 | -- total time for each task
55 | totalTimes :: [(Text, [(DiffTime, DiffTime)])] -> [(Text, DiffTime)]
56 | totalTimes tasks = map (second clocksSum) tasks
57 | where
58 | clocksSum :: [(DiffTime, DiffTime)] -> DiffTime
59 | clocksSum clocks = sum $ map (\(start, end) -> end - start) clocks
60 |
61 | -- list of leaves
62 | orgToList :: Org -> [(Text, [Clock])]
63 | orgToList = orgToList' ""
64 | where
65 | orgToList' :: Text -> Org -> [(Text, [Clock])]
66 | orgToList' _pr org =
67 | --let path = pr <> "/" <> _orgTitle org
68 | let path = _orgTitle org
69 | in (path, _orgClocks org) : concatMap (orgToList' path) (_orgSubtrees org)
70 |
71 |
72 | ----------------------------------------------------------------------------
73 | -- Drawing
74 | ----------------------------------------------------------------------------
75 |
76 |
77 | diffTimeSeconds :: DiffTime -> Integer
78 | diffTimeSeconds time = floor $ toRational time
79 |
80 | diffTimeMinutes :: DiffTime -> Integer
81 | diffTimeMinutes time = diffTimeSeconds time `div` 60
82 |
83 | -- diffTimeHours :: DiffTime -> Integer
84 | -- diffTimeHours time = diffTimeMinutes time `div` 60
85 |
86 |
87 | labelColour :: TimelineParams -> Text -> D.Colour Double
88 | labelColour params _label = hashColour (params ^. tpColorSalt) _label
89 |
90 | -- | Returns if the label is to be shown. Second param is font-related
91 | -- heuristic constant, third is length of interval.
92 | fitLabelHeight :: TimelineParams -> Double -> Double -> Bool
93 | fitLabelHeight params n h = h >= (params ^. tpColumnHeight) * n
94 |
95 | -- | Decides by , width of column
96 | -- and string, should it be truncated. And returns modified string.
97 | fitLabelWidth :: TimelineParams -> Double -> Text -> Text
98 | fitLabelWidth params n s =
99 | if T.length s <= toTake then s else T.take toTake s <> ".."
100 | where
101 | toTake = floor $ n * ((params ^. tpColumnWidth) ** 1.2)
102 |
103 | -- rectangle with origin in the top-left corner
104 | topLeftRect :: Double -> Double -> D.Diagram B
105 | topLeftRect w h =
106 | D.rect w h
107 | & D.moveOriginTo (D.p2 (-w/2, h/2))
108 |
109 | -- timeline for a single day
110 | timelineDay :: TimelineParams -> Day -> [(Text, (DiffTime, DiffTime))] -> D.Diagram B
111 | timelineDay params day clocks =
112 | mconcat
113 | [ timeticks
114 | , dateLabel
115 | , mconcat (map showClock clocks)
116 | , clocksBackground
117 | ]
118 | where
119 | width = 140 * (params ^. tpColumnWidth)
120 | ticksWidth = 20
121 | height = 700 * (params ^. tpColumnHeight)
122 |
123 | timeticks :: D.Diagram B
124 | timeticks =
125 | mconcat $
126 | flip map [(0::Int)..23] $ \hour ->
127 | mconcat
128 | [ D.alignedText 0.5 1 (show hour)
129 | & D.font "DejaVu Sans"
130 | & D.fontSize 8
131 | & D.moveTo (D.p2 (ticksWidth/2, -5))
132 | & D.fc (D.sRGB24 150 150 150)
133 | , D.strokeT (D.p2 (0,0) D.~~ (D.p2 (ticksWidth, 0)))
134 | & D.translateY (-0.5)
135 | & D.lwO 1
136 | & D.lc (D.sRGB24 200 200 200)
137 | ]
138 | & D.moveTo (D.p2 (0, negate $ fromInteger . round $ height * (fromIntegral hour / 24)))
139 | & D.moveOriginTo (D.p2 (ticksWidth, 0))
140 |
141 | dateLabel :: D.Diagram B
142 | dateLabel =
143 | mconcat
144 | [ D.strutY 20
145 | , D.alignedText 0.5 0 (formatTime defaultTimeLocale "%a, %d.%m.%Y" day)
146 | & D.font "DejaVu Sans"
147 | & D.fontSize 12
148 | & D.moveOriginTo (D.p2 (-width/2, 0))
149 | ]
150 |
151 | clocksBackground :: D.Diagram B
152 | clocksBackground =
153 | topLeftRect width height
154 | & D.lw D.none
155 | & D.fc (params ^. tpBackground)
156 |
157 | contrastFrom c = if luminance c < 0.14 then D.sRGB24 224 224 224 else D.black
158 |
159 | showClock :: (Text, (DiffTime, DiffTime)) -> D.Diagram B
160 | showClock (label, (start, end)) =
161 | let
162 | w = width
163 | h = (* height) $ fromInteger (diffTimeMinutes $ end - start) / (24*60)
164 | y = (* height) $ fromInteger (diffTimeMinutes start) / (24*60)
165 |
166 | bgboxColour = labelColour params label
167 | bgbox = topLeftRect w h
168 | & D.lw D.none
169 | & D.fc bgboxColour
170 | label' = D.alignedText 0 0.5 (T.unpack $ fitLabelWidth params 21 label)
171 | & D.font "DejaVu Sans"
172 | & D.fontSize 10
173 | & D.fc (contrastFrom bgboxColour)
174 | & D.moveTo (D.p2 (5, -h/2))
175 | box = mconcat $ bool [] [label'] (fitLabelHeight params 11 h) ++ [bgbox]
176 | in box & D.moveTo (D.p2 (0, -y))
177 |
178 | -- timelines for several days, with top lists
179 | timelineDays
180 | :: TimelineParams
181 | -> [Day]
182 | -> [[(Text, (DiffTime, DiffTime))]]
183 | -> [[(Text, DiffTime)]]
184 | -> D.Diagram B
185 | timelineDays params days clocks topLists =
186 | (D.strutY 10 D.===) $
187 | D.hcat $
188 | flip map (days `zip` (clocks `zip` topLists)) $ \(day, (dayClocks, topList)) ->
189 | D.vsep 5
190 | [ timelineDay params day dayClocks
191 | , taskList params topList True
192 | ]
193 |
194 | -- task list, with durations and colours
195 | taskList :: TimelineParams -> [(Text, DiffTime)] -> Bool -> D.Diagram B
196 | taskList params labels fit = D.vsep 5 $ map oneTask $ reverse $ sortOn snd labels
197 | where
198 | oneTask :: (Text, DiffTime) -> D.Diagram B
199 | oneTask (label, time) =
200 | D.hsep 3
201 | [ D.alignedText 1 0.5 (showTime time)
202 | & D.font "DejaVu Sans"
203 | & D.fontSize 10
204 | & D.translateX 20
205 | , D.rect 12 12
206 | & D.fc (labelColour params label)
207 | & D.lw D.none
208 | , D.alignedText 0 0.5 (T.unpack $ bool label (fitLabelWidth params 18 label) fit)
209 | & D.font "DejaVu Sans"
210 | & D.fontSize 10
211 | ]
212 |
213 | showTime :: DiffTime -> Prelude.String
214 | showTime time = printf "%d:%02d" hours minutes
215 | where
216 | (hours, minutes) = diffTimeMinutes time `divMod` 60
217 |
218 | emptyReport :: D.Diagram B
219 | emptyReport =
220 | mconcat
221 | [ D.strutY 20
222 | , D.strutX 40
223 | , D.alignedText 0.5 0 "empty"
224 | & D.font "DejaVu Sans"
225 | & D.fontSize 8
226 | ]
227 |
228 | timelineReport :: TimelineParams -> Org -> TimelineOutput
229 | timelineReport params org =
230 | if (null $ concat $ org ^.. traverseTree . orgClocks)
231 | then
232 | TimelineOutput $ D.vsep 30 [emptyReport]
233 |
234 | else TimelineOutput pic
235 | where
236 | lookupDef :: Eq a => b -> a -> [(a, b)] -> b
237 | lookupDef d a xs = fromMaybe d $ lookup a xs
238 |
239 | -- These two should be taken from the Org itself (min/max).
240 | (from,to) =
241 | let c = concat $ org ^.. traverseTree . orgClocks
242 | in (L.minimum (map cFrom c), L.maximum (map cTo c))
243 |
244 | -- period to show. Right border is -1min, we assume it's non-inclusive
245 | daysToShow = [localDay from ..
246 | localDay ((negate 120 :: Int) `addLocalTime` to)]
247 |
248 | -- unfiltered leaves
249 | tasks :: [(Text, [Clock])]
250 | tasks = orgToList org
251 |
252 | -- tasks from the given period, split by days
253 | byDay :: [[(Text, [(DiffTime, DiffTime)])]]
254 | byDay = selectDays daysToShow tasks
255 |
256 | -- total durations for each task, split by days
257 | byDayDurations :: [[(Text, DiffTime)]]
258 | byDayDurations = map totalTimes byDay
259 |
260 | -- total durations for the whole period
261 | allDaysDurations :: [(Text, DiffTime)]
262 | allDaysDurations =
263 | let allTasks = nub $ map fst $ concat byDayDurations in
264 | flip map allTasks $ \task ->
265 | (task,) $ sum $ flip map byDayDurations $ \durations ->
266 | lookupDef (fromInteger 0) task durations
267 |
268 | -- split clocks
269 | clocks :: [[(Text, (DiffTime, DiffTime))]]
270 | clocks = map allClocks byDay
271 |
272 | -- top list for each day
273 | topLists :: [[(Text, DiffTime)]]
274 | topLists =
275 | map (take (params ^. tpTopDay) . reverse . sortOn (\(_task, time) -> time))
276 | byDayDurations
277 |
278 | optLegend | params ^. tpLegend = [taskList params allDaysDurations False]
279 | | otherwise = []
280 |
281 | pic =
282 | D.vsep 30 $ [ timelineDays params daysToShow clocks topLists ] ++ optLegend
283 |
284 | processTimeline :: TimelineParams -> Org -> TimelineOutput
285 | processTimeline params org = timelineReport params org
286 |
--------------------------------------------------------------------------------
/src/arch/Main.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE ApplicativeDo, OverloadedStrings, ScopedTypeVariables #-}
2 |
3 | module Main where
4 |
5 | import Universum
6 |
7 | import qualified Data.Attoparsec.Text as A
8 | import qualified Data.HashMap.Strict as HM
9 | import qualified Data.List as L
10 | import qualified Data.OrgMode.Parse as O
11 | import Data.OrgMode.Types
12 | import qualified Data.OrgMode.Types as O
13 | import qualified Data.Text as T
14 | import qualified Data.Text.IO as TIO
15 | import Data.Time (LocalTime(..), TimeOfDay(..), fromGregorian)
16 | import Data.Time.Format (defaultTimeLocale, parseTimeM)
17 | import Data.Version (showVersion)
18 | import Options.Applicative.Simple
19 | (Parser, ReadM, help, long, maybeReader, metavar, option, simpleOptions, strOption, switch)
20 | import Paths_orgstat (version)
21 | import System.Directory (doesFileExist)
22 | import System.FilePath (takeBaseName, takeExtension)
23 | import System.FilePath ((>))
24 |
25 | import OrgStat.Logging
26 |
27 | ----------------------------------------------------------------------------
28 | -- Arguments/options
29 | ----------------------------------------------------------------------------
30 |
31 | data Args = Args
32 | { argsInputs :: ![String]
33 | , argsOutDir :: !String
34 | , argsTodoKeywords :: ![Text]
35 | , argsDoneKeywords :: ![Text]
36 | , argsDate :: !LocalTime
37 | , argsDebug :: !Bool
38 | } deriving Show
39 |
40 | argsParser :: Parser Args
41 | argsParser = do
42 | argsInputs <-
43 | some $
44 | strOption
45 | (long "input" <> metavar "FILEPATH" <>
46 | help "Files to consider for input")
47 | argsOutDir <- strOption (long "out-dir" <> metavar "FILENAME" <> help "Output directory")
48 | argsTodoKeywords <- option (maybeReader $ pure . map fromString . L.words)
49 | (long "todo-keywords" <> metavar "STRLIST" <> help "TODO keywords, space-separated list")
50 | argsDoneKeywords <- option (maybeReader $ pure . map fromString . L.words)
51 | (long "done-keywords" <> metavar "STRLIST" <> help "DONE keywords, space-separated list")
52 | argsDate <- option dateReadM (long "archive-from" <> metavar "DATE ")
53 | argsDebug <- switch (long "debug" <> help "Enable debug logging")
54 | pure Args{..}
55 | where
56 | dateReadM :: ReadM LocalTime
57 | dateReadM = maybeReader $ \s ->
58 | case parseTimeM True defaultTimeLocale "%Y-%m-%d" s of
59 | Nothing -> fail $
60 | "Couldn't read date " <> show s <>
61 | ". Correct format is YYYY-MM-DD"
62 | Just ut -> pure ut
63 |
64 |
65 | getOptions :: IO Args
66 | getOptions = do
67 | (res, ()) <-
68 | simpleOptions
69 | ("orgarch-" <> showVersion version)
70 | "----- OrgArch ------"
71 | "The tool for creating org-mode archives"
72 | argsParser
73 | empty
74 | pure res
75 |
76 |
77 | ----------------------------------------------------------------------------
78 | -- Parsing and processing
79 | ----------------------------------------------------------------------------
80 |
81 | data LogicException = LogicException Text
82 | deriving (Show, Typeable)
83 |
84 | instance Exception LogicException
85 |
86 |
87 | -- | Analogous to readOrgFile from OrgStat.IO, but with original
88 | -- orgmode-parse datatype.
89 | readOrgFile
90 | :: (MonadIO m, MonadCatch m)
91 | => [Text] -> FilePath -> m (Text, O.Document)
92 | readOrgFile todoKeywords fp = do
93 | logDebug $ "Reading org file " <> fpt
94 | unlessM (liftIO $ doesFileExist fp) $
95 | throwM $ LogicException $ "Org file " <> fpt <> " doesn't exist"
96 | (content, fname) <- case takeExtension fp of
97 | ".org" -> (,fp) <$> liftIO (TIO.readFile fp)
98 | _ -> throwM $ LogicException $
99 | "File " <> fpt <> " has unknown extension. Need to be .org"
100 | let filename = T.pack $ takeBaseName fname
101 | logDebug $ "Parsing org file " <> fpt
102 | parsed <-
103 | case A.parseOnly (O.parseDocument todoKeywords) content of
104 | Left err -> throwM $ LogicException $ T.pack err
105 | Right res -> pure res
106 |
107 | pure (filename, parsed)
108 | where
109 | fpt = T.pack fp
110 |
111 | -- Nothing for DateTime without time-of-day
112 | convertDateTime :: O.DateTime -> Maybe LocalTime
113 | convertDateTime
114 | O.DateTime
115 | { yearMonthDay = O.YearMonthDay year month day
116 | , hourMinute = Just (hour, minute)
117 | }
118 | = Just $ LocalTime
119 | (fromGregorian (toInteger year) month day)
120 | (TimeOfDay hour minute 0)
121 | convertDateTime _ = Nothing
122 |
123 |
124 | printDocument :: Document -> Text
125 | printDocument Document{..} =
126 | documentText <> "\n" <> T.intercalate "\n" (map printHeadline documentHeadlines)
127 | where
128 | prependSpace prefix s = if T.null s then "" else prefix <> s
129 |
130 | printStats (StatsPct i) = " [" <> show i <> "%]"
131 | printStats (StatsOf i j) = " [" <> show i <> "/" <> show j <> "]"
132 |
133 | printHeadline :: Headline -> Text
134 | printHeadline Headline{..} =
135 | let Depth d = depth in
136 | let prefix =
137 | fromString (take d (Universum.repeat '*')) <>
138 | maybe "" (\s -> " " <> unStateKeyword s) stateKeyword <>
139 | maybe "" (\p -> " [#" <> show p <> "]") priority <>
140 | maybe "" printStats stats <>
141 | (prependSpace " " title)
142 | in
143 | let tagList = if null tags then "" else ":" <> T.intercalate ":" tags <> ":" in
144 | let spaceLen = 77 - T.length prefix - T.length tagList in
145 | let header = prefix <>
146 | prependSpace (fromString (take spaceLen (Universum.repeat ' '))) tagList in
147 |
148 | let sec = printSection d section in
149 |
150 | let subHeadlinesStr = map printHeadline subHeadlines in
151 |
152 | header <> (prependSpace "\n" sec) <>
153 | (if all T.null subHeadlinesStr
154 | then "" else "\n" <> T.intercalate "\n" subHeadlinesStr)
155 |
156 | printSection :: Int -> Section -> Text
157 | printSection depth Section{..} =
158 | let indent = fromString (take (depth+1) (Universum.repeat ' ')) in
159 | let Plns plns = sectionPlannings in
160 | let planningsStr =
161 | T.intercalate " " $ map (\(k,v) -> show k <> ": " <> printTs v) $
162 | HM.toList plns in
163 | let clocksStr = map printClock sectionClocks in
164 | let withDrawer name xs = [":" <> name <> ":"] <> xs <> [":END:"] in
165 | let props = unProperties sectionProperties in
166 | let propsStr = if HM.null props
167 | then []
168 | else withDrawer "PROPERTIES" $
169 | map (\(k,v) -> ":" <> k <> ": " <> v) $ HM.toList props in
170 | let logbook = unLogbook sectionLogbook in
171 | let logbookStr = if logbook == [] then [] else
172 | withDrawer "LOGBOOK" $ map printClock logbook in
173 | let drawersStr =
174 | concatMap (\(Drawer name contents) -> withDrawer name [contents]) sectionDrawers in
175 |
176 | let maybeInclude s = if T.null s then [] else [s] in
177 | prependSpace indent $
178 | T.intercalate ("\n" <> indent)
179 | (concat [ maybeInclude planningsStr
180 | , clocksStr, propsStr
181 | , logbookStr, drawersStr])
182 | <> T.stripEnd sectionParagraph
183 |
184 | printClock :: Clock -> Text
185 | printClock (Clock (Just ts, Just (h,m))) =
186 | let withSpace s = if T.length s == 1 then " " <> s else s in
187 | let withZero s = if T.length s == 1 then "0" <> s else s in
188 | "CLOCK: " <> printTs ts <> " => " <> withSpace (show h) <> ":" <> withZero (show m)
189 | printClock (Clock (Just ts, Nothing)) = "CLOCK: " <> printTs ts
190 | printClock c = error $ "printClock: not yet implemented " <> show c
191 |
192 | printTs :: Timestamp -> Text
193 | printTs Timestamp{..} =
194 | bracketOnActive tsActive (dateTime tsTime) <>
195 | maybe "" (\end -> "--" <> bracketOnActive tsActive (dateTime end)) tsEndTime
196 | where
197 | maybePrepend a s = if s == "" then a else a <> " " <> s
198 | withZero s = if T.length s == 1 then "0" <> s else s
199 | dateTime DateTime{..} =
200 | (show (ymdYear yearMonthDay) <> "-" <>
201 | withZero (show (ymdMonth yearMonthDay)) <> "-" <>
202 | withZero (show (ymdDay yearMonthDay))) `maybePrepend`
203 | maybe "" id dayName `maybePrepend`
204 | maybe "" (\(h,m) -> withZero (show h) <> ":" <> withZero (show m)) hourMinute `maybePrepend`
205 | maybe "" printRepeater repeater `maybePrepend`
206 | maybe "" printDelay delay
207 |
208 | bracketOnActive active s = if active == Active then "<" <> s <> ">" else "[" <> s <> "]"
209 |
210 | printTimeUnit = \case
211 | UnitYear -> "y"
212 | UnitMonth -> "m"
213 | UnitWeek -> "w"
214 | UnitDay -> "d"
215 | UnitHour -> "h"
216 |
217 | printRepeater Repeater{..} =
218 | (case repeaterType of
219 | RepeatCumulate -> "++"
220 | RepeatCatchUp -> "+"
221 | RepeatRestart -> ".+") <>
222 | show repeaterValue <>
223 | printTimeUnit repeaterUnit
224 |
225 | printDelay Delay{..} =
226 | (case delayType of
227 | DelayAll -> "-"
228 | DelayFirst -> "--") <>
229 | show delayValue <>
230 | printTimeUnit delayUnit
231 |
232 | -- TODO: repeated common tasks?
233 | filterOrg :: [Text] -> LocalTime -> O.Document -> (O.Document, O.Document)
234 | filterOrg doneKeywords archDate Document{..} =
235 | let hlUpd = map go documentHeadlines in
236 | (Document { documentHeadlines = mapMaybe fst hlUpd, ..},
237 | Document { documentHeadlines = mapMaybe snd hlUpd, ..})
238 | where
239 | tsOlder :: Timestamp -> Bool
240 | tsOlder ts = case convertDateTime (tsTime ts) of
241 | Nothing -> False
242 | Just locTime -> locTime <= archDate
243 |
244 | go :: Headline -> (Maybe Headline,Maybe Headline)
245 | go hl@Headline{..} =
246 | let subHls = map go subHeadlines in
247 | -- Whether this headline was CLOSED before archive date
248 | let isDone = stateKeyword `elem` (map (Just . StateKeyword) doneKeywords) in
249 | let Plns plannings = sectionPlannings section in
250 | let isRepeating = case HM.lookup SCHEDULED plannings of
251 | Nothing -> False
252 | Just ts -> isJust (repeater (tsTime ts)) in
253 | let closedOld = case HM.lookup CLOSED plannings of
254 | Nothing -> True
255 | Just ts -> tsOlder ts in
256 |
257 | if isRepeating || stateKeyword == Nothing
258 | then
259 | let clocks =
260 | reverse $
261 | L.sortOn (maybe (error "Couldn't convert datetime to sort") id .
262 | convertDateTime . tsTime . fst) $
263 | map (\case Clock (Just x, y) -> (x,y)
264 | c -> error $ "Have encountered a broken clock: " <> show c) $
265 | L.nub $
266 | concat [ sectionClocks section
267 | , unLogbook (sectionLogbook section)
268 | ] in
269 | let (splitArch, splitRemain) = L.partition (tsOlder . fst) clocks in
270 |
271 | let toClock (a, b) = Clock (Just a, b) in
272 |
273 | let remainItem = all (isNothing . snd) subHls && splitArch == [] in
274 | let hlLeft =
275 | hl { section = section { sectionClocks = []
276 | , sectionLogbook = Logbook (map toClock splitRemain)}
277 | , subHeadlines = mapMaybe fst subHls } in
278 |
279 | let hlRight =
280 | hl { section = section { sectionClocks = []
281 | , sectionLogbook = Logbook (map toClock splitArch)}
282 | , subHeadlines = mapMaybe snd subHls } in
283 |
284 | (Just hlLeft,if remainItem then Nothing else Just hlRight)
285 | else (if isDone && closedOld then (Nothing, Just hl) else (Just hl, Nothing))
286 |
287 |
288 | main :: IO ()
289 | main = do
290 | args@Args{..} <- getOptions
291 | let sev = if argsDebug then Debug else Info
292 | initLogging sev
293 | logInfo $ show args
294 |
295 | orgFiles <- forM argsInputs $ readOrgFile $ argsTodoKeywords <> argsDoneKeywords
296 |
297 | logInfo $ show $ map fst orgFiles
298 |
299 | let filteredFiles = map (second $ filterOrg argsDoneKeywords argsDate) orgFiles
300 |
301 | forM_ filteredFiles $ \(fn,(remain,arch)) -> do
302 | TIO.writeFile (argsOutDir > (toString fn <> "_remain.org" )) $ printDocument remain
303 | TIO.writeFile (argsOutDir > (toString fn <> "_archive.org")) $ printDocument arch
304 |
305 | logInfo "Done"
306 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------