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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::{prelude::*, LintContext};
use camino::Utf8Path;
use guppy::graph::{PackageGraph, PackageMetadata};
use x_core::WorkspaceStatus;

/// Represents a linter that runs once per package.
pub trait PackageLinter: Linter {
    fn run<'l>(
        &self,
        ctx: &PackageContext<'l>,
        out: &mut LintFormatter<'l, '_>,
    ) -> Result<RunStatus<'l>>;
}

/// Lint context for an individual package.
#[derive(Copy, Clone, Debug)]
pub struct PackageContext<'l> {
    project_ctx: &'l ProjectContext<'l>,
    // PackageContext requires the package graph to be computed and available, though ProjectContext
    // does not.
    package_graph: &'l PackageGraph,
    workspace_path: &'l Utf8Path,
    metadata: PackageMetadata<'l>,
    is_default_member: bool,
}

impl<'l> PackageContext<'l> {
    pub fn new(
        project_ctx: &'l ProjectContext<'l>,
        package_graph: &'l PackageGraph,
        workspace_path: &'l Utf8Path,
        metadata: PackageMetadata<'l>,
    ) -> Result<Self> {
        let default_members = project_ctx.default_members()?;
        Ok(Self {
            project_ctx,
            package_graph,
            workspace_path,
            metadata,
            is_default_member: default_members.status_of(metadata.id()) != WorkspaceStatus::Absent,
        })
    }

    /// Returns the project context.
    pub fn project_ctx(&self) -> &'l ProjectContext<'l> {
        self.project_ctx
    }

    /// Returns the package graph.
    pub fn package_graph(&self) -> &'l PackageGraph {
        self.package_graph
    }

    /// Returns the relative path for this package in the workspace.
    pub fn workspace_path(&self) -> &'l Utf8Path {
        self.workspace_path
    }

    /// Returns the metadata for this package.
    pub fn metadata(&self) -> &PackageMetadata<'l> {
        &self.metadata
    }

    /// Returns true if this is a default member of this workspace.
    pub fn is_default_member(&self) -> bool {
        self.is_default_member
    }
}

impl<'l> LintContext<'l> for PackageContext<'l> {
    fn kind(&self) -> LintKind<'l> {
        LintKind::Package {
            name: self.metadata.name(),
            workspace_path: self.workspace_path,
        }
    }
}