ploys 0.6.0

A utility to manage projects, packages, releases and deployments.
Documentation
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Package inspection and management utilities
//!
//! This module includes utilities for inspecting and managing packages located
//! on the local file system or in a remote version control system.

mod bump;
mod error;
mod kind;
pub mod lockfile;
pub mod manifest;

use std::borrow::Borrow;
use std::str::FromStr;

use bytes::Bytes;
use either::Either;
use relative_path::{RelativePath, RelativePathBuf};
use semver::Version;
use tracing::info;
use url::Url;

use crate::changelog::Changelog;
use crate::project::Project;
use crate::repository::adapters::subdirectory::Subdirectory;
use crate::repository::types::staging::Staging;
use crate::repository::{Remote, Repository, Stage};

pub use self::bump::{Bump, BumpOrVersion, Error as BumpError};
pub use self::error::Error;
pub use self::kind::PackageKind;
pub use self::lockfile::Lockfile;
pub use self::manifest::Manifest;
use self::manifest::{Dependencies, DependenciesMut, DependencyMut, DependencyRef};

/// A project package.
#[derive(Clone)]
pub struct Package<T = Staging> {
    pub(crate) repository: Subdirectory<T>,
    manifest: Manifest,
    primary: bool,
}

impl Package {
    /// Constructs a new cargo package.
    pub fn new_cargo(name: impl Into<String>) -> Self {
        Self {
            repository: Subdirectory::new_root(Staging::new()),
            manifest: Manifest::new_cargo(name),
            primary: false,
        }
    }
}

impl<T> Package<T> {
    /// Gets the package name.
    pub fn name(&self) -> &str {
        match self.manifest() {
            Manifest::Cargo(cargo) => cargo.package().expect("package").name(),
        }
    }

    /// Gets the package description.
    pub fn description(&self) -> Option<&str> {
        match self.manifest() {
            Manifest::Cargo(cargo) => cargo.package().expect("package").description(),
        }
    }

    /// Sets the package description.
    pub fn set_description(&mut self, description: impl Into<String>) -> &mut Self {
        match self.manifest_mut() {
            Manifest::Cargo(cargo) => {
                cargo
                    .package_mut()
                    .expect("package")
                    .set_description(description);
            }
        }

        self
    }

    /// Builds the package with the given description.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.set_description(description);
        self
    }

    /// Gets the package version.
    pub fn version(&self) -> Version {
        match self.manifest() {
            Manifest::Cargo(cargo) => cargo.package().expect("package").version(),
        }
    }

    /// Sets the package version.
    pub fn set_version(&mut self, version: impl Into<Version>) -> &mut Self {
        match self.manifest_mut() {
            Manifest::Cargo(cargo) => cargo.package_mut().expect("package").set_version(version),
        };

        self
    }

    /// Bumps the package version.
    pub fn bump_version(&mut self, bump: impl Into<Bump>) -> Result<&mut Self, BumpError> {
        let mut version = self.version();

        bump.into().bump(&mut version)?;
        self.set_version(version);

        Ok(self)
    }

    /// Builds the package with the given version.
    pub fn with_version(mut self, version: impl Into<Version>) -> Self {
        self.set_version(version);
        self
    }

    /// Gets the package repository.
    pub fn repository(&self) -> Option<Url> {
        match self.manifest() {
            Manifest::Cargo(cargo) => cargo.package().expect("package").repository(),
        }
    }

    /// Sets the package repository.
    pub fn set_repository(&mut self, repository: impl Into<Url>) -> &mut Self {
        match self.manifest_mut() {
            Manifest::Cargo(cargo) => {
                cargo
                    .package_mut()
                    .expect("package")
                    .set_repository(repository);
            }
        }

        self
    }

    /// Builds the package with the given repository.
    pub fn with_repository(mut self, repository: impl Into<Url>) -> Self {
        self.set_repository(repository);
        self
    }

    /// Gets the package authors.
    pub fn authors(&self) -> Option<impl IntoIterator<Item = &str>> {
        match self.manifest() {
            Manifest::Cargo(cargo) => cargo.package().expect("package").authors(),
        }
    }

    /// Adds a package author.
    pub fn add_author(&mut self, author: impl Into<String>) -> &mut Self {
        match self.manifest_mut() {
            Manifest::Cargo(cargo) => {
                cargo.package_mut().expect("package").add_author(author);
            }
        }

        self
    }

    /// Builds the package with the given author.
    pub fn with_author(mut self, author: impl Into<String>) -> Self {
        self.add_author(author);
        self
    }

    /// Gets the package path.
    pub fn path(&self) -> &RelativePath {
        self.repository.path()
    }

    /// Gets the package manifest path.
    pub fn manifest_path(&self) -> RelativePathBuf {
        self.path().join(self.kind().file_name())
    }

    /// Gets the package kind.
    pub fn kind(&self) -> PackageKind {
        self.manifest.package_kind()
    }

    /// Checks if this is the primary package.
    ///
    /// A primary package shares the same name as the project and all releases
    /// are tagged under the version number without the package name prefix.
    pub fn is_primary(&self) -> bool {
        self.primary
    }
}

