Skip to main content

rsynko_rsync/
observation.rs

1use crate::*;
2use alux_ext::ext;
3use ambassador::delegatable_trait;
4use rsynko_manager::ChangeKind;
5
6/// Provides the carrier and constructor for one path a transfer would change.
7#[delegatable_trait]
8pub trait SyncChangeAlg: RsyncSorts {
9    /// Defines one change from the path it names, what happens to it, and what it moves.
10    fn sync_change(&self, path: impl Into<String>, kind: ChangeKind, size: Option<u64>) -> Self::Change;
11}
12
13/// Provides the carriers and constructors for what a running transfer states.
14#[delegatable_trait]
15pub trait SyncObservationAlg: RsyncSorts {
16    /// Defines the observation of one path the transfer would change, or has changed.
17    fn observed_change(&self, change: Self::Change) -> Self::Observation;
18    /// Defines the observation of how far the whole transfer has come.
19    fn observed_progress(&self, transferred: u64, percent: u16) -> Self::Observation;
20    /// Defines the observation of a line naming nothing this specification reads.
21    fn observed_nothing(&self) -> Self::Observation;
22}
23
24/// Specifies what one observation of a running transfer states.
25#[delegatable_trait]
26pub trait SyncObservationViewAlg: RsyncSorts {
27    /// Observes the changed path, exactly when the observation states one.
28    fn observation_change<'a>(&self, observation: &'a Self::Observation) -> Option<&'a Self::Change>;
29    /// Observes the bytes moved and the share completed, exactly when the observation states them.
30    fn observation_progress(&self, observation: &Self::Observation) -> Option<(u64, u16)>;
31}
32
33/// Names the mark a removal states instead of a change flag.
34pub const DELETION_MARK: &str = "*deleting";
35
36/// Names the field separator each stated path is written with.
37pub const FIELD_MARK: char = '|';
38
39/// Derives what one line a running transfer wrote states.
40#[ext(name = SyncReadExt)]
41pub impl<This> This
42where
43    This: SyncChangeAlg + SyncObservationAlg,
44{
45    /// Reads one line the transfer program wrote as what it states.
46    ///
47    /// A change is stated in three fields: the flags naming what happens, the byte count, and the
48    /// path. Anything else on the stream is progress, or is nothing this specification reads.
49    fn read_sync_line(&self, line: &str) -> This::Observation {
50        let line = line.trim_end();
51        if let Some(change) = self.read_sync_change(line) {
52            return self.observed_change(change);
53        }
54        read_advance(line).map_or_else(
55            || self.observed_nothing(),
56            |(transferred, percent)| self.observed_progress(transferred, percent),
57        )
58    }
59
60    /// Reads one itemized line as the change it denotes, and states nothing for a line naming
61    /// only that a folder was opened on the way to what is inside it.
62    fn read_sync_change(&self, line: &str) -> Option<This::Change> {
63        let mut fields = line.splitn(3, FIELD_MARK);
64        let flags = fields.next()?.trim();
65        let size = fields.next()?.trim();
66        let path = fields.next()?.trim();
67        if path.is_empty() || touches_folder(flags) {
68            return None;
69        }
70        let kind = read_kind(flags)?;
71        // A removal is stated without a size, because the transfer never looked at what it holds.
72        let size = (kind != ChangeKind::Delete).then(|| read_count(size)).flatten();
73        Some(self.sync_change(path, kind, size))
74    }
75}
76
77/// Observes whether the flags name a folder that is only having its own attributes brought up
78/// to date.
79///
80/// Transferring a folder's contents restates the folder itself, which a reader has already been
81/// told about by the paths inside it. A folder that did not exist before is stated as it is.
82fn touches_folder(flags: &str) -> bool {
83    let mut marks = flags.chars();
84    let happening = marks.next();
85    let kind_of_path = marks.next();
86    matches!(kind_of_path, Some('d'))
87        && matches!(happening, Some('.' | 'c' | '>' | '<'))
88        && !marks.as_str().starts_with("+++")
89}
90
91/// Reads the itemized flags as what would happen to the path they name.
92///
93/// A removal states itself in words. Everything else states eleven marks: what is happening, what
94/// kind of path it is, and then one mark per attribute that differs. All-new content states
95/// pluses; nothing differing states dots.
96fn read_kind(flags: &str) -> Option<ChangeKind> {
97    if flags.starts_with(DELETION_MARK) {
98        return Some(ChangeKind::Delete);
99    }
100    let mut marks = flags.chars();
101    let happening = marks.next()?;
102    if !matches!(happening, '<' | '>' | 'c' | 'h' | '.') {
103        return None;
104    }
105    let _kind_of_path = marks.next()?;
106    let attributes = marks.as_str();
107    if attributes.starts_with("+++") {
108        return Some(ChangeKind::Create);
109    }
110    if happening == '.' && attributes.chars().all(|mark| mark == '.' || mark == ' ') {
111        return Some(ChangeKind::Unchanged);
112    }
113    Some(ChangeKind::Update)
114}
115
116/// Reads one progress line as the bytes it has moved and the share it has completed.
117fn read_advance(line: &str) -> Option<(u64, u16)> {
118    let mut fields = line.split_whitespace();
119    let transferred = read_count(fields.next()?)?;
120    let percent = fields.next()?.strip_suffix('%')?.parse::<u16>().ok()?;
121    Some((transferred, percent.min(100)))
122}
123
124/// Reads a count the transfer program wrote, which it groups for a reader.
125fn read_count(text: &str) -> Option<u64> {
126    let digits = text.replace([',', '.', '\u{a0}'], "");
127    (!digits.is_empty() && digits.chars().all(|digit| digit.is_ascii_digit())).then(|| digits.parse().ok()).flatten()
128}