reinhardt-utils 0.1.0-rc.22

Utility functions aggregator for Reinhardt
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! System checks for static files configuration
//!
//! Validates static files configuration and provides warnings/errors
//! for common misconfigurations, similar to Django's check framework.

use super::StaticFilesConfig;

/// Severity level for a configuration check message.
#[derive(Debug, Clone, PartialEq)]
pub enum CheckLevel {
	/// Detailed diagnostic information.
	Debug,
	/// General informational note about the configuration.
	Info,
	/// A potential misconfiguration that may cause issues.
	Warning,
	/// A configuration error that should be fixed.
	Error,
	/// A severe misconfiguration that prevents proper operation.
	Critical,
}

/// A diagnostic message produced by a configuration check.
#[derive(Debug, Clone)]
pub struct CheckMessage {
	/// The severity level of this message.
	pub level: CheckLevel,
	/// A unique identifier for this check (e.g., `"static.E001"`).
	pub id: String,
	/// A human-readable description of the issue.
	pub message: String,
	/// An optional suggestion for how to fix the issue.
	pub hint: Option<String>,
}

impl CheckMessage {
	/// Documentation for `error`
	///
	pub fn error(id: impl Into<String>, message: impl Into<String>) -> Self {
		Self {
			level: CheckLevel::Error,
			id: id.into(),
			message: message.into(),
			hint: None,
		}
	}
	/// Documentation for `warning`
	///
	pub fn warning(id: impl Into<String>, message: impl Into<String>) -> Self {
		Self {
			level: CheckLevel::Warning,
			id: id.into(),
			message: message.into(),
			hint: None,
		}
	}
	/// Add a hint to the check message
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_utils::staticfiles::checks::CheckMessage;
	/// let msg = CheckMessage::error("E001", "Error").with_hint("Try this");
	/// ```
	pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
		self.hint = Some(hint.into());
		self
	}
}

/// Run all static files configuration checks
///
/// Returns a list of check messages indicating any configuration issues.
///
/// # Example
///
/// ```rust
/// use reinhardt_utils::staticfiles::checks::check_static_files_config;
/// use reinhardt_utils::staticfiles::storage::StaticFilesConfig;
/// use std::path::PathBuf;
///
/// let config = StaticFilesConfig {
///     static_root: PathBuf::from("/var/www/static"),
///     static_url: "/static/".to_string(),
///     staticfiles_dirs: vec![PathBuf::from("/app/static")],
///     media_url: None,
/// };
///
/// let messages = check_static_files_config(&config);
/// for message in messages {
///     println!("[{}] {}", message.id, message.message);
/// }
/// ```
pub fn check_static_files_config(config: &StaticFilesConfig) -> Vec<CheckMessage> {
	let mut messages = Vec::new();

	messages.extend(check_static_root(config));
	messages.extend(check_static_url(config));
	messages.extend(check_staticfiles_dirs(config));
	messages.extend(check_media_url_conflict(config));

	messages
}

/// Check STATIC_ROOT configuration
fn check_static_root(config: &StaticFilesConfig) -> Vec<CheckMessage> {
	let mut messages = Vec::new();

	// E001: STATIC_ROOT is not set
	if config.static_root.as_os_str().is_empty() {
		messages.push(
			CheckMessage::error("static.E001", "STATIC_ROOT setting is not set").with_hint(
				"Set STATIC_ROOT to a directory path where static files will be collected",
			),
		);
	}

	// W001: STATIC_ROOT is in STATICFILES_DIRS
	for dir in &config.staticfiles_dirs {
		if dir == &config.static_root {
			messages.push(
				CheckMessage::error(
					"static.E002",
					format!(
						"STATIC_ROOT ({}) is in STATICFILES_DIRS",
						config.static_root.display()
					),
				)
				.with_hint("STATIC_ROOT should be a separate directory from source directories"),
			);
		}

		// Check if STATIC_ROOT is a subdirectory of any STATICFILES_DIRS
		if config.static_root.starts_with(dir) {
			messages.push(
				CheckMessage::warning(
					"static.W001",
					format!(
						"STATIC_ROOT ({}) is a subdirectory of STATICFILES_DIRS entry ({})",
						config.static_root.display(),
						dir.display()
					),
				)
				.with_hint("This may cause files to be collected recursively"),
			);
		}
	}

	messages
}