impl<T> Package<T> {
    /// Gets the package manifest.
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    /// Gets the mutable package manifest.
    ///
    /// Note that replacing the manifest with another kind is a logic error and
    /// the behavior is not specified. This will likely lead to incorrect
    /// results and panics.
    pub fn manifest_mut(&mut self) -> &mut Manifest {
        &mut self.manifest
    }
}

impl<T> Package<T>
where
    T: Repository,
{
    /// Gets the package changelog.
    pub fn changelog(&self) -> Option<Changelog> {
        self.get_file_as("CHANGELOG.md").ok().flatten()
    }
}

impl<T> Package<T>
where
    T: Stage,
{
    /// Adds a file to the package.
    pub fn add_file(
        &mut self,
        path: impl Into<RelativePathBuf>,
        file: impl Into<Bytes>,
    ) -> Result<&mut Self, Error<T::Error>> {
        self.repository
            .add_file(path, file)
            .map_err(Error::Repository)?;

        Ok(self)
    }

    /// Builds the package with the given file.
    pub fn with_file(
        mut self,
        path: impl Into<RelativePathBuf>,
        file: impl Into<Bytes>,
    ) -> Result<Self, Error<T::Error>> {
        self.add_file(path, file)?;

        Ok(self)
    }
}

impl<T> Package<T>
where
    T: Repository,
{
    /// Gets a file at the given path.
    pub fn get_file(
        &self,
        path: impl AsRef<RelativePath>,
    ) -> Result<Option<Bytes>, Error<T::Error>> {
        if path.as_ref() == self.kind().file_name() {
            return Ok(Some(self.manifest.to_string().into()));
        }

        self.repository.get_file(path).map_err(Error::Repository)
    }

    /// Gets a file at the given path in the specified format.
    #[allow(clippy::type_complexity)]
    pub fn get_file_as<U>(
        &self,
        path: impl AsRef<RelativePath>,
    ) -> Result<Option<U>, Either<Error<T::Error>, U::Err>>
    where
        U: FromStr,
    {
        match self.get_file(path).map_err(Either::Left)? {
            Some(bytes) => match std::str::from_utf8(&bytes) {
                Ok(str) => str.parse().map(Some).map_err(Either::Right),
                Err(err) => Err(Either::Left(Error::Utf8(err))),
            },
            None => Ok(None),
        }
    }
}

impl<T> Package<T> {
    /// Gets the dependency with the given name.
    pub fn get_dependency(&self, name: impl AsRef<str>) -> Option<DependencyRef<'_>> {
        self.manifest().get_dependency(name)
    }

    /// Gets the mutable dependency with the given name.
    pub fn get_dependency_mut(&mut self, name: impl AsRef<str>) -> Option<DependencyMut<'_>> {
        self.manifest_mut().get_dependency_mut(name)
    }

    /// Gets the dependencies.
    pub fn dependencies(&self) -> Dependencies<'_> {
        self.manifest().dependencies()
    }

    /// Gets the mutable dependencies.
    pub fn dependencies_mut(&mut self) -> DependenciesMut<'_> {
        self.manifest_mut().dependencies_mut()
    }
}

impl<T> Package<T> {
    /// Gets the dev dependency with the given name.
    pub fn get_dev_dependency(&self, name: impl AsRef<str>) -> Option<DependencyRef<'_>> {
        self.manifest().get_dev_dependency(name)
    }

    /// Gets the mutable dev dependency with the given name.
    pub fn get_dev_dependency_mut(&mut self, name: impl AsRef<str>) -> Option<DependencyMut<'_>> {
        self.manifest_mut().get_dev_dependency_mut(name)
    }

    /// Gets the dev dependencies.
    pub fn dev_dependencies(&self) -> Dependencies<'_> {
        self.manifest().dev_dependencies()
    }

    /// Gets the mutable dev dependencies.
    pub fn dev_dependencies_mut(&mut self) -> DependenciesMut<'_> {
        self.manifest_mut().dev_dependencies_mut()
    }
}

impl<T> Package<T> {
    /// Gets the build dependency with the given name.
    pub fn get_build_dependency(&self, name: impl AsRef<str>) -> Option<DependencyRef<'_>> {
        self.manifest().get_build_dependency(name)
    }

    /// Gets the mutable build dependency with the given name.
    pub fn get_build_dependency_mut(&mut self, name: impl AsRef<str>) -> Option<DependencyMut<'_>> {
        self.manifest_mut().get_build_dependency_mut(name)
    }

    /// Gets the build dependencies.
    pub fn build_dependencies(&self) -> Dependencies<'_> {
        self.manifest().build_dependencies()
    }

    /// Gets the mutable build dependencies.
    pub fn build_dependencies_mut(&mut self) -> DependenciesMut<'_> {
        self.manifest_mut().build_dependencies_mut()
    }
}

