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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- CLI frontend for running and submitting analyses to the Dragons.dev web
-- service.
--
-- : out dragons-analyze
module Biz.Dragons.Analysis
( Analysis (..),
Commit (..),
run,
main,
test,
git,
)
where
import Alpha
import qualified Control.Concurrent.Async as Async
import qualified Data.Aeson as Aeson
import Data.Data (Data)
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.String as String
import qualified Data.Text as Text
import qualified Data.Time.Clock as Time
import qualified Data.Time.Format as Time
import qualified Omni.Cli as Cli
import Omni.Test ((@=?))
import qualified Omni.Test as Test
import qualified System.Directory as Directory
import qualified System.Process as Process
main :: IO ()
main = Cli.main <| Cli.Plan help move test tidy
move :: Cli.Arguments -> IO ()
move args = gitDir +> run authors /> Aeson.encode +> putStrLn
where
gitDir =
Cli.longOption "git-dir"
|> Cli.getArgWithDefault args ""
|> Directory.makeAbsolute
authors =
-- i think this is not working? do i need optparse-applicative?
-- see: https://github.com/docopt/docopt.hs/issues/25
Cli.shortOption 'a'
|> Cli.getAllArgs args
|> map Text.pack
tidy :: cfg -> IO ()
tidy _ = pure ()
test :: Test.Tree
test = Test.group "Biz.Dragons.Analysis" [test_calculateScore]
help :: Cli.Docopt
help =
[Cli.docopt|
dragons-analyze
Usage:
dragons-analyze test
dragons-analyze [--author=<email>]...
Options:
--git-dir The git repo to analyze [default: ./.git]
-a, --author List of active authors' emails, may be specified
multiple times
|]
newtype Commit = Sha Text
deriving (Eq, Data, Typeable, Ord, Generic, Show)
instance Aeson.ToJSON Commit
instance Aeson.FromJSON Commit
-- | The result of analyzing a git repo.
data Analysis = Analysis
{ -- | Where the repo is stored on the local disk.
gitDir :: FilePath,
-- | A path with no active contributors
blackholes :: [Text],
-- | A path with < 3 active contributors
liabilities :: [Text],
-- | Map of path to number of commits, for detecting paths that continually
-- get rewritten.
hotspotMap :: Map FilePath Integer,
-- | Files that have not been touched in 6 months
stale :: Map FilePath Integer,
-- | Total score for the repo
score :: Integer,
-- | Total number of files
totalFiles :: Integer,
-- | The total number of commits
totalCommits :: Integer,
-- | List of all the active users we care about
activeAuthors :: [Text],
-- | Which commit this analysis was run against.
commit :: Commit
}
deriving (Eq, Ord, Generic, Show, Data, Typeable)
instance Aeson.ToJSON Analysis
instance Aeson.FromJSON Analysis
run :: [Text] -> FilePath -> IO Analysis
run activeAuthors bareRepo = do
commit <- git bareRepo ["rev-parse", "HEAD"] /> Text.pack /> chomp /> Sha
tree <-
git
bareRepo
[ "ls-tree",
"--full-tree",
"--name-only",
"-r", -- recurse into subtrees
"HEAD"
]
/> String.lines
authors <- traverse (authorsFor bareRepo) tree :: IO [[(Text, Text, Text)]]
let authorMap = zip tree authors :: [(FilePath, [(Text, Text, Text)])]
stalenessMap <- traverse (lastTouched bareRepo) tree
let blackholes =
[ Text.pack path
| (path, authors_) <- authorMap,
null (map third authors_ `List.intersect` activeAuthors)
]
let liabilities =
[ Text.pack path
| (path, authors_) <- authorMap,
length (map third authors_ `List.intersect` activeAuthors) < 3
]
let numBlackholes = realToFrac <| length blackholes
let numLiabilities = realToFrac <| length liabilities
let numTotal = realToFrac <| length tree
hotspotMap <-
Map.fromList </ Async.mapConcurrently getChangeCount tree
totalCommits <-
git bareRepo ["rev-list", "--count", "HEAD"]
/> filter (/= '\n')
/> readMaybe
/> fromMaybe 0
pure
<| Analysis
{ gitDir = bareRepo,
stale =
Map.fromList
<| [ (path, days)
| (path, Just days) <- stalenessMap,
days > 180
],
score = calculateScore numTotal numBlackholes numLiabilities,
totalFiles = toInteger <| length tree,
..
}
where
third :: (a, b, c) -> c
third (_, _, a) = a
getChangeCount :: FilePath -> IO (FilePath, Integer)
getChangeCount path =
git bareRepo ["rev-list", "--count", "HEAD", "--", path]
/> filter (/= '\n')
/> readMaybe
/> fromMaybe 0
/> (path,)
-- | Given a git dir and a path inside the git repo, get information about the
-- authors.
authorsFor ::
FilePath ->
FilePath ->
-- | returns (number of commits, author name, author email)
IO [(Text, Text, Text)]
authorsFor gitDir path =
Process.readProcess
"git"
[ "--git-dir",
gitDir,
"shortlog",
"--numbered",
"--summary",
"--email",
"HEAD",
"--",
path
]
""
/> Text.pack
/> Text.lines
/> map (Text.break (== '\t'))
/> map parseAuthor
where
parseAuthor (commits, author) =
( Text.strip commits,
Text.strip <| Text.takeWhile (/= '<') author,
Text.strip <| Text.dropAround (`elem` ['<', '>']) <| Text.dropWhile (/= '<') author
)
-- | Run a git command on a repo
git ::
-- | path to the git dir (bare repo)
String ->
-- | args to `git`
[String] ->
IO String
git bareRepo args = Process.readProcess "git" (["--git-dir", bareRepo] ++ args) ""
lastTouched :: FilePath -> FilePath -> IO (FilePath, Maybe Integer)
lastTouched bareRepo path = do
now <- Time.getCurrentTime
timestamp <-
Process.readProcess
"git"
[ "--git-dir",
bareRepo,
"log",
"-n1",
"--pretty=%aI",
"--",
path
]
""
/> filter (/= '\n')
/> Time.parseTimeM True Time.defaultTimeLocale "%Y-%m-%dT%H:%M:%S%z"
pure (path, calculateAge now </ timestamp)
where
calculateAge now n = round <| Time.diffUTCTime now n / Time.nominalDay
-- | Does the aggregate score calculation given number of files found to be
-- blackholes, liabilities, etc.
calculateScore :: Double -> Double -> Double -> Integer
calculateScore 0 _ _ = 0
calculateScore a 0 0 | a > 0 = 100
calculateScore a b c | a < 0 || b < 0 || c < 0 = 0
calculateScore numTotal numBlackholes numLiabilities =
max 0
<. round
<| maxScore
* (weightedBlackholes + weightedLiabilities + numGood)
/ numTotal
where
weightedBlackholes = numBlackholes * (5 / 10)
weightedLiabilities = numLiabilities * (7 / 10)
numGood = numTotal - numBlackholes - numLiabilities
maxScore = 100.0
test_calculateScore :: Test.Tree
test_calculateScore =
Test.group
"calculateScore"
[ Test.unit "perfect score" <| 100 @=? calculateScore 100 0 0,
Test.unit "all blackholes" <| 50 @=? calculateScore 100 100 0,
Test.unit "all liabilities" <| 70 @=? calculateScore 100 0 100,
Test.prop "never > 100" <| \t b l -> calculateScore t b l <= 100,
Test.prop "never < 0" <| \t b l -> calculateScore t b l >= 0
]
|