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
use std::collections::HashMap;
use std::fmt::Display;
use std::path::{Path, PathBuf};

use globwalk::{FileType, GlobWalkerBuilder};
use pariter::IteratorExt;
use serde::Deserialize;

use crate::configuration_file::ConfigurationFile;
use crate::io::{read_json_from_file, FromFileError};
use crate::package_manifest::PackageManifest;
use crate::types::{Directory, PackageName};

#[derive(Debug, Deserialize)]
struct PackageManifestGlob(String);

#[derive(Debug, Clone, Copy)]
pub enum MonorepoKind {
    Lerna,
    Workspace,
}

impl Into<&'static str> for MonorepoKind {
    fn into(self) -> &'static str {
        match self {
            MonorepoKind::Lerna => "lerna",
            MonorepoKind::Workspace => "workspace",
        }
    }
}

#[derive(Debug, Deserialize)]
struct LernaManifest {
    packages: Vec<PackageManifestGlob>,
}

#[derive(Debug, Deserialize)]
struct WorkspaceManifest {
    workspaces: Vec<PackageManifestGlob>,
}

#[derive(Debug)]
pub struct MonorepoManifest {
    pub kind: MonorepoKind,
    pub root: Directory,
    globs: Vec<PackageManifestGlob>,
}

#[derive(Debug)]
#[non_exhaustive]
pub struct GlobError {
    pub kind: GlobErrorKind,
}

impl Display for GlobError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "unable to enumerate monorepo packages")
    }
}

impl std::error::Error for GlobError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.kind)
    }
}

impl From<GlobErrorKind> for GlobError {
    fn from(kind: GlobErrorKind) -> Self {
        Self { kind }
    }
}

#[derive(Debug)]
pub enum GlobErrorKind {
    #[non_exhaustive]
    GlobNotValidUtf8(PathBuf),
    #[non_exhaustive]
    GlobWalkBuilderError(globwalk::GlobError),
}

impl Display for GlobErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GlobErrorKind::GlobNotValidUtf8(glob) => {
                write!(f, "glob cannot be expressed in UTF-8: {:?}", glob)
            }
            GlobErrorKind::GlobWalkBuilderError(_) => {
                write!(f, "unable to build glob walker")
            }
        }
    }
}

impl std::error::Error for GlobErrorKind {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self {
            GlobErrorKind::GlobNotValidUtf8(_) => None,
            GlobErrorKind::GlobWalkBuilderError(err) => Some(err),
        }
    }
}

#[derive(Debug)]
#[non_exhaustive]
pub struct WalkError {
    pub kind: WalkErrorKind,
}

impl Display for WalkError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "unable to enumerate monorepo packages")
    }
}

impl std::error::Error for WalkError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.kind)
    }
}

impl From<globwalk::WalkError> for WalkError {
    fn from(err: globwalk::WalkError) -> Self {
        Self {
            kind: WalkErrorKind::GlobWalkError(err),
        }
    }
}

impl From<WalkErrorKind> for WalkError {
    fn from(kind: WalkErrorKind) -> Self {
        Self { kind }
    }
}

#[derive(Debug)]
pub enum WalkErrorKind {
    #[non_exhaustive]
    GlobWalkError(globwalk::WalkError),
    #[non_exhaustive]
    FromFile(FromFileError),
    #[non_exhaustive]
    PackageInMonorepoRoot(PathBuf),
}

impl Display for WalkErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WalkErrorKind::FromFile(_) => {
                write!(f, "unable to reading file")
            }
            WalkErrorKind::GlobWalkError(_) => {
                write!(f, "error walking directory tree")
            }
            WalkErrorKind::PackageInMonorepoRoot(path) => {
                write!(f, "package in monorepo root: {:?}", path)
            }
        }
    }
}

impl std::error::Error for WalkErrorKind {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self {
            WalkErrorKind::FromFile(err) => err.source(),
            WalkErrorKind::GlobWalkError(err) => Some(err),
            WalkErrorKind::PackageInMonorepoRoot(_) => None,
        }
    }
}

#[derive(Debug)]
pub enum EnumeratePackageManifestsError {
    #[non_exhaustive]
    GlobError(GlobError),
    #[non_exhaustive]
    WalkError(WalkError),
}

impl Display for EnumeratePackageManifestsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "unable to enumerate monorepo packages")
    }
}

impl std::error::Error for EnumeratePackageManifestsError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self {
            EnumeratePackageManifestsError::GlobError(err) => Some(err),
            EnumeratePackageManifestsError::WalkError(err) => Some(err),
        }
    }
}

