aboutsummaryrefslogtreecommitdiff
path: root/modules/pkgs/xinclude2nix/xinclude2nix.hs
blob: 49d34ca34aa055c2913f8e308099f970074b20d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
{-# LANGUAGE Arrows #-}

{-
 Takes a list of XML files
 Parses them for xi:xinclude elements
 Extract included files
 Prints list of included files
-}

module Main where

import Data.List (intercalate, isPrefixOf, stripPrefix)
import Data.Maybe (fromMaybe)
import System.Environment (getArgs)
import Text.XML.HXT.Core ( (>>>), deep, getAttrValue, hasAttr, hasName,
  isElem, readDocument, returnA, runX)

getXIncludes :: String -> IO [String]
getXIncludes xmlFileName = runX $ readDocument [] xmlFileName
  >>> deep (isElem >>> hasName "xi:include" >>> hasAttr "href") >>>
  proc d -> do
    href <- getAttrValue "href" -< d
    returnA -< href

getFiles :: [String] -> [String]
getFiles = map stripScheme . filter isFile
  where
    fileScheme = "file://"
    isFile s = "/" `isPrefixOf` s || (fileScheme `isPrefixOf` s)
    stripScheme u = fromMaybe u (stripPrefix fileScheme u)

unique :: [String] -> [String]
unique [] = []
unique (x:xs)
  | x `elem` xs = unique xs
  | otherwise = x:unique xs

toNix :: [String] -> String
toNix ss = "[" ++ intercalate " " (map show ss) ++ "]"

main :: IO ()
main = do
  paths <- getArgs
  includedFiles <- unique . getFiles . concat <$> mapM getXIncludes paths
  putStrLn $ toNix includedFiles