msy 0.4.2

Modern musl rsync alternative - Fast, parallel file synchronization
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
use crate::error::Result;
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Command;
use std::time::Duration;

/// Type of hook to execute
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookType {
    PreSync,
    PostSync,
}

impl HookType {
    fn file_name(&self) -> &str {
        match self {
            HookType::PreSync => "pre-sync",
            HookType::PostSync => "post-sync",
        }
    }
}

/// Context passed to hooks via environment variables
#[derive(Debug, Clone)]
pub struct HookContext {
    pub source: String,
    pub destination: String,
    pub files_scanned: usize,
    pub files_created: usize,
    pub files_updated: usize,
    pub files_deleted: usize,
    pub files_skipped: usize,
    pub bytes_transferred: u64,
    pub duration_secs: u64,
    pub dry_run: bool,
}

impl HookContext {
    pub fn to_env_vars(&self) -> HashMap<String, String> {
        let mut vars = HashMap::new();
        vars.insert("SY_SOURCE".to_string(), self.source.clone());
        vars.insert("SY_DESTINATION".to_string(), self.destination.clone());
        vars.insert(
            "SY_FILES_SCANNED".to_string(),
            self.files_scanned.to_string(),
        );
        vars.insert(
            "SY_FILES_CREATED".to_string(),
            self.files_created.to_string(),
        );
        vars.insert(
            "SY_FILES_UPDATED".to_string(),
            self.files_updated.to_string(),
        );
        vars.insert(
            "SY_FILES_DELETED".to_string(),
            self.files_deleted.to_string(),
        );
        vars.insert(
            "SY_FILES_SKIPPED".to_string(),
            self.files_skipped.to_string(),
        );
        vars.insert(
            "SY_BYTES_TRANSFERRED".to_string(),
            self.bytes_transferred.to_string(),
        );
        vars.insert(
            "SY_DURATION_SECS".to_string(),
            self.duration_secs.to_string(),
        );
        vars.insert(
            "SY_DRY_RUN".to_string(),
            if self.dry_run { "1" } else { "0" }.to_string(),
        );
        vars
    }
}

/// Hook execution result
#[derive(Debug)]
#[allow(dead_code)] // Public API for hook execution results
pub struct HookResult {
    pub hook_type: HookType,
    pub path: PathBuf,
    pub success: bool,
    pub exit_code: Option<i32>,
    pub stdout: String,
    pub stderr: String,
    pub duration: Duration,
}

/// Hook executor
pub struct HookExecutor {
    hooks_dir: PathBuf,
    abort_on_failure: bool,
}

impl HookExecutor {
    pub fn new() -> Result<Self> {
        let hooks_dir = Self::default_hooks_dir()?;
        Ok(Self {
            hooks_dir,
            abort_on_failure: false,
        })
    }

    pub fn with_abort_on_failure(mut self, abort: bool) -> Self {
        self.abort_on_failure = abort;
        self
    }

    fn default_hooks_dir() -> Result<PathBuf> {
        // Use XDG_CONFIG_HOME or fallback to ~/.config
        let config_dir = dirs::config_dir().ok_or_else(|| {
            crate::error::SyncError::Config("Could not determine config directory".to_string())
        })?;
        Ok(config_dir.join("sy").join("hooks"))
    }

    /// Find hook script for given type
    fn find_hook(&self, hook_type: HookType) -> Option<PathBuf> {
        let base_name = hook_type.file_name();

        // Try common extensions
        let extensions = if cfg!(windows) {
            vec!["bat", "cmd", "ps1", "exe"]
        } else {
            vec!["sh", "bash", "zsh", "fish", ""]
        };

        for ext in extensions {
            let file_name = if ext.is_empty() {
                base_name.to_string()
            } else {
                format!("{}.{}", base_name, ext)
            };

            let path = self.hooks_dir.join(&file_name);
            if path.exists() && path.is_file() {
                // Check if executable (Unix-like systems)
                #[cfg(unix)]
                {
                    use std::os::unix::fs::PermissionsExt;
                    if let Ok(metadata) = path.metadata() {
                        let permissions = metadata.permissions();
                        if permissions.mode() & 0o111 == 0 {
                            tracing::warn!("Hook found but not executable: {}", path.display());
                            continue;
                        }
                    }
                }

                return Some(path);
            }
        }

        None
    }