impl From<GlobError> for EnumeratePackageManifestsError {
    fn from(err: GlobError) -> Self {
        Self::GlobError(err)
    }
}

impl From<WalkError> for EnumeratePackageManifestsError {
    fn from(err: WalkError) -> Self {
        Self::WalkError(err)
    }
}

fn get_internal_package_manifests(
    monorepo_root: &Directory,
    package_globs: &[PackageManifestGlob],
) -> Result<impl Iterator<Item = Result<PackageManifest, WalkError>>, GlobError> {
    let mut package_manifests: Vec<String> = package_globs
        .iter()
        .map(|package_manifest_glob| {
            let glob = Path::new(&package_manifest_glob.0).join("package.json");
            glob.to_str().map(ToOwned::to_owned).ok_or(GlobError {
                kind: GlobErrorKind::GlobNotValidUtf8(glob),
            })
        })
        .collect::<Result<_, _>>()?;

    // ignore paths to speed up file-system walk
    package_manifests.push(String::from("!node_modules/"));

    // Take ownership so we can move this value into the parallel_map
    let monorepo_root = monorepo_root.to_owned();

    // DISCUSS: can we enforce _here_ that there are no files in the monorepo root,
    // and never have to check that again anywhere else?
    let package_manifests_iter =
        GlobWalkerBuilder::from_patterns(&monorepo_root, &package_manifests)
            .file_type(FileType::FILE)
            .min_depth(1)
            .build()
            .map_err(|err| GlobError {
                kind: GlobErrorKind::GlobWalkBuilderError(err),
            })?
            .parallel_map_custom(
                |options| options.threads(32),
                move |dir_entry| -> Result<PackageManifest, WalkError> {
                    let dir_entry = dir_entry?;
                    let path = dir_entry.path();
                    let manifest = PackageManifest::from_directory(
                        &monorepo_root,
                        Directory::unchecked_from_path(
                            path.parent()
                                .ok_or_else(|| {
                                    WalkErrorKind::PackageInMonorepoRoot(path.to_owned())
                                })?
                                .strip_prefix(&monorepo_root)
                                .expect("expected all files to be children of monorepo root"),
                        ),
                    )
                    .map_err(WalkErrorKind::FromFile)?;
                    Ok(manifest)
                },
            );

    Ok(package_manifests_iter)
}

impl MonorepoManifest {
    const LERNA_MANIFEST_FILENAME: &'static str = "lerna.json";
    const PACKAGE_MANIFEST_FILENAME: &'static str = "package.json";

    fn from_lerna_manifest(root: &Path) -> Result<MonorepoManifest, FromFileError> {
        let filename = root.join(Self::LERNA_MANIFEST_FILENAME);
        let lerna_manifest: LernaManifest = read_json_from_file(&filename)?;
        Ok(MonorepoManifest {
            kind: MonorepoKind::Lerna,
            root: Directory::unchecked_from_path(root),
            globs: lerna_manifest.packages,
        })
    }

    fn from_package_manifest(root: &Path) -> Result<MonorepoManifest, FromFileError> {
        let filename = root.join(Self::PACKAGE_MANIFEST_FILENAME);
        let package_manifest: WorkspaceManifest = read_json_from_file(&filename)?;
        Ok(MonorepoManifest {
            kind: MonorepoKind::Workspace,
            root: Directory::unchecked_from_path(root),
            globs: package_manifest.workspaces,
        })
    }

    pub fn from_directory<P>(root: P) -> Result<MonorepoManifest, FromFileError>
    where
        P: AsRef<Path>,
    {
        MonorepoManifest::from_lerna_manifest(root.as_ref())
            .or_else(|_| MonorepoManifest::from_package_manifest(root.as_ref()))
    }

    pub fn package_manifests_by_package_name(
        &self,
    ) -> Result<HashMap<PackageName, PackageManifest>, EnumeratePackageManifestsError> {
        let map = get_internal_package_manifests(&self.root, &self.globs)?
            .map(|maybe_manifest| -> Result<_, WalkError> {
                let manifest = maybe_manifest?;
                Ok((manifest.contents.name.to_owned(), manifest))
            })
            .collect::<Result<_, _>>()?;
        Ok(map)
    }

    pub fn internal_package_manifests(
        &self,
    ) -> Result<impl Iterator<Item = Result<PackageManifest, WalkError>>, GlobError> {
        get_internal_package_manifests(&self.root, &self.globs)
    }
}