packages feed

json-state (empty) → 0.1.0.0

raw patch · 10 files changed

+455/−0 lines, 10 filesdep +aesondep +aeson-prettydep +basesetup-changed

Dependencies added: aeson, aeson-pretty, base, bytestring, libgit, time-units

Files

+ AUTHORS view
@@ -0,0 +1,1 @@+fr33domlover <fr33domlover@riseup.net>
+ COPYING view
@@ -0,0 +1,121 @@+Creative Commons Legal Code++CC0 1.0 Universal++    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE+    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN+    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS+    INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES+    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS+    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM+    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED+    HEREUNDER.++Statement of Purpose++The laws of most jurisdictions throughout the world automatically confer+exclusive Copyright and Related Rights (defined below) upon the creator+and subsequent owner(s) (each and all, an "owner") of an original work of+authorship and/or a database (each, a "Work").++Certain owners wish to permanently relinquish those rights to a Work for+the purpose of contributing to a commons of creative, cultural and+scientific works ("Commons") that the public can reliably and without fear+of later claims of infringement build upon, modify, incorporate in other+works, reuse and redistribute as freely as possible in any form whatsoever+and for any purposes, including without limitation commercial purposes.+These owners may contribute to the Commons to promote the ideal of a free+culture and the further production of creative, cultural and scientific+works, or to gain reputation or greater distribution for their Work in+part through the use and efforts of others.++For these and/or other purposes and motivations, and without any+expectation of additional consideration or compensation, the person+associating CC0 with a Work (the "Affirmer"), to the extent that he or she+is an owner of Copyright and Related Rights in the Work, voluntarily+elects to apply CC0 to the Work and publicly distribute the Work under its+terms, with knowledge of his or her Copyright and Related Rights in the+Work and the meaning and intended legal effect of CC0 on those rights.++1. Copyright and Related Rights. A Work made available under CC0 may be+protected by copyright and related or neighboring rights ("Copyright and+Related Rights"). Copyright and Related Rights include, but are not+limited to, the following:++  i. the right to reproduce, adapt, distribute, perform, display,+     communicate, and translate a Work;+ ii. moral rights retained by the original author(s) and/or performer(s);+iii. publicity and privacy rights pertaining to a person's image or+     likeness depicted in a Work;+ iv. rights protecting against unfair competition in regards to a Work,+     subject to the limitations in paragraph 4(a), below;+  v. rights protecting the extraction, dissemination, use and reuse of data+     in a Work;+ vi. database rights (such as those arising under Directive 96/9/EC of the+     European Parliament and of the Council of 11 March 1996 on the legal+     protection of databases, and under any national implementation+     thereof, including any amended or successor version of such+     directive); and+vii. other similar, equivalent or corresponding rights throughout the+     world based on applicable law or treaty, and any national+     implementations thereof.++2. Waiver. To the greatest extent permitted by, but not in contravention+of, applicable law, Affirmer hereby overtly, fully, permanently,+irrevocably and unconditionally waives, abandons, and surrenders all of+Affirmer's Copyright and Related Rights and associated claims and causes+of action, whether now known or unknown (including existing as well as+future claims and causes of action), in the Work (i) in all territories+worldwide, (ii) for the maximum duration provided by applicable law or+treaty (including future time extensions), (iii) in any current or future+medium and for any number of copies, and (iv) for any purpose whatsoever,+including without limitation commercial, advertising or promotional+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each+member of the public at large and to the detriment of Affirmer's heirs and+successors, fully intending that such Waiver shall not be subject to+revocation, rescission, cancellation, termination, or any other legal or+equitable action to disrupt the quiet enjoyment of the Work by the public+as contemplated by Affirmer's express Statement of Purpose.++3. Public License Fallback. Should any part of the Waiver for any reason+be judged legally invalid or ineffective under applicable law, then the+Waiver shall be preserved to the maximum extent permitted taking into+account Affirmer's express Statement of Purpose. In addition, to the+extent the Waiver is so judged Affirmer hereby grants to each affected+person a royalty-free, non transferable, non sublicensable, non exclusive,+irrevocable and unconditional license to exercise Affirmer's Copyright and+Related Rights in the Work (i) in all territories worldwide, (ii) for the+maximum duration provided by applicable law or treaty (including future+time extensions), (iii) in any current or future medium and for any number+of copies, and (iv) for any purpose whatsoever, including without+limitation commercial, advertising or promotional purposes (the+"License"). The License shall be deemed effective as of the date CC0 was+applied by Affirmer to the Work. Should any part of the License for any+reason be judged legally invalid or ineffective under applicable law, such+partial invalidity or ineffectiveness shall not invalidate the remainder+of the License, and in such case Affirmer hereby affirms that he or she+will not (i) exercise any of his or her remaining Copyright and Related+Rights in the Work or (ii) assert any associated claims and causes of+action with respect to the Work, in either case contrary to Affirmer's+express Statement of Purpose.++4. Limitations and Disclaimers.++ a. No trademark or patent rights held by Affirmer are waived, abandoned,+    surrendered, licensed or otherwise affected by this document.+ b. Affirmer offers the Work as-is and makes no representations or+    warranties of any kind concerning the Work, express, implied,+    statutory or otherwise, including without limitation warranties of+    title, merchantability, fitness for a particular purpose, non+    infringement, or the absence of latent or other defects, accuracy, or+    the present or absence of errors, whether or not discoverable, all to+    the greatest extent permissible under applicable law.+ c. Affirmer disclaims responsibility for clearing rights of other persons+    that may apply to the Work or any use thereof, including without+    limitation any person's Copyright and Related Rights in the Work.+    Further, Affirmer disclaims responsibility for obtaining any necessary+    consents, permissions or other rights required for any use of the+    Work.+ d. Affirmer understands and acknowledges that Creative Commons is not a+    party to this document and has no duty or obligation with respect to+    this CC0 or use of the Work.
+ ChangeLog view
@@ -0,0 +1,17 @@+The changes are recorded by the version control system, Darcs. To see a log+quickly from the terminal, run:++  $ darcs changes --repo http://dev.rel4tion.org/fr33domlover/json-state++There is also a web interface at <http://dev.rel4tion.org> which, among other+things, can display the history log.++To see the log in a local clone, first get a copy of the repository if you+haven't yet:++  $ darcs get http://dev.rel4tion.org/fr33domlover/json-state++Then move into the newly created directory and run darcs:++  $ cd json-state+  $ darcs changes
+ INSTALL view
@@ -0,0 +1,13 @@+Install from Hackage:++    $ cabal install json-state++Install from unpacked release tarball or source repo:++    $ cd json-state+    $ cabal install++Just play with it without installing:++    $ cabal build+    $ cabal repl
+ NEWS view
@@ -0,0 +1,23 @@+This file lists the user-visible interesting changes between releases. For a+full list of changes to the source, see the ChangeLog.++++json-state 0.1.0.0 -- (2015-09-17)+==================================++General, build and documentation changes:++* (This is the first release, so everything is new)++New APIs, features and enhancements:++* (This is the first release, so everything is a new feature)++Bug fixes:++* (This is just the first release, many bugs haven't been discovered yet)++Dependency changes:++* (This is the first release)
+ README.md view
@@ -0,0 +1,14 @@+See the .cabal file for more info and link to project website the version+control.++The official download location is Hackage:++<http://hackage.haskell.org/package/json-state>++This library is free software, and is committed to software freedom. It is+released to the public domain using the CC0 Public Domain Dedication. For the+boring "legal" details see the file 'COPYING'.++See the file 'INSTALL' for hints on installation. The file 'ChangeLog' explains+how to see the history log of the changes done in the code. 'NEWS' provides a+friendly overview of the changes for each release.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ json-state.cabal view
@@ -0,0 +1,37 @@+name:                json-state+version:             0.1.0.0+synopsis:            Keep program state in JSON files.+description:+  If your program manages simple state data not shared with other programs,+  this package provide a lightweight alternative to full ACID databases. It+  allows you to load state from JSON files and update those files+  asynchronously and periodically. Version control (using Git) is supported.+homepage:            http://rel4tion.org/projects/json-state/+bug-reports:         http://rel4tion.org/projects/json-state/tickets/+license:             PublicDomain+license-file:        COPYING+author:              fr33domlover+maintainer:          fr33domlover@riseup.net+copyright:           ♡ Copying is an act of love. Please copy, reuse and share.+category:            Data, Database+build-type:          Simple+extra-source-files:  AUTHORS ChangeLog COPYING INSTALL NEWS README.md+cabal-version:       >=1.10++source-repository head+  type:                darcs+  location:            http://dev.rel4tion.org/fr33domlover/json-state++library+  exposed-modules:     Data.JsonState+  other-modules:       Control.Debounce+  -- other-extensions:    +  build-depends:       aeson+                     , aeson-pretty   >=0.7+                     , base           >=4.7 && <5+                     , bytestring+                     , libgit         >=0.3.1+                     , time-units     >=1+  hs-source-dirs:      src+  default-language:    Haskell2010+  ghc-options:         -Wall
+ src/Control/Debounce.hs view
@@ -0,0 +1,61 @@+{- This file is part of json-state.+ -+ - Written in 2015 by fr33domlover <fr33domlover@rel4tion.org>.+ -+ - ♡ Copying is an act of love. Please copy, reuse and share.+ -+ - The author(s) have dedicated all copyright and related and neighboring+ - rights to this software to the public domain worldwide. This software is+ - distributed without any warranty.+ -+ - You should have received a copy of the CC0 Public Domain Dedication along+ - with this software. If not, see+ - <http://creativecommons.org/publicdomain/zero/1.0/>.+ -}++-- | This is similar to the same module from "auto-update" package, except here+-- the caller can pass a parameter to the debounced action. Also, the returned+-- action comes in 2 versions.+--+-- The first is non-blocking at the cost of a small chance a parameter isn't+-- passed and is instead discarded. This can happen if the action is called+-- from different threads simultanously. One empties the 'MVar', and the other+-- happens to fill it first, and then the parameter the former thread passed is+-- discarded. If you run the action from a single thread, there is no problem,+-- or if missing at a hopefully small chance isn't a problem.+--+-- The second is blocking, but only in the small chance described above.+-- Otherwise it doesn't block in practice.+--+-- Also, exceptions aren't handled. This includes async exceptions and any+-- exceptions thrown by the given action.+module Control.Debounce+    ( mkDebounce+    )+where++import Control.Monad (forever, void)+import Control.Concurrent (forkIO, threadDelay)+import Control.Concurrent.MVar+import Data.Time.Units++mkDebounce :: TimeUnit t+           => t               -- ^ Time delay between calls to the action+           -> (a -> IO ())    -- ^ Action to perform+           -> IO ( a -> IO () --   Never-blocking version+                 , a -> IO () --   Possibly-blocking version+                 )+mkDebounce interval action = do+    paramVar <- newEmptyMVar+    let run = void $ forkIO $ forever $ do+            param <- takeMVar paramVar+            action param+            threadDelay $ fromInteger $ toMicroseconds interval+        actNB param = do+            void $ tryTakeMVar paramVar+            void $ tryPutMVar paramVar param+        actPB param = do+            void $ tryTakeMVar paramVar+            putMVar paramVar param+    run+    return (actNB, actPB)
+ src/Data/JsonState.hs view
@@ -0,0 +1,166 @@+{- This file is part of json-state.+ -+ - Written in 2015 by fr33domlover <fr33domlover@rel4tion.org>.+ -+ - ♡ Copying is an act of love. Please copy, reuse and share.+ -+ - The author(s) have dedicated all copyright and related and neighboring+ - rights to this software to the public domain worldwide. This software is+ - distributed without any warranty.+ -+ - You should have received a copy of the CC0 Public Domain Dedication along+ - with this software. If not, see+ - <http://creativecommons.org/publicdomain/zero/1.0/>.+ -}++-- | This module provides a function for loading a state value from a JSON+-- file, and a function which generates a safe scalable saver function. The+-- JSON files are written using the @aeson-pretty@ package, so that they are+-- easy to read and modify manually if needed.+--+-- The save function generator, @mkSaveState@, returns a function which+-- saves settings when called, but only at most once in @t@, the time interval+-- passed to the generator. For example, if you pass an interval of 3 seconds,+-- you can safely call the generated save function even 100 times a second, and+-- the JSON file will still get updated just once in 3 seconds, avoiding an+-- overload of file I/O.+--+-- The actual saving happens in a dedicated worker thread, so even when a save+-- does occur, it won't block the caller thread. The generator can be called+-- once at program start, and the returned save function saved in application+-- state.+--+-- 'mkSaveStateVC' works similarly, but additionally provides a saver function+-- which commits the change into a git repo.+--+-- Note that while this simple periodic save-to-file method can serve a simple+-- standalone application well, it won't work if you wish your data to be+-- shared by multiple applications and allow them to read and write it at the+-- same time. If that's the case, check out the @acid-state@ package, and other+-- persistence related packages.+module Data.JsonState+    ( loadState+    , mkSaveState+    , mkSaveStateVC+    , mkSaveStateChoose+    , stateFilePath+    )+where++import Control.Debounce (mkDebounce)+import Control.Monad (liftM, when)+import Data.Aeson (FromJSON, ToJSON, eitherDecode)+import Data.Aeson.Encode.Pretty (encodePretty)+import Data.Time.Units (TimeUnit)+import Lib.Git+import System.IO.Error (tryIOError)++import qualified Data.ByteString.Lazy as B++-- | Try to load state from a file.+--+-- If an error occurs, 'Left' a pair is returned. The boolean indicates whether+-- reading the file failed ('False') or parsing the content failed ('True').+-- The string is an error description.+--+-- If the operation succeeds, 'Right' the loaded state data is returned.+loadState :: FromJSON s+          => FilePath -- ^ File to load+          -> IO (Either (Bool, String) s)+loadState file = do+    errOrStr <- tryIOError (B.readFile file)+    let pairOrStr = either (Left . (,) False . show) Right errOrStr+    return $ pairOrStr >>= either (Left . (,) True) Right . eitherDecode++saveAction :: ToJSON s => FilePath -> s -> IO ()+saveAction file s = B.writeFile file $ encodePretty s++-- | Prepare a save action which writes state into a JSON file. This action+-- defers the work to a separate dedicated thread, and ensures the file isn't+-- saved more than once within the given time interval.+--+-- The action is non-blocking but there is a chance a save is missed if saves+-- are triggered simultaneously from different threads.+--+-- You can call the returned action from your UI thread as a reaction to a+-- state change, without worrying about delay or IO load.+mkSaveState :: (TimeUnit t, ToJSON s)+            => t        -- ^ Minimal time interval between saves+            -> FilePath -- ^ File to save+            -> IO (s -> IO ())+mkSaveState interval file =+    liftM fst $ mkDebounce interval (saveAction file)++saveActionVC :: ToJSON s => FilePath -> Config -> String -> (s, Bool) -> IO ()+saveActionVC file cfg msg (s, git) = do+    saveAction (configCwd cfg ++ '/' : file) s+    when git $ runGit cfg $ do+        add [file]+        commit [] "json-state" "json@state" msg []++-- | Like 'mkSaveState', but also takes a repository path. Creates a Git+-- repository there if there isn't yet. Two save actions are returned. The+-- first one simply saves state to a file, just like in 'mkSaveState'. The+-- second one saves to file and then commits it into the Git repository.+--+-- Note that the file path is relative to the repo path. For example, if you+-- have the repo in \"/home/joe/repo\" and the file is \"/home/joe/repo/file\",+-- pass just \"file\" as the file path.+mkSaveStateVC :: (TimeUnit t, ToJSON s)+              => t        -- ^ Minimal time interval between saves+              -> FilePath -- ^ File to save, path relative to repo path+              -> FilePath -- ^ Path of the Git repository+              -> String   -- ^ Commit message to use in automatic commits+              -> IO ( s -> IO ()+                    , s -> IO ()+                    )+mkSaveStateVC interval file repo msg = do+    let cfg = makeConfig repo Nothing+    runGit cfg $ initDB False+    action <- liftM fst $ mkDebounce interval (saveActionVC file cfg msg)+    let withgit s = action (s, True)+        nogit s = action (s, False)+    return (nogit, withgit)++-- | This is a variant which returns a single save action, which either uses or+-- doesn't use a Git repo. If the repo path (3rd argument) is 'Nothing', then+-- Git isn't used at all and the file path is treated like 'mkSaveState' would.+-- Otherwise, i.e. if a repo path is specified, the returned action will commit+-- changes to the Git repo, and the repo and file path arguments are treated+-- like 'mkSaveStateVC' would, i.e. the file path is relative to the repo.+--+-- If you use this function, also use 'stateFilePath' to determine the correct+-- path to pass to 'loadState'.+mkSaveStateChoose :: (TimeUnit t, ToJSON s)+                  => t+                  -- ^ Minimal time interval between saves+                  -> FilePath+                  -- ^ File to save. If the repo path (next argument) is+                  -- 'Nothing', no Git repo is used, and this path is relative+                  -- to the process working dir, or absolute. If a repo path is+                  -- specified, this path is relative to repo path, and the+                  -- returned action also commits the file to the Git repo.+                  -> Maybe FilePath+                  -- ^ Optional path of the Git repository. If you pass+                  -- 'Nothing', a Git repo won't be used. If you pass 'Just' a+                  -- repo path, the save action will commit the change.+                  -> String+                  -- ^ Commit message to use in automatic commits+                  -> IO (s -> IO ())+mkSaveStateChoose interval file (Just repo) msg  =+    liftM snd $ mkSaveStateVC interval file repo msg+mkSaveStateChoose interval file Nothing     _msg =+    mkSaveState interval file++-- | If you use 'mkSaveStateChoose' to save the state, that function combines+-- the repo path and the file path when needed, to determine the full path of+-- the state file. But then, how do you determine which path to pass to+-- 'loadState'? This is exactly what this function does. Pass it the optional+-- repo path and the file path you passed to 'mkSaveStateChoose', and you'll+-- get a full path you can pass to 'loadState'.+stateFilePath :: FilePath -> Maybe FilePath -> FilePath+stateFilePath file (Just dir@(_:_)) =+    if last dir == '/'+        then dir ++ file+        else dir ++ '/' : file+stateFilePath file _                = file