impl<T> Package<&T>
where
    T: Clone,
{
    /// Detaches the package from the backing repository.
    ///
    /// This allows a package obtained from an existing project to be modified
    /// by cloning the inner repository. The changes made to this package are
    /// not kept in sync with the project or original repository instance.
    ///
    /// Note that this will clone the entire repository including all staged
    /// changes across all files and packages. This is to ensure that any
    /// ability to access sibling packages or project configuration uses the
    /// state at the point where the package is detached. Otherwise, adding a
    /// new package, retrieving it, and then detaching it would leave the
    /// package in a state where it is no longer part of the workspace.
    pub fn detached(self) -> Package<T> {
        Package {
            repository: self.repository.detached(),
            manifest: self.manifest,
            primary: self.primary,
        }
    }
}

impl<T> Package<&mut T>
where
    T: Clone,
{
    /// Detaches the package from the backing repository.
    ///
    /// This allows a package obtained from an existing project to be modified
    /// by cloning the inner repository. The changes made to this package are
    /// not kept in sync with the project or original repository instance.
    ///
    /// Note that this will clone the entire repository including all staged
    /// changes across all files and packages. This is to ensure that any
    /// ability to access sibling packages or project configuration uses the
    /// state at the point where the package is detached. Otherwise, adding a
    /// new package, retrieving it, and then detaching it would leave the
    /// package in a state where it is no longer part of the workspace.
    pub fn detached(self) -> Package<T> {
        Package {
            repository: self.repository.detached(),
            manifest: self.manifest,
            primary: self.primary,
        }
    }
}

impl<T> Package<T>
where
    T: Remote,
{
    /// Requests the release of the specified package version.
    ///
    /// It does not yet support parallel release or hotfix branches and expects
    /// all development to be on the default branch in the repository settings.
    pub fn request_release(&self, version: impl Into<BumpOrVersion>) -> Result<(), T::Error> {
        let version = version.into();

        info!(
            package = self.name(),
            version = %self.version(),
            request = %version,
            "Requesting release"
        );

        self.repository
            .inner()
            .request_package_release(self.name(), version)?;

        Ok(())
    }

    /// Builds the changelog release for the given package version.
    ///
    /// This method queries the GitHub API to generate new release information
    /// and may differ to the existing release information or changelogs. This
    /// includes information for new releases as well as existing ones.
    ///
    /// It does not yet support parallel release or hotfix branches and expects
    /// all development to be on the default branch in the repository settings.
    pub fn build_release_notes(
        &self,
        version: impl Borrow<Version>,
    ) -> Result<crate::changelog::Release, T::Error> {
        self.repository.inner().get_changelog_release(
            self.name(),
            version.borrow(),
            self.is_primary(),
        )
    }
}

impl<T> Package<T>
where
    T: Repository,
{
    /// Constructs a package from a manifest.
    pub(super) fn from_manifest(
        project: &Project<T>,
        path: impl Into<RelativePathBuf>,
        manifest: Manifest,
    ) -> Option<Package<&T>> {
        let kind = manifest.package_kind();
        let primary = match kind {
            PackageKind::Cargo => {
                let pkg = manifest.try_as_cargo_ref()?.package()?;

                pkg.name() == project.name()
            }
        };

        Some(Package {
            repository: Subdirectory::new_unvalidated(&project.repository, path.into()),
            manifest: manifest.clone(),
            primary,
        })
    }
}

#[cfg(test)]
mod tests {
    use semver::Version;

    use super::{Package, PackageKind};

    #[test]
    fn test_package_builder() {
        let mut package = Package::new_cargo("example");

        assert_eq!(package.name(), "example");
        assert_eq!(package.description(), None);
        assert_eq!(package.version().to_string(), "0.0.0");
        assert_eq!(package.dependencies().into_iter().count(), 0);
        assert_eq!(package.dev_dependencies().into_iter().count(), 0);
        assert_eq!(package.build_dependencies().into_iter().count(), 0);
        assert_eq!(package.kind(), PackageKind::Cargo);
        assert_eq!(package.path(), "");

        package.set_version("0.1.0".parse::<Version>().unwrap());

        assert_eq!(package.version().to_string(), "0.1.0");
        assert_eq!(package.changelog(), None);

        package.add_file("hello-world.txt", "Hello World!").unwrap();

        let txt = package.get_file("hello-world.txt").unwrap();

        assert_eq!(txt, Some("Hello World!".into()));
    }
}