-
-
Notifications
You must be signed in to change notification settings - Fork 443
Expand file tree
/
Copy pathCodeAction.hs
More file actions
347 lines (316 loc) · 14 KB
/
Copy pathCodeAction.hs
File metadata and controls
347 lines (316 loc) · 14 KB
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
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE RecordWildCards #-}
module Ide.Plugin.Cabal.CabalAdd.CodeAction where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trans.Except
import Data.Aeson.Types (toJSON)
import Data.Foldable (asum)
import Data.Maybe (mapMaybe)
import qualified Data.Text as T
import Development.IDE.Core.PluginUtils (uriToFilePathE)
import Development.IDE.Types.Location (Uri)
import Distribution.PackageDescription
import Distribution.PackageDescription.Configuration (flattenPackageDescription)
import qualified Distribution.Pretty as CabalPretty
import Distribution.Simple.BuildTarget (BuildTarget,
buildTargetComponentName,
readBuildTargets)
import Distribution.Utils.Path (getSymbolicPath)
import Distribution.Verbosity (silent,
verboseNoStderr)
import Ide.Logger
import Ide.Plugin.Cabal.CabalAdd.Types
import Ide.Plugin.Cabal.Completion.Completer.Module (fpToExposedModulePath)
import Ide.Plugin.Cabal.Orphans ()
import Ide.Plugin.Error
import Ide.PluginUtils (mkLspCommand)
import Ide.Types (CommandId (CommandId),
PluginId)
import Control.Lens ((^.))
import qualified Data.Aeson as Aeson
import Development.IDE.Session.Diagnostics
import qualified Language.LSP.Protocol.Lens as JL
import Language.LSP.Protocol.Types (CodeActionKind (..),
VersionedTextDocumentIdentifier)
import qualified Language.LSP.Protocol.Types as J
import System.FilePath
import Text.PrettyPrint (render)
import Text.Regex.TDFA
--------------------------------------------
-- Add module to cabal file
--------------------------------------------
{- | Takes a path to a cabal file, a module path in exposed module syntax
and the contents of the cabal file and generates all possible
code actions for inserting the module into the cabal file
with the given contents.
-}
collectModuleInsertionOptions ::
(MonadIO m) =>
Recorder (WithPriority Log) ->
PluginId ->
VersionedTextDocumentIdentifier ->
J.Diagnostic ->
-- | The file path of the cabal file to insert the new module into
FilePath ->
-- | The generic package description of the cabal file to insert the new module into.
GenericPackageDescription ->
-- | The URI of the unknown haskell file/new module to insert into the cabal file.
Uri ->
ExceptT PluginError m [J.CodeAction]
collectModuleInsertionOptions _ plId txtDocIdentifier diag cabalFilePath gpd haskellFilePathURI = do
haskellFilePath <- uriToFilePathE haskellFilePathURI
let configs = concatMap (mkModuleInsertionConfig txtDocIdentifier cabalFilePath haskellFilePath) (makeStanzaItems gpd)
pure $ map (mkCodeActionForModulePath plId diag) configs
where
makeStanzaItems :: GenericPackageDescription -> [StanzaItem]
makeStanzaItems gpd =
mainLibItem pd
++ libItems pd
++ executableItems pd
++ testSuiteItems pd
++ benchmarkItems pd
where
pd = flattenPackageDescription gpd
{- | Takes a buildInfo of a cabal file component as defined in the generic package description,
and translates it to filepaths of the component's hsSourceDirs,
to be processed for adding modules to exposed-, or other-modules fields in a cabal file.
-}
buildInfoToHsSourceDirs :: BuildInfo -> [FilePath]
buildInfoToHsSourceDirs buildInfo = map getSymbolicPath hsSourceDirs'
where
hsSourceDirs' = hsSourceDirs buildInfo
{- | Takes the path to the cabal file to insert the module into,
the module path to be inserted, and a stanza representation.
Returns a list of module insertion configs, where each config
represents a possible place to insert the module.
-}
mkModuleInsertionConfig :: VersionedTextDocumentIdentifier -> FilePath -> FilePath -> StanzaItem -> [ModuleInsertionConfig]
mkModuleInsertionConfig txtDocIdentifier cabalFilePath haskellFilePath (StanzaItem{..}) = do
case mkRelativeModulePathM siHsSourceDirs cabalFilePath haskellFilePath of
Just processedModPath ->
[modInsertItem processedModPath "other-modules"]
++ [modInsertItem processedModPath "exposed-modules" | CLibName _ <- [siComponent]]
_ -> []
where
modInsertItem :: T.Text -> T.Text -> ModuleInsertionConfig
modInsertItem modPath label =
ModuleInsertionConfig
{ targetFile = cabalFilePath
, moduleToInsert = modPath
, modVerTxtDocId = txtDocIdentifier
, insertionStanza = siComponent
, insertionLabel = label
}
mkCodeActionForModulePath :: PluginId -> J.Diagnostic -> ModuleInsertionConfig -> J.CodeAction
mkCodeActionForModulePath plId diag insertionConfig =
J.CodeAction
{ _title = "Add to " <> label <> " as " <> fieldName
, _kind = Just CodeActionKind_Refactor
, _diagnostics = Just [diag]
, _isPreferred = Nothing
, _disabled = Nothing
, _edit = Nothing
, _command = Just command
, _data_ = Nothing
}
where
fieldName = insertionLabel insertionConfig
command = mkLspCommand plId (CommandId cabalAddModuleCommandId) "Add missing module" (Just [toJSON insertionConfig])
label = T.pack $ CabalPretty.prettyShow $ insertionStanza insertionConfig
{- | Takes a list of source subdirectories, a cabal source path and a haskell filepath
and returns a path to the module in exposed module syntax.
The path will be relative to one of the subdirectories, in case the module is contained within one of them.
-}
mkRelativeModulePathM :: [FilePath] -> FilePath -> FilePath -> Maybe T.Text
mkRelativeModulePathM hsSourceDirs cabalSrcPath' haskellFilePath =
asum $
map
( \srcDir -> do
let relMP = makeRelative (normalise (cabalSrcPath </> srcDir)) haskellFilePath
if relMP == haskellFilePath then Nothing else Just $ fpToExposedModulePath cabalSrcPath relMP
)
hsSourceDirs
where
cabalSrcPath = takeDirectory cabalSrcPath'
isUnknownModuleDiagnostic :: J.Diagnostic -> Bool
isUnknownModuleDiagnostic diag =
case diag ^. JL.data_ of
Nothing -> False
Just v ->
case Aeson.fromJSON v of
Aeson.Success details ->
case structuredCradleError details of
Just (UnknownModuleError _) -> True
_ -> False
_ -> False
--------------------------
-- Below are several utility functions which create a StanzaItem for each of the possible Stanzas,
-- these all have specific constructors we need to match, so we can't generalise this process well.
--------------------------
benchmarkItems :: PackageDescription -> [StanzaItem]
benchmarkItems pd =
map
( \benchmark ->
StanzaItem
{ siComponent = CBenchName $ benchmarkName benchmark
, siHsSourceDirs = buildInfoToHsSourceDirs $ benchmarkBuildInfo benchmark
}
)
(benchmarks pd)
testSuiteItems :: PackageDescription -> [StanzaItem]
testSuiteItems pd =
map
( \testSuite ->
StanzaItem
{ siComponent = CTestName $ testName testSuite
, siHsSourceDirs = buildInfoToHsSourceDirs $ testBuildInfo testSuite
}
)
(testSuites pd)
executableItems :: PackageDescription -> [StanzaItem]
executableItems pd =
map
( \executable ->
StanzaItem
{ siComponent = CExeName $ exeName executable
, siHsSourceDirs = buildInfoToHsSourceDirs $ buildInfo executable
}
)
(executables pd)
libItems :: PackageDescription -> [StanzaItem]
libItems pd =
mapMaybe
( \subLib ->
case libName subLib of
LSubLibName compName ->
Just
StanzaItem
{ siComponent = CLibName $ LSubLibName compName
, siHsSourceDirs = buildInfoToHsSourceDirs $ libBuildInfo subLib
}
_ -> Nothing
)
(subLibraries pd)
mainLibItem :: PackageDescription -> [StanzaItem]
mainLibItem pd =
case library pd of
Just lib ->
[ StanzaItem
{ siComponent = CLibName LMainLibName
, siHsSourceDirs = buildInfoToHsSourceDirs $ libBuildInfo lib
}
]
Nothing -> []
--------------------------------------------
-- Add dependency to a cabal file
--------------------------------------------
{- | Creates a code action that calls the `cabalAddCommand`,
using dependency-version suggestion pairs as input.
Returns disabled action if no cabal files given.
Takes haskell and cabal file paths to create a relative path
to the haskell file, which is used to get a `BuildTarget`.
-}
addDependencySuggestCodeAction ::
PluginId ->
-- | Cabal's versioned text identifier
VersionedTextDocumentIdentifier ->
-- | A dependency-version suggestion pairs
[(T.Text, T.Text)] ->
-- | Path to the haskell file (source of diagnostics)
FilePath ->
-- | Path to the cabal file (that will be edited)
FilePath ->
GenericPackageDescription ->
IO [J.CodeAction]
addDependencySuggestCodeAction plId verTxtDocId suggestions haskellFilePath cabalFilePath gpd = do
buildTargets <- liftIO $ getBuildTargets (flattenPackageDescription gpd) cabalFilePath haskellFilePath
case buildTargets of
-- If there are no build targets found, run the `cabal-add` command with default behaviour
[] -> pure $ mkCodeActionForDependency cabalFilePath Nothing <$> suggestions
-- Otherwise provide actions for all found targets
targets ->
pure $
concat
[ mkCodeActionForDependency cabalFilePath (Just $ buildTargetToStringRepr target)
<$> suggestions
| target <- targets
]
where
{- | Note the use of the `pretty` function.
It converts the `BuildTarget` to an acceptable string representation.
It will be used as the input for `cabal-add`'s `executeConfig`.
-}
buildTargetToStringRepr target = render $ CabalPretty.pretty $ buildTargetComponentName target
mkCodeActionForDependency :: FilePath -> Maybe String -> (T.Text, T.Text) -> J.CodeAction
mkCodeActionForDependency cabalFilePath target (suggestedDep, suggestedVersion) =
let
versionTitle = if T.null suggestedVersion then T.empty else "-" <> suggestedVersion
targetTitle = case target of
Nothing -> T.empty
Just t -> " at " <> T.pack t
title = "Add dependency " <> suggestedDep <> versionTitle <> targetTitle
version = if T.null suggestedVersion then Nothing else Just suggestedVersion
params =
CabalAddDependencyCommandParams
{ depCabalPath = cabalFilePath
, depVerTxtDocId = verTxtDocId
, depBuildTarget = target
, depDependency = suggestedDep
, depVersion = version
}
command = mkLspCommand plId (CommandId cabalAddDependencyCommandId) "Add dependency" (Just [toJSON params])
in
J.CodeAction title (Just CodeActionKind_QuickFix) (Just []) Nothing Nothing Nothing (Just command) Nothing
{- | Finds the build targets that are used in `cabal-add`.
Note the unorthodox usage of `readBuildTargets`:
If the relative path to the haskell file is provided,
`readBuildTargets` will return the build targets, this
module is mentioned in (either exposed-modules or other-modules).
-}
getBuildTargets :: PackageDescription -> FilePath -> FilePath -> IO [BuildTarget]
getBuildTargets pd cabalFilePath haskellFilePath = do
let haskellFileRelativePath = makeRelative (dropFileName cabalFilePath) haskellFilePath
readBuildTargets (verboseNoStderr silent) pd [haskellFileRelativePath]
{- | Gives a mentioned number of @(dependency, version)@ pairs
found in the "hidden package" diagnostic message.
For example, if a ghc error looks like this:
> "Could not load module ‘Data.List.Split’
> It is a member of the hidden package ‘split-0.2.5’.
> Perhaps you need to add ‘split’ to the build-depends in your .cabal file."
or this if PackageImports extension is used:
> "Could not find module ‘Data.List.Split’
> Perhaps you meant
> Data.List.Split (needs flag -package-id split-0.2.5)"
It extracts mentioned package names and version numbers.
In this example, it will be @[("split", "0.2.5")]@
Also supports messages without a version.
> "Perhaps you need to add ‘split’ to the build-depends in your .cabal file."
Will turn into @[("split", "")]@
-}
hiddenPackageSuggestion :: J.Diagnostic -> [(T.Text, T.Text)]
hiddenPackageSuggestion diag = getMatch (msg =~ regex)
where
msg :: T.Text
msg = diag ^. JL.message
regex :: T.Text
regex =
let regex' = "([a-zA-Z0-9-]*[a-zA-Z0-9])(-([0-9\\.]*))?"
in "It is a member of the hidden package [\8216']"
<> regex'
<> "[\8217']"
<> "|"
<> "needs flag -package-id "
<> regex'
-- Have to do this matching because `Regex.TDFA` doesn't(?) support
-- not-capturing groups like (?:message)
getMatch :: (T.Text, T.Text, T.Text, [T.Text]) -> [(T.Text, T.Text)]
getMatch (_, _, _, []) = []
getMatch (_, _, _, [dependency, _, cleanVersion, "", "", ""]) = [(dependency, cleanVersion)]
getMatch (_, _, _, ["", "", "", dependency, _, cleanVersion]) = [(dependency, cleanVersion)]
getMatch (_, _, _, _) = []