Files

81 lines
2.4 KiB
Dart

import '../../../core/api_gateway.dart';
JsonMap storageMap(Object? value) =>
value is Map ? Map<String, dynamic>.from(value) : <String, dynamic>{};
int storageInt(Object? value) => value is num ? value.toInt() : 0;
List<JsonMap> storageRows(Object? value) =>
value is List ? value.whereType<Map>().map(storageMap).toList() : const [];
class StoragePolicy {
const StoragePolicy({
this.enabled = false,
this.maxAgeDays = 0,
this.maxBytes = 0,
this.includeWorktrees = false,
});
factory StoragePolicy.fromJson(Object? value) {
final data = storageMap(value);
return StoragePolicy(
enabled: data['enabled'] == true,
maxAgeDays: storageInt(data['max_age_days']),
maxBytes: storageInt(data['max_bytes']),
includeWorktrees: data['include_worktrees'] == true,
);
}
final bool enabled;
final int maxAgeDays;
final int maxBytes;
final bool includeWorktrees;
JsonMap toJson() => {
'enabled': enabled,
'max_age_days': maxAgeDays,
'max_bytes': maxBytes,
'include_worktrees': includeWorktrees,
};
}
String storageBytes(int bytes) {
if (bytes < 1024) return '$bytes B';
const units = ['KiB', 'MiB', 'GiB', 'TiB'];
var amount = bytes / 1024;
var index = 0;
while (amount >= 1024 && index < units.length - 1) {
amount /= 1024;
index++;
}
return '${amount.toStringAsFixed(amount < 10 ? 2 : 1)} ${units[index]}';
}
/// Blank limits mean unbounded; no implicit deletion defaults.
StoragePolicy parseStoragePolicy({
required bool enabled,
required String days,
required String gib,
required bool includeWorktrees,
}) {
final age = days.trim().isEmpty ? 0 : int.tryParse(days.trim());
final size = gib.trim().isEmpty ? 0.0 : double.tryParse(gib.trim());
if (age == null || age < 0 || age > 36500) {
throw const FormatException(
'Enter a whole number of days from 1 to 36500, or leave blank.',
);
}
if (size == null || !size.isFinite || size < 0 || size > 1048576) {
throw const FormatException(
'Enter a storage limit in GiB, or leave blank.',
);
}
final bytes = (size * 1024 * 1024 * 1024).round();
if (enabled && age == 0 && bytes == 0) {
throw const FormatException(
'Set an age or size limit before enabling automatic cleanup.',
);
}
return StoragePolicy(
enabled: enabled,
maxAgeDays: age,
maxBytes: bytes,
includeWorktrees: includeWorktrees,
);
}