/// Check STATIC_URL configuration
fn check_static_url(config: &StaticFilesConfig) -> Vec<CheckMessage> {
	let mut messages = Vec::new();

	// E003: STATIC_URL is empty
	if config.static_url.is_empty() {
		messages.push(
			CheckMessage::error("static.E003", "STATIC_URL setting is empty")
				.with_hint("Set STATIC_URL to a URL path like '/static/'"),
		);
	}

	// W002: STATIC_URL doesn't start with /
	if !config.static_url.is_empty() && !config.static_url.starts_with('/') {
		messages.push(
			CheckMessage::warning(
				"static.W002",
				format!(
					"STATIC_URL ('{}') doesn't start with '/'",
					config.static_url
				),
			)
			.with_hint("STATIC_URL should start with '/' for local serving"),
		);
	}

	// W003: STATIC_URL doesn't end with /
	if !config.static_url.is_empty() && !config.static_url.ends_with('/') {
		messages.push(
			CheckMessage::warning(
				"static.W003",
				format!("STATIC_URL ('{}') doesn't end with '/'", config.static_url),
			)
			.with_hint("STATIC_URL should end with '/' to avoid path issues"),
		);
	}

	messages
}

/// Check STATICFILES_DIRS configuration
fn check_staticfiles_dirs(config: &StaticFilesConfig) -> Vec<CheckMessage> {
	let mut messages = Vec::new();

	// W004: Empty STATICFILES_DIRS
	if config.staticfiles_dirs.is_empty() {
		messages.push(
			CheckMessage::warning("static.W004", "STATICFILES_DIRS is empty")
				.with_hint("Add source directories containing static files"),
		);
	}

	// W005: Directory doesn't exist
	for dir in &config.staticfiles_dirs {
		if !dir.exists() {
			messages.push(
				CheckMessage::warning(
					"static.W005",
					format!("STATICFILES_DIRS entry does not exist: {}", dir.display()),
				)
				.with_hint("Create the directory or remove it from STATICFILES_DIRS"),
			);
		} else if !dir.is_dir() {
			messages.push(CheckMessage::error(
				"static.E004",
				format!(
					"STATICFILES_DIRS entry is not a directory: {}",
					dir.display()
				),
			));
		}
	}

	// W006: Duplicate entries
	for (i, dir1) in config.staticfiles_dirs.iter().enumerate() {
		for dir2 in config.staticfiles_dirs.iter().skip(i + 1) {
			if dir1 == dir2 {
				messages.push(
					CheckMessage::warning(
						"static.W006",
						format!(
							"STATICFILES_DIRS contains duplicate entry: {}",
							dir1.display()
						),
					)
					.with_hint("Remove duplicate directory entries"),
				);
			}
		}
	}

	messages
}

