summaryrefslogtreecommitdiff
path: root/Biz/Devalloc.hs
blob: ec8f870cfb4b5c1dfe4f8dd93e5b401fe56881e3 (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
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

-- Developer allocation
--
-- : out devalloc
-- : dep clay
-- dep cmark
-- sys cmark
-- : dep envy
-- : dep github
-- : dep lucid
-- : dep protolude
-- : dep req
-- : dep servant
-- : dep servant-lucid
-- : dep servant-server
-- : dep uuid
-- : dep vector
-- : dep warp
module Biz.Devalloc
  ( main,
    test,
  )
where

import Alpha hiding ((<.>))
import Biz.App (CSS (..), HtmlApp (..))
import qualified Biz.Look
import qualified Clay
import qualified Control.Exception as Exception
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as LBS
import qualified Data.List as List
import qualified Data.String as String
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Encoding
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import qualified GitHub
import qualified Lucid
import qualified Lucid.Base as Lucid
import qualified Lucid.Servant as Lucid
import Network.HTTP.Req ((/:), (=:))
import qualified Network.HTTP.Req as Req
import qualified Network.Wai as Wai
import qualified Network.Wai.Handler.Warp as Warp
import Network.Wai.Middleware.RequestLogger (logStdout)
import Servant
import Servant.HTML.Lucid
import qualified System.Directory as Directory
import qualified System.Envy as Envy
import System.FilePath ((<.>), (</>))
import qualified System.Process as Process
import qualified Web.FormUrlEncoded

main :: IO ()
main = Exception.bracket startup shutdown run
  where
    startup = do
      cfg <- Envy.decodeWithDefaults Envy.defConfig
      oAuthArgs <- Envy.decodeWithDefaults Envy.defConfig
      putText "@"
      putText "devalloc"
      putText <| "port: " <> (show <| port cfg)
      putText <| "depo: " <> (Text.pack <| depo cfg)
      return (cfg, serve (Proxy @AllPaths) <| paths cfg oAuthArgs)
    shutdown :: (Config, Application) -> IO ()
    shutdown _ = pure ()
    run :: (Config, Wai.Application) -> IO ()
    run (cfg, app) = Warp.run (port cfg) (logStdout app)

test :: IO ()
test = test_analyzeGitHub >> pure ()

data Config = Config
  { port :: Warp.Port,
    -- | The repo depo! Depository of repositories!
    depo :: FilePath
  }
  deriving (Generic, Show)

instance Envy.DefConfig Config where
  defConfig =
    Config
      { port = 8005,
        depo = "_/var/devalloc/depo"
      }

instance Envy.FromEnv Config

-- | These are arguments that a 3rd-party OAuth provider needs in order for us
-- to authenticate a user.
data OAuthArgs = OAuthArgs
  { githubClientSecret :: Text,
    githubClientId :: Text,
    githubState :: Text
  }
  deriving (Generic, Show)

instance Envy.DefConfig OAuthArgs where
  defConfig =
    OAuthArgs
      { githubClientSecret = mempty,
        githubClientId = mempty,
        githubState = mempty
      }

instance Envy.FromEnv OAuthArgs

-- | Wraps pages in default HTML
instance Lucid.ToHtml a => Lucid.ToHtml (HtmlApp a) where
  toHtmlRaw = Lucid.toHtml
  toHtml (HtmlApp x) =
    Lucid.doctypehtml_ <| do
      Lucid.head_ <| do
        Lucid.meta_ [Lucid.charset_ "utf-8"]
        jsRef "//unpkg.com/turbolinks@5.2.0/dist/turbolinks.js"
        cssRef "/css/main.css"
      Lucid.body_ (Lucid.toHtml x)
    where
      jsRef _href =
        Lucid.with
          (Lucid.script_ mempty)
          [ Lucid.makeAttribute "src" _href,
            Lucid.makeAttribute "async" mempty,
            Lucid.makeAttribute "defer" mempty
          ]
      cssRef _href =
        Lucid.with
          (Lucid.link_ mempty)
          [ Lucid.rel_ "stylesheet",
            Lucid.type_ "text/css",
            Lucid.href_ _href
          ]

-- * paths and pages

type AllPaths =
  Get '[HTML] (HtmlApp Home)
    :<|> "auth" :> "github" :> "callback"
      :> QueryParam "code" Text
      :> Get '[HTML] (HtmlApp SelectRepo)
    :<|> GitHubAnalysis
    :<|> "css" :> "main.css" :> Get '[CSS] Text

allPaths :: Proxy AllPaths
allPaths = Proxy :: Proxy AllPaths

type GitHubAnalysis =
  "analysis" :> "github"
    :> Capture "user" Text
    :> Capture "repo" Text
    :> Get '[HTML] (HtmlApp Analysis)

paths :: Config -> OAuthArgs -> Server AllPaths
paths cfg oAuthArgs =
  page (Home oAuthArgs)
    :<|> auth oAuthArgs
    :<|> (\user repo -> liftIO <| analyzeGitHub cfg user repo >>= pure . HtmlApp)
    :<|> look
  where
    page = pure . HtmlApp
    look =
      return . toStrict . Clay.render <| do
        Biz.Look.fuckingStyle
        "body" Clay.? Biz.Look.fontStack

-- | Create an href attribute to a path in 'AllPaths'.
linkTo ::
  (HasLink path, IsElem path AllPaths) =>
  -- | Proxy to the path
  Proxy path ->
  -- | Return value @x@ is to be used like @Lucid.a_ [ x ] ...@
  MkLink path Lucid.Attribute
linkTo = Lucid.safeHref_ "/" allPaths

newtype Home = Home OAuthArgs

instance Lucid.ToHtml Home where
  toHtmlRaw = Lucid.toHtml
  toHtml (Home oAuthArgs) =
    Lucid.toHtml <| pitch oAuthArgs

data OAuthResponse = OAuthResponse
  { access_token :: Text,
    scope :: Text,
    token_type :: Text
  }
  deriving (Generic, Aeson.FromJSON)

newtype SelectRepo = SelectRepo (Vector GitHub.Repo)

instance Lucid.ToHtml SelectRepo where
  toHtmlRaw = Lucid.toHtml
  toHtml (SelectRepo repos) =
    Lucid.toHtml <| do
      Lucid.h1_ "Select a repo to analyze"
      selectRepo repos

auth :: OAuthArgs -> Maybe Text -> Handler (HtmlApp SelectRepo)
auth _ Nothing = panic "no code from github api"
auth OAuthArgs {..} (Just code) =
  liftIO <| getAccessToken
    >>= getRepos
    >>= \case
      Left err -> panic <| show err
      Right repos -> pure . HtmlApp <| SelectRepo repos
  where
    getRepos oAuthToken =
      GitHub.github
        (GitHub.OAuth <| Encoding.encodeUtf8 oAuthToken)
        (GitHub.currentUserReposR GitHub.RepoPublicityAll GitHub.FetchAll)
    getAccessToken =
      accessTokenRequest
        >>= Req.responseBody
        /> access_token
        /> return
        |> Req.runReq Req.defaultHttpConfig
    accessTokenRequest =
      Req.req
        Req.POST
        (Req.https "github.com" /: "login" /: "oauth" /: "access_token")
        Req.NoReqBody
        Req.jsonResponse
        <| "client_id" =: githubClientId
        <> "client_secret" =: githubClientSecret
        <> "code" =: code
        <> "state" =: githubState

data Analysis = Analysis
  { bareRepo :: FilePath,
    -- | A path with no active contributors
    blackholes :: [Text],
    -- | A path with < 3 active contributors
    liabilities :: [Text],
    -- | Files that have not been touched in 6 months
    stale :: [Text],
    -- | Total score for the repo
    score :: Int
  }

instance Lucid.ToHtml Analysis where
  toHtmlRaw = Lucid.toHtml
  toHtml = Lucid.toHtml . render
    where
      render :: Analysis -> Lucid.Html ()
      render Analysis {..} =
        Lucid.div_ <| do
          Lucid.h1_ "Analysis Results"
          Lucid.h3_ "blackholes:"
          Lucid.ul_ <| do
            mapM_ (Lucid.li_ . Lucid.toHtml) blackholes

-- | Takes a list of active authors and a path to a bare git repo and runs a
-- regular analysis
analyze :: [Text] -> FilePath -> IO Analysis
analyze activeAuthors bareRepo = do
  tree <-
    Process.readProcess
      "git"
      [ "--git-dir",
        bareRepo,
        "ls-tree",
        "--full-tree",
        "--name-only",
        "-r", -- recurse into subtrees
        "HEAD"
      ]
      ""
      /> String.lines
  authors <- mapM (authorsFor bareRepo) tree :: IO [[(Text, Text, Text)]]
  let authorMap =
        zipWith
          ( \path authors_ ->
              (path, authors_)
          )
          tree
          authors ::
          [(FilePath, [(Text, Text, Text)])]

  return
    Analysis
      { blackholes =
          [ Text.pack path
            | (path, authors_) <- authorMap,
              length (List.intersect (map third authors_) activeAuthors) < 1
          ],
        liabilities = [],
        stale = [], -- actually a map of path->staleness
        score = 10,
        ..
      }

third :: (a, b, c) -> c
third (_, _, a) = a

-- | Given a git dir and a path inside the git repo, return a list of tuples
-- with number of commits and author.
authorsFor ::
  FilePath ->
  FilePath ->
  -- | Returns (number of commits, author name, author email)
  IO [(Text, Text, Text)]
authorsFor gitDir path = do
  -- git shortlog writes to stderr for some reason, so we can't just use
  -- Process.readProcess
  Process.readProcess
    "git"
    [ "--git-dir",
      gitDir,
      "shortlog",
      "--numbered",
      "--summary",
      "--email",
      "HEAD",
      "--",
      path
    ]
    ""
    /> Text.pack
    /> Text.lines
    /> map (Text.break (== '\t'))
    /> map
      ( \(commits, author) ->
          ( Text.strip commits,
            Text.strip <| Text.takeWhile (/= '<') author,
            Text.strip <| Text.dropAround (`elem` ['<', '>']) <| Text.dropWhile (/= '<') author
          )
      )

-- | Clones a repo from GitHub and does the analysis.
analyzeGitHub ::
  Config ->
  -- | GitHub owner
  Text ->
  -- | GitHub repo
  Text ->
  IO Analysis
analyzeGitHub cfg o r = do
  -- I currently have no way of getting active users... getting a list of
  -- collaborators on a repo requires authentication for some reason.
  --
  -- If the owner is an organization, then we can just use org members, which is
  -- public too. And if the auth'ed user is a member of the org, then it returns
  -- all of the members, not just public ones, so that will work just fine.
  --
  -- In the meantime, what do? Maybe get the number of commits, and consider
  -- "active users" as the top 10% in terms of number of commits? Or ask for a
  -- list explicitly? If it is a personal repo, then I can assume that the owner
  -- is the only regular contributor, at least for now.
  --
  -- Right activeUsers <- GitHub.github () (GitHub.collaboratorsOnR ghOwner ghRepo GitHub.FetchAll)
  Right user <-
    GitHub.github
      ()
      ( GitHub.userInfoForR
          <| GitHub.mkName (Proxy :: Proxy GitHub.User) o
      )
  -- assume the only active author is the owner, for now
  let activeAuthors = [require "user email" <| GitHub.userName user]
  Right repo <- GitHub.github () (GitHub.repositoryR ghOwner ghRepo)
  bareRepo <- gitBareClone cfg . GitHub.getUrl <| GitHub.repoHtmlUrl repo
  analyze activeAuthors bareRepo
  where
    ghOwner = GitHub.mkName (Proxy :: Proxy GitHub.Owner) o
    ghRepo = GitHub.mkName (Proxy :: Proxy GitHub.Repo) r

test_analyzeGitHub :: IO Analysis
test_analyzeGitHub = analyzeGitHub Envy.defConfig "bsima" "bin"

-- | Clone the repo to /var/devalloc/repos/<url>, return the full path to the
-- local repo.
gitBareClone :: Config -> Text -> IO FilePath
gitBareClone Config {depo} url = do
  worktreeExists <- Directory.doesPathExist worktree
  let args =
        if worktreeExists
          then ["--git-dir", worktree, "fetch", "origin"]
          else ["clone", "--bare", "--", Text.unpack url, worktree]
  Process.callProcess "git" args
  return worktree
  where
    removeScheme :: Text -> FilePath
    removeScheme u = Text.unpack <. Text.dropWhile (== '/') <. snd <| Text.breakOn "//" u
    worktree = depo </> removeScheme url <.> "git"

-- * parts

encodeParams :: [(Text, Text)] -> Text
encodeParams =
  Encoding.decodeUtf8
    . LBS.toStrict
    . Web.FormUrlEncoded.urlEncodeParams

selectRepo :: Vector GitHub.Repo -> Lucid.Html ()
selectRepo = Lucid.ul_ . mapM_ render . Vector.toList
  where
    render :: GitHub.Repo -> Lucid.Html ()
    render repo =
      Lucid.li_
        . Lucid.a_
          [ linkTo
              (Proxy :: Proxy GitHubAnalysis)
              (GitHub.untagName <| GitHub.simpleOwnerLogin <| GitHub.repoOwner repo)
              (GitHub.untagName <| GitHub.repoName repo)
          ]
        . Lucid.toHtml
        . GitHub.untagName
        <| GitHub.repoName repo

loginButton :: OAuthArgs -> Lucid.Html ()
loginButton OAuthArgs {..} =
  Lucid.a_
    [ Lucid.href_
        <| "https://github.com/login/oauth/authorize?"
        <> encodeParams
          [ ("client_id", githubClientId),
            ("state", githubState)
          ]
    ]
    "Get Started with GitHub"

pitch :: OAuthArgs -> Lucid.Html ()
pitch oAuthArgs =
  Lucid.div_ <| do
    Lucid.h1_ "Devalloc"
    Lucid.p_
      "Devalloc analyzes your codebase trends, finds patterns \
      \ in how your developers work, and protects against tech debt."
    Lucid.p_ "Just hook it up to your CI system - it will warn you when it finds a problem."
    loginButton oAuthArgs
    Lucid.h2_ "Identify blackholes in your codebase"
    Lucid.p_
      "What if none of your active employees have touched some part of the codebase? \
      \ This happens too often with legacy code, and then it turns into a huge source of tech debt. \
      \ Devalloc finds these \"blackholes\" and warns you about them so you can be proactive in eliminating tech debt."
    loginButton oAuthArgs
    Lucid.h2_ "Protect against lost knowledge"
    Lucid.p_ "Not everyone can know every part of a codebase. By finding pieces of code that only 1 or 2 people have touched, devalloc identifes siloed knowledge. This allows you to protect against the risk of this knowledge leaving the company if an employee leaves."
    loginButton oAuthArgs
    Lucid.h2_ "Don't just measure code coverage - also know your dev coverage"
    Lucid.p_ "No matter how smart your employees are, if you are under- or over-utilizing your developers then you will never get optimal performance from your team."
    Lucid.ul_ <| do
      Lucid.li_ "Find developer hot spots in your code: which pieces of code get continually rewritten, taking up valuable dev time?"
      Lucid.li_ "Know how your devs work best: which ones have depth of knowledge, and which ones have breadth?"

    Lucid.p_ "(Paid only)"
    loginButton oAuthArgs
    Lucid.h2_ "See how your teams *actually* organize themselves with cluster analysis"
    Lucid.p_ "Does your team feel splintered or not cohesive? Which developers work best together? Devalloc analyzes the collaboration patterns between devs and helps you form optimal pairings and teams based on shared code and mindspace."
    Lucid.p_ "(Paid only)"
    loginButton oAuthArgs