aboutsummaryrefslogtreecommitdiffstats
path: root/app/Review.hs
blob: 52af23b8b8d1593049223a33877b7e6a01609041 (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
module Review
  ( Plan (..),
    PlanStep (..),
    formulatePlan,
    reviewStep,
    commitReview,
  )
where

import Backend qualified
import Comment.Language qualified as L
import Control.Monad (ap, forM, forM_, when)
import Data.Binary qualified as B
import Data.ByteString.Lazy qualified as LB
import Data.Function ((&))
import Data.List.NonEmpty qualified as NE
import Data.Text qualified as T
import Data.Text.Encoding qualified as T
import Data.Text.IO qualified as T
import GHC.Generics (Generic)
import Patch qualified as A
import Process (proc, sh, sh_)
import Render (renderAsText)
import System.Directory (createDirectoryIfMissing)
import System.FilePath (takeDirectory, (</>))
import System.IO.Temp (withSystemTempDirectory)
import System.Process.Typed qualified as P
import Text.Diff.Extra ()
import Text.Diff.Parse.Types qualified as D

data Plan = Plan
  { baseBranch :: BranchName,
    featureBranch :: BranchName,
    commit :: Backend.CommitHash,
    perCommit :: Bool,
    steps :: NE.NonEmpty PlanStep
  }
  deriving (Show, Generic, B.Binary)

type BranchName = T.Text

data PlanStep = PlanStep
  { commit :: Backend.CommitHash,
    earlierCommit :: Backend.CommitHash,
    changes :: D.FileDeltas
  }
  deriving (Show, Generic, B.Binary)

formulatePlan :: Bool -> T.Text -> T.Text -> IO Plan
formulatePlan perCommit baseBranch featureBranch = do
  baseCommit <- Backend.resolveRef baseBranch
  featureCommit <- Backend.resolveRef featureBranch

  commits <-
    if perCommit
      then do
        commits <-
          reverse <$> Backend.getCommitsBetween baseCommit featureCommit
        pure $ zipWith (,) commits (baseCommit : commits)
      else pure [(featureCommit, baseCommit)]

  fileDeltas <-
    fmap concat . forM commits $
      \(commit, earlierCommit) ->
        map ((commit, earlierCommit),) . (: []) . (.fileDeltas)
          <$> Backend.diffOf earlierCommit commit

  pure
    Plan
      { steps =
          NE.fromList
            ( map
                ( \((commit, earlierCommit), changes) ->
                    PlanStep {..}
                )
                fileDeltas
            ),
        commit = featureCommit,
        ..
      }

reviewStep :: PlanStep -> IO D.FileDeltas
reviewStep step = do
  commitMessages <-
    T.decodeUtf8 . LB.toStrict
      <$> sh
        ( proc
            "git log %..%"
            (Backend.toTextUnsafe step.earlierCommit)
            (Backend.toTextUnsafe step.commit)
        )
  separateReview step.earlierCommit step.changes
    =<< reviewPatch commitMessages step.changes

reviewPatch :: T.Text -> D.FileDeltas -> IO D.FileDeltas
reviewPatch commitMessages fileDeltas =
  withSystemTempDirectory "anissue" $ \tmp -> do
    let patchFile = tmp </> "a.patch"
        patchFile' = tmp </> "b.patch"
        patchContents = renderAsText (A.Patch fileDeltas)
    T.writeFile patchFile patchContents
    T.writeFile patchFile' (addCommitMessages <> patchContents)
    sh_ (proc "${EDITOR-vi} %" patchFile')
    T.writeFile patchFile'
      . (renderAsText . A.Patch)
      . addComments
      . ((.fileDeltas) . A.parse)
      . stripCommitMessages
      =<< T.readFile patchFile'
    ((.fileDeltas) . A.parse . T.decodeUtf8 . LB.toStrict)
      <$> sh (proc "rediff % %" patchFile patchFile')
  where
    addCommitMessages =
      T.unlines . map ("# " <>) . T.lines $ commitMessages
    stripCommitMessages =
      T.unlines . dropWhile ("# " `T.isPrefixOf`) . T.lines

addComments :: D.FileDeltas -> D.FileDeltas
addComments =
  map
    ( \fileDelta@(D.FileDelta {D.fileDeltaSourceFile}) ->
        ( mapContent . mapHunks . mapLines $
            \line@(D.Line {..}) ->
              if lineAnnotation == D.Comment
                then
                  let language = L.fromPath (T.unpack fileDeltaSourceFile)
                   in D.Line D.Added (L.lineStart language <> " REVIEW" <> lineContent)
                else line
        )
          fileDelta
    )
  where
    mapContent f x = x {D.fileDeltaContent = f x.fileDeltaContent}
    mapHunks _ D.Binary = D.Binary
    mapHunks f (D.Hunks hs) = D.Hunks (map f hs)
    mapLines f x = x {D.hunkLines = map f x.hunkLines}

separateReview ::
  Backend.CommitHash ->
  D.FileDeltas ->
  D.FileDeltas ->
  IO D.FileDeltas
separateReview commit fileDeltas fileDeltas' =
  withTempSourceFiles commit fileDeltas $ \tmp -> do
    T.writeFile (tmp </> patchFile) (renderAsText (A.Patch fileDeltas))
    T.writeFile (tmp </> patchFile') (renderAsText (A.Patch fileDeltas'))
    sh_
      ( proc "patch --quiet -p0 <../%" patchFile
          & P.setWorkingDir (tmp </> "a")
      )
    sh_
      ( proc "patch --quiet -p0 <../%" patchFile'
          & P.setWorkingDir (tmp </> "b")
      )
    ( ap (flip if' [] . LB.null) $
        (.fileDeltas) . A.parse . T.decodeUtf8 . LB.toStrict
      )
      <$> sh
        ( proc "git diff --no-index -- a b || :"
            & P.setWorkingDir tmp
        )
  where
    patchFile = "a.patch"
    patchFile' = "b.patch"

withTempSourceFiles :: Backend.CommitHash -> D.FileDeltas -> (FilePath -> IO a) -> IO a
withTempSourceFiles commit fileDeltas action = do
  withSystemTempDirectory "anissue" $ \tmp -> do
    createDirectoryIfMissing False (tmp </> "a")
    createDirectoryIfMissing False (tmp </> "b")
    forM_ sourceFiles $ \sourceFile -> do
      let sourceDir = takeDirectory sourceFile
      fileContents <-
        if sourceFile /= "/dev/null"
          then case commit of
            Backend.Commit hash -> sh (proc "git show %:%" hash sourceFile)
            Backend.WorkingTree -> sh (proc "cat" sourceFile)
          else pure ""
      createDirectoryIfMissing True (tmp </> "a" </> sourceDir)
      LB.writeFile (tmp </> "a" </> sourceFile) fileContents
      createDirectoryIfMissing True (tmp </> "b" </> sourceDir)
      LB.writeFile (tmp </> "b" </> sourceFile) fileContents
    action tmp
  where
    sourceFiles = map (T.unpack . (.fileDeltaSourceFile)) fileDeltas

if' :: Bool -> a -> a -> a
if' True a _ = a
if' False _ b = b

commitReview :: Plan -> A.Patch -> IO ()
commitReview plan patch = do
  withSystemTempDirectory "anissue" $ \tmp -> do
    when (not (null patch.fileDeltas)) do
      T.writeFile (tmp </> "review.patch") (renderAsText patch)
      sh_ (proc "patch -p1 <%/review.patch" tmp)
    T.writeFile (tmp </> "commit_editmsg") (commit_editmsg plan)
    sh_ (proc "git add %" (map (T.drop (T.length "b/") . (.fileDeltaDestFile)) patch.fileDeltas))
    sh_ (proc "git commit --allow-empty --template %/commit_editmsg" tmp)

commit_editmsg :: Plan -> T.Text
commit_editmsg plan = do
  T.unlines
    [ "",
      "# Please enter the commit message for your review. Lines starting",
      "# with '#' will be ignored, and an empty message aborts the commit.",
      "#",
      "# To approve the changes, format your commit message like this:",
      "#",
      "# review: approve " <> plan.featureBranch,
      "#",
      "# Reviewed branch " <> plan.featureBranch <> " at commit " <> Backend.toTextUnsafe plan.commit <> ".",
      "#",
      "# To requst changes, format your commit message like this:",
      "#",
      "# review: request-changes " <> plan.featureBranch,
      "#",
      "# Reviewed branch " <> plan.featureBranch <> " at commit " <> Backend.toTextUnsafe plan.commit <> "."
    ]