/// Check for conflicts with MEDIA_URL (if present)
fn check_media_url_conflict(config: &StaticFilesConfig) -> Vec<CheckMessage> {
	let mut messages = Vec::new();

	// Check if MEDIA_URL is configured
	if let Some(media_url) = &config.media_url {
		// E004: STATIC_URL and MEDIA_URL are the same
		if config.static_url == *media_url {
			messages.push(
				CheckMessage::error("static.E004", "STATIC_URL and MEDIA_URL cannot be the same")
					.with_hint(
						"Use different URL paths for static and media files (e.g., '/static/' and '/media/')",
					),
			);
		}

		// W007: MEDIA_URL is not empty but doesn't start with /
		if !media_url.is_empty() && !media_url.starts_with('/') {
			messages.push(
				CheckMessage::warning("static.W007", "MEDIA_URL should start with a slash")
					.with_hint(format!(
						"Change MEDIA_URL from '{}' to '/{}'",
						media_url, media_url
					)),
			);
		}

		// W008: MEDIA_URL is not empty but doesn't end with /
		if !media_url.is_empty() && !media_url.ends_with('/') {
			messages.push(
				CheckMessage::warning("static.W008", "MEDIA_URL should end with a slash")
					.with_hint(format!(
						"Change MEDIA_URL from '{}' to '{}'",
						media_url,
						if media_url.ends_with('/') {
							media_url.to_string()
						} else {
							format!("{}/", media_url)
						}
					)),
			);
		}

		// W009: MEDIA_URL is a prefix of STATIC_URL or vice versa
		if config.static_url.starts_with(media_url) || media_url.starts_with(&config.static_url) {
			messages.push(
				CheckMessage::warning(
					"static.W009",
					"MEDIA_URL should not be a prefix of STATIC_URL or vice versa",
				)
				.with_hint("Use distinct URL paths to avoid routing conflicts"),
			);
		}
	}

	messages
}

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

	#[test]
	fn test_check_static_root_not_set() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from(""),
			static_url: "/static/".to_string(),
			staticfiles_dirs: vec![],
			media_url: None,
		};

		let messages = check_static_root(&config);
		assert_eq!(messages.len(), 1);
		assert_eq!(messages[0].id, "static.E001");
		assert_eq!(messages[0].level, CheckLevel::Error);
	}

	#[test]
	fn test_check_static_root_in_staticfiles_dirs() {
		let root = PathBuf::from("/var/www/static");
		let config = StaticFilesConfig {
			static_root: root.clone(),
			static_url: "/static/".to_string(),
			staticfiles_dirs: vec![root],
			media_url: None,
		};

		let messages = check_static_root(&config);
		assert!(messages.iter().any(|m| m.id == "static.E002"));
	}

	#[test]
	fn test_check_static_root_subdirectory() {
		let temp_dir = TempDir::new().unwrap();
		let parent = temp_dir.path().to_path_buf();
		let child = parent.join("collected");

		let config = StaticFilesConfig {
			static_root: child,
			static_url: "/static/".to_string(),
			staticfiles_dirs: vec![parent],
			media_url: None,
		};

		let messages = check_static_root(&config);
		assert!(messages.iter().any(|m| m.id == "static.W001"));
	}

	#[test]
	fn test_check_static_url_empty() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: String::new(),
			staticfiles_dirs: vec![],
			media_url: None,
		};

		let messages = check_static_url(&config);
		assert!(messages.iter().any(|m| m.id == "static.E003"));
	}

	#[test]
	fn test_check_static_url_no_leading_slash() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "static/".to_string(),
			staticfiles_dirs: vec![],
			media_url: None,
		};

		let messages = check_static_url(&config);
		assert!(messages.iter().any(|m| m.id == "static.W002"));
	}

	#[test]
	fn test_check_static_url_no_trailing_slash() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static".to_string(),
			staticfiles_dirs: vec![],
			media_url: None,
		};

		let messages = check_static_url(&config);
		assert!(messages.iter().any(|m| m.id == "static.W003"));
	}

	#[test]
	fn test_check_staticfiles_dirs_empty() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: vec![],
			media_url: None,
		};

		let messages = check_staticfiles_dirs(&config);
		assert!(messages.iter().any(|m| m.id == "static.W004"));
	}

	#[test]
	fn test_check_staticfiles_dirs_not_exist() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: vec![PathBuf::from("/nonexistent/path")],
			media_url: None,
		};

		let messages = check_staticfiles_dirs(&config);
		assert!(messages.iter().any(|m| m.id == "static.W005"));
	}

	#[test]
	fn test_check_staticfiles_dirs_duplicate() {
		let dir = PathBuf::from("/app/static");
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: vec![dir.clone(), dir],
			media_url: None,
		};

		let messages = check_staticfiles_dirs(&config);
		assert!(messages.iter().any(|m| m.id == "static.W006"));
	}

	#[test]
	fn test_valid_configuration() {
		let temp_dir = TempDir::new().unwrap();
		let source_dir = temp_dir.path().join("source");
		std::fs::create_dir(&source_dir).unwrap();

		let config = StaticFilesConfig {
			static_root: temp_dir.path().join("collected"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: vec![source_dir],
			media_url: None,
		};

		let messages = check_static_files_config(&config);
		// Should have no errors, only the "collected doesn't exist" warning is acceptable
		let errors: Vec<_> = messages
			.iter()
			.filter(|m| m.level == CheckLevel::Error || m.level == CheckLevel::Critical)
			.collect();
		assert_eq!(errors.len(), 0);
	}

	#[test]
	fn test_media_url_same_as_static_url() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: Vec::new(),
			media_url: Some("/static/".to_string()),
		};

		let messages = check_media_url_conflict(&config);
		assert!(messages.iter().any(|m| m.id == "static.E004"));
	}

	#[test]
	fn test_media_url_no_leading_slash() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: Vec::new(),
			media_url: Some("media/".to_string()),
		};

		let messages = check_media_url_conflict(&config);
		assert!(messages.iter().any(|m| m.id == "static.W007"));
	}

	#[test]
	fn test_media_url_no_trailing_slash() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: Vec::new(),
			media_url: Some("/media".to_string()),
		};

		let messages = check_media_url_conflict(&config);
		assert!(messages.iter().any(|m| m.id == "static.W008"));
	}

	#[test]
	fn test_media_url_prefix_conflict() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: Vec::new(),
			media_url: Some("/static/media/".to_string()),
		};

		let messages = check_media_url_conflict(&config);
		assert!(messages.iter().any(|m| m.id == "static.W009"));
	}

	#[test]
	fn test_media_url_valid() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: Vec::new(),
			media_url: Some("/media/".to_string()),
		};

		let messages = check_media_url_conflict(&config);
		assert_eq!(messages.len(), 0);
	}

	#[test]
	fn test_media_url_none() {
		let config = StaticFilesConfig {
			static_root: PathBuf::from("/var/www/static"),
			static_url: "/static/".to_string(),
			staticfiles_dirs: Vec::new(),
			media_url: None,
		};

		let messages = check_media_url_conflict(&config);
		assert_eq!(messages.len(), 0);
	}
}