cull-gmail 0.1.8

Cull emails from a gmail account using the gmail API
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
//! Unit tests for init CLI functionality.

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

    /// Test helper to create a mock credential file
    fn create_mock_credential_file(dir: &Path) -> std::io::Result<()> {
        let credential_content = r#"{
            "installed": {
                "client_id": "test-client-id.googleusercontent.com",
                "client_secret": "test-client-secret",
                "auth_uri": "https://accounts.google.com/o/oauth2/auth",
                "token_uri": "https://oauth2.googleapis.com/token",
                "redirect_uris": ["http://localhost"]
            }
        }"#;
        fs::write(dir.join("credential.json"), credential_content)
    }

    /// Test helper to create a default InitCli instance
    fn create_test_init_cli() -> InitCli {
        InitCli {
            rules_dir: None,
            config_dir: "test".to_string(),
            credential_file: None,
            force: false,
            dry_run: false,
            interactive: false,
            skip_rules: false,
        }
    }

    /// Test helper to create an InitCli instance with force enabled
    fn create_test_init_cli_with_force() -> InitCli {
        InitCli {
            rules_dir: None,
            config_dir: "test".to_string(),
            credential_file: None,
            force: true,
            dry_run: false,
            interactive: false,
            skip_rules: false,
        }
    }

    #[test]
    fn test_parse_config_root_home() {
        let result = parse_config_root("h:.test-config");
        let home = env::home_dir().unwrap_or_default();
        assert_eq!(result, home.join(".test-config"));
    }

    #[test]
    fn test_parse_config_root_current() {
        let result = parse_config_root("c:.test-config");
        let current = env::current_dir().unwrap_or_default();
        assert_eq!(result, current.join(".test-config"));
    }

    #[test]
    fn test_parse_config_root_root() {
        let result = parse_config_root("r:etc/cull-gmail");
        assert_eq!(result, std::path::PathBuf::from("/etc/cull-gmail"));
    }

    #[test]
    fn test_parse_config_root_no_prefix() {
        let result = parse_config_root("/absolute/path");
        assert_eq!(result, std::path::PathBuf::from("/absolute/path"));
    }

    #[test]
    fn test_init_defaults() {
        assert_eq!(InitDefaults::credential_filename(), "credential.json");
        assert_eq!(InitDefaults::config_filename(), "cull-gmail.toml");
        assert_eq!(InitDefaults::rules_filename(), "rules.toml");
        assert_eq!(InitDefaults::token_dir_name(), "gmail1");

        // Test that config content contains expected keys
        let config_content = InitDefaults::CONFIG_FILE_CONTENT;
        assert!(config_content.contains("credential_file = \"credential.json\""));
        assert!(config_content.contains("config_root = \"h:.cull-gmail\""));
        assert!(config_content.contains("execute = false"));

        // Test that rules content is a valid template
        let rules_content = InitDefaults::RULES_FILE_CONTENT;
        assert!(rules_content.contains("# Example rules for cull-gmail"));
        assert!(rules_content.contains("older_than:30d"));
    }

    #[test]
    fn test_validate_credential_file_success() {
        let temp_dir = TempDir::new().unwrap();
        create_mock_credential_file(temp_dir.path()).unwrap();

        let init_cli = create_test_init_cli();

        let credential_path = temp_dir.path().join("credential.json");
        let result = init_cli.validate_credential_file(&credential_path);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_credential_file_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let init_cli = create_test_init_cli();

        let nonexistent_path = temp_dir.path().join("nonexistent.json");
        let result = init_cli.validate_credential_file(&nonexistent_path);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[test]
    fn test_validate_credential_file_invalid_json() {
        let temp_dir = TempDir::new().unwrap();
        let credential_path = temp_dir.path().join("invalid.json");
        fs::write(&credential_path, "invalid json content").unwrap();

        let init_cli = create_test_init_cli();

        let result = init_cli.validate_credential_file(&credential_path);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Invalid credential file format")
        );
    }

    #[test]
    fn test_plan_operations_new_setup() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("new-config");

        let init_cli = create_test_init_cli();

        let operations = init_cli.plan_operations(&config_path, None).unwrap();

        // Should have: CreateDir, WriteFile (config), WriteFile (rules), EnsureTokenDir
        assert_eq!(operations.len(), 4);

        match &operations[0] {
            Operation::CreateDir { path, .. } => {
                assert_eq!(path, &config_path);
            }
            _ => panic!("Expected CreateDir operation"),
        }

        match &operations[1] {
            Operation::WriteFile { path, contents, .. } => {
                assert_eq!(path, &config_path.join("cull-gmail.toml"));
                assert!(contents.contains("credential_file = \"credential.json\""));
            }
            _ => panic!("Expected WriteFile operation for config"),
        }

        match &operations[2] {
            Operation::WriteFile { path, contents, .. } => {
                assert_eq!(path, &config_path.join("rules.toml"));
                assert!(contents.contains("# Example rules for cull-gmail"));
            }
            _ => panic!("Expected WriteFile operation for rules"),
        }

        match &operations[3] {
            Operation::EnsureTokenDir { path, .. } => {
                assert_eq!(path, &config_path.join("gmail1"));
            }
            _ => panic!("Expected EnsureTokenDir operation"),
        }
    }

    #[test]
    fn test_plan_operations_with_credential_file() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("new-config");
        let cred_path = temp_dir.path().join("cred.json");
        create_mock_credential_file(temp_dir.path()).unwrap();
        fs::rename(temp_dir.path().join("credential.json"), &cred_path).unwrap();

        let init_cli = create_test_init_cli();

        let operations = init_cli
            .plan_operations(&config_path, Some(&cred_path))
            .unwrap();

        // Should have: CreateDir, CopyFile (credential), WriteFile (config), WriteFile (rules), EnsureTokenDir, RunOAuth2
        assert_eq!(operations.len(), 6);

        // Check that CopyFile operation exists
        let copy_op = operations
            .iter()
            .find(|op| matches!(op, Operation::CopyFile { .. }));
        assert!(copy_op.is_some());

        // Check that RunOAuth2 operation exists
        let oauth_op = operations
            .iter()
            .find(|op| matches!(op, Operation::RunOAuth2 { .. }));
        assert!(oauth_op.is_some());
    }

    #[test]
    fn test_plan_operations_existing_config_no_force() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("existing-config");
        fs::create_dir_all(&config_path).unwrap();

        // Create existing config file
        fs::write(config_path.join("cull-gmail.toml"), "existing config").unwrap();

        let init_cli = create_test_init_cli();

        let result = init_cli.plan_operations(&config_path, None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("already exists"));
    }

    #[test]
    fn test_plan_operations_existing_config_with_force() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("existing-config");
        fs::create_dir_all(&config_path).unwrap();

        // Create existing config file
        fs::write(config_path.join("cull-gmail.toml"), "existing config").unwrap();
        fs::write(config_path.join("rules.toml"), "existing rules").unwrap();

        let init_cli = create_test_init_cli_with_force();

        let operations = init_cli.plan_operations(&config_path, None).unwrap();

        // Should succeed and plan backup operations
        let config_op = operations.iter().find(|op| {
            if let Operation::WriteFile {
                path,
                backup_if_exists,
                ..
            } = op
            {
                path.file_name().unwrap() == "cull-gmail.toml" && *backup_if_exists
            } else {
                false
            }
        });
        assert!(config_op.is_some());
    }

    #[test]
    fn test_create_backup() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let init_cli = create_test_init_cli();

        let result = init_cli.create_backup(&test_file);
        assert!(result.is_ok());

        // Check that a backup file was created
        let backup_files: Vec<_> = fs::read_dir(temp_dir.path())
            .unwrap()
            .filter_map(|entry| {
                let entry = entry.ok()?;
                let name = entry.file_name().to_string_lossy().to_string();
                if name.starts_with("test.bak-") {
                    Some(name)
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(backup_files.len(), 1);

        // Verify backup content
        let backup_path = temp_dir.path().join(&backup_files[0]);
        let backup_content = fs::read_to_string(backup_path).unwrap();
        assert_eq!(backup_content, "test content");
    }

    #[cfg(unix)]
    #[test]
    fn test_set_permissions() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        let init_cli = create_test_init_cli();

        let result = init_cli.set_permissions(&test_file, 0o600);
        assert!(result.is_ok());

        let metadata = fs::metadata(&test_file).unwrap();
        let permissions = metadata.permissions();
        assert_eq!(permissions.mode() & 0o777, 0o600);
    }

    #[test]
    fn test_operation_display() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().join("test");

        let create_dir_op = Operation::CreateDir {
            path: temp_path.clone(),
            #[cfg(unix)]
            mode: Some(0o755),
        };
        assert_eq!(
            format!("{create_dir_op}"),
            format!("Create directory: {}", temp_path.display())
        );

        let copy_file_op = Operation::CopyFile {
            from: temp_path.clone(),
            to: temp_path.join("dest"),
            #[cfg(unix)]
            mode: Some(0o600),
            backup_if_exists: false,
        };
        assert_eq!(
            format!("{copy_file_op}"),
            format!(
                "Copy file: {} → {}",
                temp_path.display(),
                temp_path.join("dest").display()
            )
        );

        let write_file_op = Operation::WriteFile {
            path: temp_path.clone(),
            contents: "content".to_string(),
            #[cfg(unix)]
            mode: Some(0o644),
            backup_if_exists: false,
        };
        assert_eq!(
            format!("{write_file_op}"),
            format!("Write file: {}", temp_path.display())
        );

        let oauth_op = Operation::RunOAuth2 {
            config_root: "h:.config".to_string(),
            credential_file: Some("cred.json".to_string()),
        };
        assert_eq!(format!("{oauth_op}"), "Run OAuth2 authentication flow");
    }

    #[cfg(unix)]
    #[test]
    fn test_operation_get_mode() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path().join("test");

        let create_dir_op = Operation::CreateDir {
            path: temp_path.clone(),
            mode: Some(0o755),
        };
        assert_eq!(create_dir_op.get_mode(), Some(0o755));

        let oauth_op = Operation::RunOAuth2 {
            config_root: "h:.config".to_string(),
            credential_file: Some("cred.json".to_string()),
        };
        assert_eq!(oauth_op.get_mode(), None);
    }

    #[test]
    fn test_plan_operations_with_skip_rules_no_rules_file() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("new-config");

        let init_cli = InitCli {
            rules_dir: None,
            config_dir: "test".to_string(),
            credential_file: None,
            force: false,
            dry_run: false,
            interactive: false,
            skip_rules: true,
        };

        let operations = init_cli.plan_operations(&config_path, None).unwrap();

        // Should have: CreateDir, WriteFile (config only, no rules), EnsureTokenDir
        assert_eq!(operations.len(), 3);

        // Verify no WriteFile operation for rules.toml
        let has_rules_write = operations.iter().any(|op| {
            if let Operation::WriteFile { path, .. } = op {
                path.file_name().unwrap() == "rules.toml"
            } else {
                false
            }
        });
        assert!(
            !has_rules_write,
            "rules.toml should not be written when skip_rules is true"
        );
    }

    #[test]
    fn test_plan_operations_with_skip_rules_and_rules_dir() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config");

        let init_cli = InitCli {
            rules_dir: Some("c:rules".to_string()),
            config_dir: "test".to_string(),
            credential_file: None,
            force: false,
            dry_run: false,
            interactive: false,
            skip_rules: true,
        };

        let operations = init_cli.plan_operations(&config_path, None).unwrap();

        // Should have: CreateDir (config), CreateDir (rules), WriteFile (config only), EnsureTokenDir
        // The rules directory should still be created even though the file isn't
        let rules_dir_created = operations.iter().any(|op| {
            if let Operation::CreateDir { path, .. } = op {
                path.ends_with("rules")
            } else {
                false
            }
        });
        assert!(rules_dir_created, "Rules directory should still be created");

        // Verify no WriteFile operation for rules.toml
        let has_rules_write = operations.iter().any(|op| {
            if let Operation::WriteFile { path, .. } = op {
                path.file_name().unwrap() == "rules.toml"
            } else {
                false
            }
        });
        assert!(
            !has_rules_write,
            "rules.toml should not be written when skip_rules is true"
        );
    }

    #[test]
    fn test_config_content_has_skip_rules_comment() {
        // Test that config content includes skip-rules comment
        let content_with_skip = InitDefaults::config_content_with_skip_rules("rules.toml");

        assert!(
            content_with_skip
                .contains("NOTE: rules.toml creation was skipped via --skip-rules flag")
        );
        assert!(content_with_skip.contains("expected to be provided externally"));
        assert!(content_with_skip.contains("rules = \"rules.toml\""));
    }

    #[test]
    fn test_config_content_skip_rules_with_custom_path() {
        let custom_path = "/mnt/rules/rules.toml";
        let content_with_skip = InitDefaults::config_content_with_skip_rules(custom_path);

        assert!(
            content_with_skip
                .contains("NOTE: rules.toml creation was skipped via --skip-rules flag")
        );
        assert!(content_with_skip.contains(&format!("rules = \"{custom_path}\"")));
    }
}