-
Notifications
You must be signed in to change notification settings - Fork 173
/
Cargo.hs
376 lines (332 loc) · 11.5 KB
/
Cargo.hs
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
module Strategy.Cargo (
discover,
CargoMetadata (..),
CargoProject (..),
NodeDependency (..),
NodeDepKind (..),
PackageId (..),
Resolve (..),
ResolveNode (..),
buildGraph,
getDeps,
mkProject,
findProjects,
) where
import App.Fossa.Analyze.Types (AnalyzeProject, analyzeProject)
import App.Pathfinder.Types (LicenseAnalyzeProject (licenseAnalyzeProject))
import Control.Effect.Diagnostics (
Diagnostics,
Has,
ToDiagnostic,
context,
errCtx,
run,
warn,
)
import Control.Effect.Reader (Reader)
import Data.Aeson.Types (
FromJSON (parseJSON),
Parser,
ToJSON,
withObject,
(.:),
(.:?),
)
import Data.Foldable (for_, traverse_)
import Data.Map.Strict qualified as Map
import Data.Maybe (catMaybes, isJust)
import Data.Set (Set)
import Data.String.Conversion (toText)
import Data.Text qualified as Text
import Diag.Diagnostic (renderDiagnostic)
import Discovery.Filters (AllFilters)
import Discovery.Simple (simpleDiscover)
import Discovery.Walk (
WalkStep (WalkContinue, WalkSkipAll),
findFileNamed,
walkWithFilters',
)
import Effect.Exec (
AllowErr (Never),
Command (..),
Exec,
execJson,
execThrow,
)
import Effect.Grapher (
LabeledGrapher,
direct,
edge,
label,
withLabeling,
)
import Effect.ReadFS (ReadFS, readContentsToml)
import GHC.Generics (Generic)
import Graphing (Graphing, stripRoot)
import Path (Abs, Dir, File, Path, parent, parseRelFile, toFilePath, (</>))
import Prettyprinter (Pretty (pretty))
import Toml (TomlCodec, dioptional, diwrap, (.=))
import Toml qualified
import Types (
DepEnvironment (EnvDevelopment, EnvProduction),
DepType (CargoType),
Dependency (..),
DependencyResults (..),
DiscoveredProject (..),
DiscoveredProjectType (CargoProjectType),
GraphBreadth (Complete),
License (License),
LicenseResult (LicenseResult, licenseFile, licensesFound),
LicenseType (LicenseFile, LicenseSPDX, UnknownType),
VerConstraint (CEq),
insertEnvironment,
)
newtype CargoLabel
= CargoDepKind DepEnvironment
deriving (Eq, Ord, Show)
data PackageId = PackageId
{ pkgIdName :: Text.Text
, pkgIdVersion :: Text.Text
, pkgIdSource :: Text.Text
}
deriving (Eq, Ord, Show)
data PackageDependency = PackageDependency
{ pkgDepName :: Text.Text
, pkgDepReq :: Text.Text
, pkgDepKind :: Maybe Text.Text
}
deriving (Eq, Ord, Show)
data Package = Package
{ pkgName :: Text.Text
, pkgVersion :: Text.Text
, pkgId :: PackageId
, pkgLicense :: Maybe Text.Text
, pkgLicenseFile :: Maybe Text.Text
, pkgDependencies :: [PackageDependency]
}
deriving (Eq, Ord, Show)
data NodeDepKind = NodeDepKind
{ nodeDepKind :: Maybe Text.Text
, nodeDepTarget :: Maybe Text.Text
}
deriving (Eq, Ord, Show)
data NodeDependency = NodeDependency
{ nodePkg :: PackageId
, nodeDepKinds :: [NodeDepKind]
}
deriving (Eq, Ord, Show)
data ResolveNode = ResolveNode
{ resolveNodeId :: PackageId
, resolveNodeDeps :: [NodeDependency]
}
deriving (Eq, Ord, Show)
newtype Resolve = Resolve
{ resolvedNodes :: [ResolveNode]
}
deriving (Eq, Ord, Show)
data CargoMetadata = CargoMetadata
{ metadataPackages :: [Package]
, metadataWorkspaceMembers :: [PackageId]
, metadataResolve :: Resolve
}
deriving (Eq, Ord, Show)
instance FromJSON PackageDependency where
parseJSON = withObject "PackageDependency" $ \obj ->
PackageDependency <$> obj .: "name"
<*> obj .: "req"
<*> obj .:? "kind"
instance FromJSON Package where
parseJSON = withObject "Package" $ \obj ->
Package <$> obj .: "name"
<*> obj .: "version"
<*> (obj .: "id" >>= parsePkgId)
<*> obj .:? "license"
<*> obj .:? "license_file"
<*> obj .: "dependencies"
instance FromJSON NodeDepKind where
parseJSON = withObject "NodeDepKind" $ \obj ->
NodeDepKind <$> obj .:? "kind"
<*> obj .:? "target"
instance FromJSON NodeDependency where
parseJSON = withObject "NodeDependency" $ \obj ->
NodeDependency <$> (obj .: "pkg" >>= parsePkgId)
<*> obj .: "dep_kinds"
instance FromJSON ResolveNode where
parseJSON = withObject "ResolveNode" $ \obj ->
ResolveNode <$> (obj .: "id" >>= parsePkgId)
<*> obj .: "deps"
instance FromJSON Resolve where
parseJSON = withObject "Resolve" $ \obj ->
Resolve <$> obj .: "nodes"
instance FromJSON CargoMetadata where
parseJSON = withObject "CargoMetadata" $ \obj ->
CargoMetadata <$> obj .: "packages"
<*> (obj .: "workspace_members" >>= traverse parsePkgId)
<*> obj .: "resolve"
discover :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [DiscoveredProject CargoProject]
discover = simpleDiscover findProjects mkProject CargoProjectType
findProjects :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [CargoProject]
findProjects = walkWithFilters' $ \dir _ files -> do
case findFileNamed "Cargo.toml" files of
Nothing -> pure ([], WalkContinue)
Just toml -> do
let project =
CargoProject
{ cargoToml = toml
, cargoDir = dir
}
pure ([project], WalkSkipAll)
data CargoProject = CargoProject
{ cargoDir :: Path Abs Dir
, cargoToml :: Path Abs File
}
deriving (Eq, Ord, Show, Generic)
instance ToJSON CargoProject
instance AnalyzeProject CargoProject where
analyzeProject _ = getDeps
data CargoPackage = CargoPackage
{ license :: Maybe Text.Text
, cargoLicenseFile :: Maybe FilePath
-- ^ Path relative to Cargo.toml containing the license
}
deriving (Eq, Show)
cargoPackageCodec :: TomlCodec CargoPackage
cargoPackageCodec =
CargoPackage
<$> dioptional (Toml.text "license") .= license
<*> dioptional (Toml.string "license-file") .= cargoLicenseFile
-- |Representation of a Cargo.toml file. See
-- [here](https://doc.rust-lang.org/cargo/reference/manifest.html)
-- for a description of this format.
newtype CargoToml = CargoToml
{cargoPackage :: CargoPackage}
deriving (Eq, Show)
cargoTomlCodec :: TomlCodec CargoToml
cargoTomlCodec = diwrap (Toml.table cargoPackageCodec "package")
-- ^^ The above is a bit obscure. It's generating a TomlCodec CargoPackage and
-- then using 'diwrap'/Coercible to make a TomlCodec CargoToml. I can't use
-- 'CargoToml <$>' because TomlCodec aliases (Codec a a) and only (Codec a)
-- has a Functor instance, so I'd end up with a (Codec CargoPackage CargoToml).
instance LicenseAnalyzeProject CargoProject where
licenseAnalyzeProject = analyzeLicenses . cargoToml
-- |Analyze a Cargo.toml for license information. The format is documented
-- (here)[https://doc.rust-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields]
analyzeLicenses :: (Has ReadFS sig m, Has Diagnostics sig m) => Path Abs File -> m [LicenseResult]
analyzeLicenses tomlPath = do
pkg <- cargoPackage <$> readContentsToml cargoTomlCodec tomlPath
licensePathText <- maybe (pure Nothing) mkLicensePath (cargoLicenseFile pkg)
-- The license-file field in Cargo.toml is relative to the dir of the
-- Cargo.toml file. Generate an absolute path to license-file.
let maybeLicense = license pkg
let licenseCon = selectLicenseCon <$> maybeLicense
pure
[ LicenseResult
{ licenseFile = toFilePath tomlPath
, licensesFound =
catMaybes
[ License <$> licenseCon <*> maybeLicense
, License LicenseFile <$> licensePathText
]
}
]
where
mkLicensePath path = case parseRelFile path of
Just p -> pure . Just . toText $ parent tomlPath </> p
Nothing ->
warn ("Cannot parse 'license-file' value: " <> path)
>> pure Nothing
textElem c = isJust . Text.findIndex (== c)
-- Old versions of Cargo allow '/' as a separator between SPDX values in
-- 'license'. In that case 'license' can't be treated as a LicenseSPDX.
selectLicenseCon licenseText =
if textElem '/' licenseText
then UnknownType
else LicenseSPDX
mkProject :: CargoProject -> DiscoveredProject CargoProject
mkProject project =
DiscoveredProject
{ projectType = CargoProjectType
, projectBuildTargets = mempty
, projectPath = cargoDir project
, projectData = project
}
getDeps :: (Has Exec sig m, Has Diagnostics sig m) => CargoProject -> m DependencyResults
getDeps project = do
(graph, graphBreadth) <- context "Cargo" . context "Dynamic analysis" . analyze $ project
pure $
DependencyResults
{ dependencyGraph = graph
, dependencyGraphBreadth = graphBreadth
, dependencyManifestFiles = [cargoToml project]
}
cargoGenLockfileCmd :: Command
cargoGenLockfileCmd =
Command
{ cmdName = "cargo"
, cmdArgs = ["generate-lockfile"]
, cmdAllowErr = Never
}
cargoMetadataCmd :: Command
cargoMetadataCmd =
Command
{ cmdName = "cargo"
, cmdArgs = ["metadata"]
, cmdAllowErr = Never
}
analyze ::
(Has Exec sig m, Has Diagnostics sig m) =>
CargoProject ->
m (Graphing Dependency, GraphBreadth)
analyze (CargoProject manifestDir manifestFile) = do
_ <- context "Generating lockfile" $ errCtx (FailedToGenLockFile manifestFile) $ execThrow manifestDir cargoGenLockfileCmd
meta <- errCtx (FailedToRetrieveCargoMetadata manifestFile) $ execJson @CargoMetadata manifestDir cargoMetadataCmd
graph <- context "Building dependency graph" $ pure (buildGraph meta)
pure (graph, Complete)
newtype FailedToGenLockFile = FailedToGenLockFile (Path Abs File)
instance ToDiagnostic FailedToGenLockFile where
renderDiagnostic (FailedToGenLockFile path) = pretty $ "Could not generate lock file for cargo manifest: " <> (show path)
newtype FailedToRetrieveCargoMetadata = FailedToRetrieveCargoMetadata (Path Abs File)
instance ToDiagnostic FailedToRetrieveCargoMetadata where
renderDiagnostic (FailedToRetrieveCargoMetadata path) = pretty $ "Could not retrieve machine readable cargo metadata for: " <> (show path)
toDependency :: PackageId -> Set CargoLabel -> Dependency
toDependency pkg =
foldr
applyLabel
Dependency
{ dependencyType = CargoType
, dependencyName = pkgIdName pkg
, dependencyVersion = Just $ CEq $ pkgIdVersion pkg
, dependencyLocations = []
, dependencyEnvironments = mempty
, dependencyTags = Map.empty
}
where
applyLabel :: CargoLabel -> Dependency -> Dependency
applyLabel (CargoDepKind env) = insertEnvironment env
-- Possible values here are "build", "dev", and null.
-- Null refers to productions, while dev and build refer to development-time dependencies
-- Cargo does not differentiate test dependencies and dev dependencies,
-- so we just simplify it to Development.
kindToLabel :: Maybe Text.Text -> CargoLabel
kindToLabel (Just _) = CargoDepKind EnvDevelopment
kindToLabel Nothing = CargoDepKind EnvProduction
addLabel :: Has (LabeledGrapher PackageId CargoLabel) sig m => NodeDependency -> m ()
addLabel dep = do
let packageId = nodePkg dep
traverse_ (label packageId . kindToLabel . nodeDepKind) $ nodeDepKinds dep
addEdge :: Has (LabeledGrapher PackageId CargoLabel) sig m => ResolveNode -> m ()
addEdge node = do
let parentId = resolveNodeId node
for_ (resolveNodeDeps node) $ \dep -> do
addLabel dep
edge parentId $ nodePkg dep
buildGraph :: CargoMetadata -> Graphing Dependency
buildGraph meta = stripRoot $
run . withLabeling toDependency $ do
traverse_ direct $ metadataWorkspaceMembers meta
traverse_ addEdge $ resolvedNodes $ metadataResolve meta
parsePkgId :: Text.Text -> Parser PackageId
parsePkgId t =
case Text.splitOn " " t of
[a, b, c] -> pure $ PackageId a b c
_ -> fail "malformed Package ID"