-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegen.hs
70 lines (65 loc) · 2.37 KB
/
codegen.hs
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
-- | A script to generate the data type
-- runhaskell codegen.hs | ormolu > src/System/Linux/Capabilities.hs
module Main (main) where
import Data.List
import Data.Maybe
-- | returns the list of caps with there comments
readCaps :: IO [String]
readCaps =
readFile "/usr/include/linux/capability.h"
>>= (pure . dropEnd . reverse . foldl' go []) . dropBegin . lines
where
-- The actual list starts after this line
dropBegin = drop 1 . dropWhile (not . isInfixOf "POSIX-draft defined capabilities.")
-- The list ends before this line
dropEnd = takeWhile (not . isInfixOf "CAP_LAST_CAP")
push s [] = [s]
push s (x : xs) = (x <> s <> "\n") : xs
go :: [String] -> String -> [String]
go acc s
-- Drop intermediary comment
| s == " ** Linux-specific capabilities" = acc
| "#define CAP_" `isPrefixOf` s = [""] <> push s acc
| otherwise = push s acc
-- | create data type constructor with documentation
render :: String -> String
render = unlines . haddockPrefix . reverse . foldl' go [] . reverse . lines
where
go :: [String] -> String -> [String]
go acc s
| "#define CAP_" `isPrefixOf` s = [" " <> ((!! 1) . words $ s)]
| otherwise = case makeHaddock s of
[] -> acc
x -> acc <> [commentPrefix <> x]
commentPrefix = " -- "
haddockPrefix (x : xs) = (" -- | " <> stripPrefix' commentPrefix x) : xs
haddockPrefix [] = []
stripPrefix' :: String -> String -> String
stripPrefix' prefix s = fromMaybe s (stripPrefix prefix s)
makeHaddock :: String -> String
makeHaddock s =
stripPrefix' " "
. stripPrefix' " ** "
. stripPrefix' " * "
. dropWhileEnd (`elem` (['*', '/', ' '] :: [Char]))
$ makeHaddockList s
makeHaddockList s
| "/* " `isPrefixOf` s = "- " <> drop 3 s
| ":" `isSuffixOf` s = s <> "\n" <> commentPrefix
| otherwise = s
p :: String -> IO ()
p = putStrLn
main :: IO ()
main = do
p "{-# LANGUAGE DerivingStrategies #-}"
p "-- |"
p "-- Copyright: (c) 2021 Red Hat"
p "-- SPDX-License-Identifier: Apache-2.0"
p "-- Maintainer: Tristan de Cacqueray <[email protected]>"
p "--"
p "module System.Linux.Capabilities (Capability (..)) where"
p ""
p "-- | Linux capabilities"
p "data Capability = "
readCaps >>= mapM_ p . intersperse " |" . fmap render
p " deriving stock (Bounded, Enum, Eq, Read, Show)"