    /// Execute a hook with given context
    pub fn execute(
        &self,
        hook_type: HookType,
        context: &HookContext,
    ) -> Result<Option<HookResult>> {
        let hook_path = match self.find_hook(hook_type) {
            Some(path) => path,
            None => {
                tracing::debug!(
                    "No {:?} hook found in {}",
                    hook_type,
                    self.hooks_dir.display()
                );
                return Ok(None);
            }
        };

        tracing::info!("Executing {:?} hook: {}", hook_type, hook_path.display());

        let start = std::time::Instant::now();

        // Build command
        let mut cmd = Command::new(&hook_path);

        // Add environment variables
        for (key, value) in context.to_env_vars() {
            cmd.env(key, value);
        }

        // Execute with timeout (default 30 seconds)
        let output = match cmd.output() {
            Ok(output) => output,
            Err(e) => {
                let err_msg = format!("Failed to execute hook {}: {}", hook_path.display(), e);
                tracing::error!("{}", err_msg);

                if self.abort_on_failure {
                    return Err(crate::error::SyncError::Hook(err_msg));
                }

                return Ok(Some(HookResult {
                    hook_type,
                    path: hook_path,
                    success: false,
                    exit_code: None,
                    stdout: String::new(),
                    stderr: err_msg,
                    duration: start.elapsed(),
                }));
            }
        };

        let duration = start.elapsed();
        let success = output.status.success();
        let exit_code = output.status.code();
        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();

        if !success {
            tracing::warn!(
                "Hook {:?} failed with exit code {:?}: {}",
                hook_type,
                exit_code,
                hook_path.display()
            );

            if !stderr.is_empty() {
                tracing::warn!("Hook stderr: {}", stderr);
            }

            if self.abort_on_failure {
                return Err(crate::error::SyncError::Hook(format!(
                    "Hook {:?} failed with exit code {:?}",
                    hook_type, exit_code
                )));
            }
        } else {
            tracing::info!(
                "Hook {:?} completed successfully in {:?}",
                hook_type,
                duration
            );

            if !stdout.is_empty() {
                tracing::debug!("Hook stdout: {}", stdout);
            }
        }

        Ok(Some(HookResult {
            hook_type,
            path: hook_path,
            success,
            exit_code,
            stdout,
            stderr,
            duration,
        }))
    }
}

impl Default for HookExecutor {
    fn default() -> Self {
        Self::new().unwrap_or_else(|_| Self {
            hooks_dir: PathBuf::from("/dev/null"),
            abort_on_failure: false,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_hook_context_env_vars() {
        let context = HookContext {
            source: "/src".to_string(),
            destination: "/dst".to_string(),
            files_scanned: 100,
            files_created: 10,
            files_updated: 5,
            files_deleted: 2,
            files_skipped: 83,
            bytes_transferred: 1024,
            duration_secs: 30,
            dry_run: false,
        };

        let vars = context.to_env_vars();
        assert_eq!(vars.get("SY_SOURCE").unwrap(), "/src");
        assert_eq!(vars.get("SY_DESTINATION").unwrap(), "/dst");
        assert_eq!(vars.get("SY_FILES_SCANNED").unwrap(), "100");
        assert_eq!(vars.get("SY_FILES_CREATED").unwrap(), "10");
        assert_eq!(vars.get("SY_DRY_RUN").unwrap(), "0");
    }

    #[test]
    fn test_hook_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let executor = HookExecutor {
            hooks_dir: temp_dir.path().to_path_buf(),
            abort_on_failure: false,
        };

        let context = HookContext {
            source: "/src".to_string(),
            destination: "/dst".to_string(),
            files_scanned: 0,
            files_created: 0,
            files_updated: 0,
            files_deleted: 0,
            files_skipped: 0,
            bytes_transferred: 0,
            duration_secs: 0,
            dry_run: false,
        };

        let result = executor.execute(HookType::PreSync, &context).unwrap();
        assert!(result.is_none());
    }

    #[cfg(unix)]
    #[test]
    fn test_hook_execution() {
        let temp_dir = TempDir::new().unwrap();
        let hook_path = temp_dir.path().join("pre-sync.sh");

        // Create a simple hook that echoes environment variables
        fs::write(
            &hook_path,
            "#!/bin/sh\necho \"Source: $SY_SOURCE\"\necho \"Files: $SY_FILES_SCANNED\"\n",
        )
        .unwrap();

        // Make executable
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&hook_path).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&hook_path, perms).unwrap();
        }

        let executor = HookExecutor {
            hooks_dir: temp_dir.path().to_path_buf(),
            abort_on_failure: false,
        };

        let context = HookContext {
            source: "/test/src".to_string(),
            destination: "/test/dst".to_string(),
            files_scanned: 42,
            files_created: 0,
            files_updated: 0,
            files_deleted: 0,
            files_skipped: 0,
            bytes_transferred: 0,
            duration_secs: 0,
            dry_run: false,
        };

        let result = executor.execute(HookType::PreSync, &context).unwrap();
        assert!(result.is_some());

        let hook_result = result.unwrap();
        assert!(hook_result.success);
        assert!(hook_result.stdout.contains("/test/src"));
        assert!(hook_result.stdout.contains("42"));
    }

    #[cfg(unix)]
    #[test]
    fn test_hook_failure_abort() {
        let temp_dir = TempDir::new().unwrap();
        let hook_path = temp_dir.path().join("pre-sync.sh");

        // Create a hook that fails
        fs::write(&hook_path, "#!/bin/sh\nexit 1\n").unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&hook_path).unwrap().permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&hook_path, perms).unwrap();
        }

        let executor = HookExecutor {
            hooks_dir: temp_dir.path().to_path_buf(),
            abort_on_failure: true,
        };

        let context = HookContext {
            source: "/src".to_string(),
            destination: "/dst".to_string(),
            files_scanned: 0,
            files_created: 0,
            files_updated: 0,
            files_deleted: 0,
            files_skipped: 0,
            bytes_transferred: 0,
            duration_secs: 0,
            dry_run: false,
        };

        let result = executor.execute(HookType::PreSync, &context);
        assert!(result.is_err());
    }
}