Skip to content

Commit 3dbe910

Browse files
committed
Migrate JSON to/from any supported format
1 parent b2c0ab8 commit 3dbe910

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

ast-migrator.cabal

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ library
6161
, Text.Pandoc.AST.V1_22.Down
6262
, AstMigrator
6363
build-depends: aeson >= 0.6.2 && < 1.6
64+
, bytestring >= 0.10.4 && < 0.11
6465
, containers >= 0.3
6566
, deepseq >= 1.4.1 && < 1.5
6667
, pandoc-types == 1.22.*

src/Text/Pandoc/AST/Migrator.hs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@ Portability : portable
1010
Migrate from or to older AST versions.
1111
-}
1212
module Text.Pandoc.AST.Migrator
13-
( migrateUpToV1_21
13+
( ASTVersion (..)
14+
, migrateJSON
15+
, migrateJSONWith
16+
-- * migration steps
17+
, migrateUpToV1_21
1418
, migrateUpToV1_22
1519
, migrateDownFromV1_21
1620
, migrateDownFromV1_22
@@ -20,3 +24,35 @@ import Text.Pandoc.AST.V1_20.Up (migrateUpToV1_21)
2024
import Text.Pandoc.AST.V1_21.Down (migrateDownFromV1_21)
2125
import Text.Pandoc.AST.V1_21.Up (migrateUpToV1_22)
2226
import Text.Pandoc.AST.V1_22.Down (migrateDownFromV1_22)
27+
28+
import Data.Aeson (FromJSON, ToJSON, eitherDecode, encode)
29+
import Data.ByteString.Lazy (ByteString)
30+
31+
data ASTVersion
32+
= V1_20 -- ^ Version 1.20
33+
| V1_21 -- ^ Version 1.21
34+
| V1_22 -- ^ Version 1.22
35+
deriving (Eq, Ord, Show)
36+
37+
migrateJSON :: ASTVersion -- ^ initial version
38+
-> ASTVersion -- ^ target version
39+
-> ByteString -- ^ input JSON
40+
-> ByteString -- ^ migrated JSON
41+
migrateJSON from to =
42+
case (from, to) of
43+
(V1_20, V1_20) -> id
44+
(V1_20, V1_21) -> migrateJSONWith migrateUpToV1_21
45+
(V1_20, V1_22) -> migrateJSONWith (migrateUpToV1_22 . migrateUpToV1_21)
46+
(V1_21, V1_21) -> id
47+
(V1_21, V1_22) -> migrateJSONWith (migrateUpToV1_22 . migrateUpToV1_21)
48+
(V1_22, V1_22) -> id
49+
(V1_22, V1_21) -> migrateJSONWith migrateDownFromV1_22
50+
(V1_22, V1_20) -> migrateJSONWith (migrateDownFromV1_21 . migrateDownFromV1_22)
51+
(V1_21, V1_20) -> migrateJSONWith migrateDownFromV1_21
52+
53+
migrateJSONWith :: (FromJSON a, ToJSON b)
54+
=> (a -> b) -- ^ Migration function
55+
-> ByteString -- ^ Input JSON
56+
-> ByteString -- ^ Migrated JSON
57+
migrateJSONWith migrator =
58+
encode . either error migrator . eitherDecode

0 commit comments

Comments
 (0)