|
1 | 1 | {-# LANGUAGE CPP #-}
|
| 2 | +{-# LANGUAGE DataKinds #-} |
2 | 3 | {-# LANGUAGE LambdaCase #-}
|
| 4 | +{-# LANGUAGE NamedFieldPuns #-} |
| 5 | +{-# LANGUAGE OverloadedLabels #-} |
3 | 6 | {-# LANGUAGE OverloadedStrings #-}
|
4 | 7 | {-# LANGUAGE TypeApplications #-}
|
5 | 8 | {-# LANGUAGE TypeOperators #-}
|
6 | 9 | module Ide.Plugin.Ormolu
|
7 | 10 | ( descriptor
|
8 | 11 | , provider
|
| 12 | + , LogEvent |
9 | 13 | )
|
10 | 14 | where
|
11 | 15 |
|
12 | 16 | import Control.Exception (Handler (..), IOException,
|
13 |
| - SomeException (..), catches) |
| 17 | + SomeException (..), catches, |
| 18 | + handle) |
14 | 19 | import Control.Monad.Except (ExceptT (ExceptT), runExceptT,
|
15 | 20 | throwError)
|
16 | 21 | import Control.Monad.Extra
|
17 | 22 | import Control.Monad.IO.Class (liftIO)
|
18 | 23 | import Control.Monad.Trans
|
| 24 | +import Control.Monad.Trans.Except (ExceptT (..), mapExceptT, |
| 25 | + runExceptT) |
19 | 26 | import Data.Functor ((<&>))
|
| 27 | +import Data.List (intercalate) |
| 28 | +import Data.Maybe (catMaybes) |
| 29 | +import Data.Text (Text) |
20 | 30 | import qualified Data.Text as T
|
21 | 31 | import Development.IDE hiding (pluginHandlers)
|
22 | 32 | import Development.IDE.GHC.Compat (hsc_dflags, moduleNameString)
|
23 | 33 | import qualified Development.IDE.GHC.Compat as D
|
24 | 34 | import qualified Development.IDE.GHC.Compat.Util as S
|
25 | 35 | import GHC.LanguageExtensions.Type
|
26 | 36 | import Ide.Plugin.Error (PluginError (PluginInternalError))
|
| 37 | +import Ide.Plugin.Properties |
27 | 38 | import Ide.PluginUtils
|
28 | 39 | import Ide.Types hiding (Config)
|
29 | 40 | import qualified Ide.Types as Types
|
30 | 41 | import Language.LSP.Protocol.Message
|
31 | 42 | import Language.LSP.Protocol.Types
|
32 | 43 | import Language.LSP.Server hiding (defaultConfig)
|
33 | 44 | import Ormolu
|
34 |
| -import System.FilePath (takeFileName) |
| 45 | +import System.Exit |
| 46 | +import System.FilePath |
| 47 | +import System.Process.Run (cwd, proc) |
| 48 | +import System.Process.Text (readCreateProcessWithExitCode) |
| 49 | +import Text.Read (readMaybe) |
35 | 50 |
|
36 | 51 | -- ---------------------------------------------------------------------
|
37 | 52 |
|
38 |
| -descriptor :: Recorder (WithPriority T.Text) -> PluginId -> PluginDescriptor IdeState |
39 |
| -descriptor recorder plId = (defaultPluginDescriptor plId) |
40 |
| - { pluginHandlers = mkFormattingHandlers $ provider recorder |
41 |
| - } |
| 53 | +descriptor :: Recorder (WithPriority LogEvent) -> PluginId -> PluginDescriptor IdeState |
| 54 | +descriptor recorder plId = |
| 55 | + (defaultPluginDescriptor plId) |
| 56 | + { pluginHandlers = mkFormattingHandlers $ provider recorder plId, |
| 57 | + pluginConfigDescriptor = defaultConfigDescriptor {configCustomConfig = mkCustomConfig properties} |
| 58 | + } |
| 59 | + |
| 60 | +properties :: Properties '[ 'PropertyKey "external" 'TBoolean] |
| 61 | +properties = |
| 62 | + emptyProperties |
| 63 | + & defineBooleanProperty |
| 64 | + #external |
| 65 | + "Call out to an external \"ormolu\" executable, rather than using the bundled library" |
| 66 | + False |
42 | 67 |
|
43 | 68 | -- ---------------------------------------------------------------------
|
44 | 69 |
|
45 |
| -provider :: Recorder (WithPriority T.Text) -> FormattingHandler IdeState |
46 |
| -provider recorder ideState typ contents fp _ = ExceptT $ withIndefiniteProgress title Cancellable $ runExceptT $ do |
47 |
| - ghc <- liftIO $ runAction "Ormolu" ideState $ use GhcSession fp |
48 |
| - let df = hsc_dflags . hscEnv <$> ghc |
49 |
| - fileOpts <- case df of |
50 |
| - Nothing -> pure [] |
51 |
| - Just df -> pure $ fromDyn df |
52 |
| - |
53 |
| - logWith recorder Debug $ "Using ormolu-" <> VERSION_ormolu |
54 |
| - |
55 |
| - let |
56 |
| - fullRegion = RegionIndices Nothing Nothing |
57 |
| - rangeRegion s e = RegionIndices (Just $ s + 1) (Just $ e + 1) |
58 |
| - mkConf o region = defaultConfig { cfgDynOptions = o, cfgRegion = region } |
59 |
| - fmt :: T.Text -> Config RegionIndices -> IO (Either SomeException T.Text) |
60 |
| - fmt cont conf = flip catches handlers $ do |
61 |
| - let fp' = fromNormalizedFilePath fp |
| 70 | +provider :: Recorder (WithPriority LogEvent) -> PluginId -> FormattingHandler IdeState |
| 71 | +provider recorder plId ideState typ contents fp _ = ExceptT $ withIndefiniteProgress title Cancellable $ runExceptT $ do |
| 72 | + fileOpts <- |
| 73 | + maybe [] (fromDyn . hsc_dflags . hscEnv) |
| 74 | + <$> liftIO (runAction "Ormolu" ideState $ use GhcSession fp) |
| 75 | + useCLI <- liftIO $ runAction "Ormolu" ideState $ usePropertyAction #external plId properties |
| 76 | + |
| 77 | + if useCLI |
| 78 | + then mapExceptT liftIO $ ExceptT |
| 79 | + $ handle @IOException |
| 80 | + (pure . Left . PluginInternalError . T.pack . show) |
| 81 | + $ runExceptT $ cliHandler fileOpts |
| 82 | + else do |
| 83 | + logWith recorder Debug $ LogCompiledInVersion VERSION_ormolu |
| 84 | + |
| 85 | + let |
| 86 | + fmt :: T.Text -> Config RegionIndices -> IO (Either SomeException T.Text) |
| 87 | + fmt cont conf = flip catches handlers $ do |
62 | 88 | #if MIN_VERSION_ormolu(0,5,3)
|
63 |
| - cabalInfo <- getCabalInfoForSourceFile fp' <&> \case |
64 |
| - CabalNotFound -> Nothing |
65 |
| - CabalDidNotMention cabalInfo -> Just cabalInfo |
66 |
| - CabalFound cabalInfo -> Just cabalInfo |
| 89 | + cabalInfo <- getCabalInfoForSourceFile fp' <&> \case |
| 90 | + CabalNotFound -> Nothing |
| 91 | + CabalDidNotMention cabalInfo -> Just cabalInfo |
| 92 | + CabalFound cabalInfo -> Just cabalInfo |
67 | 93 | #if MIN_VERSION_ormolu(0,7,0)
|
68 |
| - (fixityOverrides, moduleReexports) <- getDotOrmoluForSourceFile fp' |
69 |
| - let conf' = refineConfig ModuleSource cabalInfo (Just fixityOverrides) (Just moduleReexports) conf |
| 94 | + (fixityOverrides, moduleReexports) <- getDotOrmoluForSourceFile fp' |
| 95 | + let conf' = refineConfig ModuleSource cabalInfo (Just fixityOverrides) (Just moduleReexports) conf |
70 | 96 | #else
|
71 |
| - fixityOverrides <- traverse getFixityOverridesForSourceFile cabalInfo |
72 |
| - let conf' = refineConfig ModuleSource cabalInfo fixityOverrides conf |
| 97 | + fixityOverrides <- traverse getFixityOverridesForSourceFile cabalInfo |
| 98 | + let conf' = refineConfig ModuleSource cabalInfo fixityOverrides conf |
73 | 99 | #endif
|
74 |
| - let cont' = cont |
| 100 | + let cont' = cont |
75 | 101 | #else
|
76 |
| - let conf' = conf |
77 |
| - cont' = T.unpack cont |
| 102 | + let conf' = conf |
| 103 | + cont' = T.unpack cont |
78 | 104 | #endif
|
79 |
| - Right <$> ormolu conf' fp' cont' |
80 |
| - handlers = |
81 |
| - [ Handler $ pure . Left . SomeException @OrmoluException |
82 |
| - , Handler $ pure . Left . SomeException @IOException |
83 |
| - ] |
84 |
| - |
85 |
| - case typ of |
86 |
| - FormatText -> do |
87 |
| - res <- liftIO $ fmt contents (mkConf fileOpts fullRegion) |
88 |
| - ret res |
89 |
| - FormatRange (Range (Position sl _) (Position el _)) -> do |
90 |
| - res <- liftIO $ fmt contents (mkConf fileOpts (rangeRegion (fromIntegral sl) (fromIntegral el))) |
91 |
| - ret res |
| 105 | + Right <$> ormolu conf' fp' cont' |
| 106 | + handlers = |
| 107 | + [ Handler $ pure . Left . SomeException @OrmoluException |
| 108 | + , Handler $ pure . Left . SomeException @IOException |
| 109 | + ] |
| 110 | + |
| 111 | + res <- liftIO $ fmt contents defaultConfig { cfgDynOptions = map DynOption fileOpts, cfgRegion = region } |
| 112 | + ret res |
92 | 113 | where
|
| 114 | + fp' = fromNormalizedFilePath fp |
| 115 | + |
| 116 | + region :: RegionIndices |
| 117 | + region = case typ of |
| 118 | + FormatText -> |
| 119 | + RegionIndices Nothing Nothing |
| 120 | + FormatRange (Range (Position sl _) (Position el _)) -> |
| 121 | + RegionIndices (Just $ fromIntegral $ sl + 1) (Just $ fromIntegral $ el + 1) |
| 122 | + |
93 | 123 | title = T.pack $ "Formatting " <> takeFileName (fromNormalizedFilePath fp)
|
94 | 124 |
|
95 | 125 | ret :: Either SomeException T.Text -> ExceptT PluginError (LspM Types.Config) ([TextEdit] |? Null)
|
96 | 126 | ret (Left err) = throwError $ PluginInternalError . T.pack $ "ormoluCmd: " ++ show err
|
97 | 127 | ret (Right new) = pure $ InL $ makeDiffTextEdit contents new
|
98 | 128 |
|
99 |
| - fromDyn :: D.DynFlags -> [DynOption] |
| 129 | + fromDyn :: D.DynFlags -> [String] |
100 | 130 | fromDyn df =
|
101 | 131 | let
|
102 | 132 | pp =
|
103 | 133 | let p = D.sPgm_F $ D.settings df
|
104 | 134 | in ["-pgmF=" <> p | not (null p)]
|
105 | 135 | pm = ("-fplugin=" <>) . moduleNameString <$> D.pluginModNames df
|
106 | 136 | ex = showExtension <$> S.toList (D.extensionFlags df)
|
107 |
| - in |
108 |
| - DynOption <$> pp <> pm <> ex |
| 137 | + in pp <> pm <> ex |
| 138 | + |
| 139 | + cliHandler :: [String] -> ExceptT PluginError IO ([TextEdit] |? Null) |
| 140 | + cliHandler fileOpts = do |
| 141 | + CLIVersionInfo{noCabal} <- do -- check Ormolu version so that we know which flags to use |
| 142 | + (exitCode, out, _err) <- liftIO $ readCreateProcessWithExitCode ( proc "ormolu" ["--version"] ) "" |
| 143 | + let version = do |
| 144 | + guard $ exitCode == ExitSuccess |
| 145 | + "ormolu" : v : _ <- pure $ T.words out |
| 146 | + traverse (readMaybe @Int . T.unpack) $ T.splitOn "." v |
| 147 | + case version of |
| 148 | + Just v -> do |
| 149 | + logWith recorder Debug $ LogExternalVersion v |
| 150 | + pure CLIVersionInfo |
| 151 | + { noCabal = v >= [0, 7] |
| 152 | + } |
| 153 | + Nothing -> do |
| 154 | + logWith recorder Debug $ LogExternalVersion [] |
| 155 | + logWith recorder Warning $ NoVersion out |
| 156 | + pure CLIVersionInfo |
| 157 | + { noCabal = True |
| 158 | + } |
| 159 | + (exitCode, out, err) <- do -- run Ormolu |
| 160 | + let commandArgs = map ("-o" <>) fileOpts |
| 161 | + -- "The --stdin-input-file option is necessary when using input from |
| 162 | + -- stdin and accounting for .cabal files" as per Ormolu documentation |
| 163 | + <> (if noCabal then ["--no-cabal"] else ["--stdin-input-file", fp']) |
| 164 | + <> catMaybes |
| 165 | + [ ("--start-line=" <>) . show <$> regionStartLine region |
| 166 | + , ("--end-line=" <>) . show <$> regionEndLine region |
| 167 | + ] |
| 168 | + cwd = takeDirectory fp' |
| 169 | + logWith recorder Debug $ LogOrmoluCommand commandArgs cwd |
| 170 | + liftIO $ readCreateProcessWithExitCode (proc "ormolu" commandArgs) {cwd = Just cwd} contents |
| 171 | + case exitCode of |
| 172 | + ExitSuccess -> do |
| 173 | + when (not $ T.null err) $ logWith recorder Debug $ StdErr err |
| 174 | + pure $ InL $ makeDiffTextEdit contents out |
| 175 | + ExitFailure n -> do |
| 176 | + logWith recorder Info $ StdErr err |
| 177 | + throwError $ PluginInternalError $ "Ormolu failed with exit code " <> T.pack (show n) |
| 178 | + |
| 179 | +newtype CLIVersionInfo = CLIVersionInfo |
| 180 | + { noCabal :: Bool |
| 181 | + } |
| 182 | + |
| 183 | +data LogEvent |
| 184 | + = NoVersion Text |
| 185 | + | StdErr Text |
| 186 | + | LogCompiledInVersion String |
| 187 | + | LogExternalVersion [Int] |
| 188 | + | LogOrmoluCommand [String] FilePath |
| 189 | + deriving (Show) |
| 190 | + |
| 191 | +instance Pretty LogEvent where |
| 192 | + pretty = \case |
| 193 | + NoVersion t -> "Couldn't get Ormolu version:" <> line <> indent 2 (pretty t) |
| 194 | + StdErr t -> "Ormolu stderr:" <> line <> indent 2 (pretty t) |
| 195 | + LogCompiledInVersion v -> "Using compiled in ormolu-" <> pretty v |
| 196 | + LogExternalVersion v -> |
| 197 | + "Using external ormolu" |
| 198 | + <> if null v then "" else "-" |
| 199 | + <> pretty (intercalate "." $ map show v) |
| 200 | + LogOrmoluCommand commandArgs cwd -> "Running: `ormolu " <> pretty (unwords commandArgs) <> "` in directory " <> pretty cwd |
109 | 201 |
|
110 | 202 | showExtension :: Extension -> String
|
111 | 203 | showExtension Cpp = "-XCPP"
|
|
0 commit comments