import 'package:cutdex/errors/app_failure.dart'; import 'dart:io'; import 'package:path/path.dart' as p; enum ProjectLocationStatus { ready, missing, unavailable, notWritable } class ProjectLocationDirectory { const ProjectLocationDirectory(); Future inspect(String path) async { if (!p.isAbsolute(path)) return ProjectLocationStatus.unavailable; try { final directory = Directory(path); if (await directory.exists()) { await _checkWritable(directory); return ProjectLocationStatus.ready; } // Never recreate a missing external/network location on the system disk. // Its mount point may still exist even though the volume is disconnected. if (_isExternalPath(path)) return ProjectLocationStatus.unavailable; var ancestor = directory; while (!await ancestor.exists()) { if (await FileSystemEntity.type(ancestor.path, followLinks: false) != FileSystemEntityType.notFound) { return ProjectLocationStatus.unavailable; } final parent = ancestor.parent; if (parent.path == ancestor.path) { return ProjectLocationStatus.unavailable; } ancestor = parent; } await _checkWritable(ancestor); return ProjectLocationStatus.missing; } on FileSystemException catch (error) { return _isPermissionError(error) ? ProjectLocationStatus.notWritable : ProjectLocationStatus.unavailable; } } Future prepare(String path) async { final status = await inspect(path); if (status == ProjectLocationStatus.notWritable) { throw AppException(AppErrorCode.projectLocationNotWritable); } if (status == ProjectLocationStatus.unavailable) { throw AppException(AppErrorCode.projectLocationUnavailable); } try { final directory = Directory(path); if (status == ProjectLocationStatus.missing) { await directory.create(recursive: true); } await _checkWritable(directory); } on FileSystemException { throw AppException(AppErrorCode.projectLocationCreateFailed); } } bool _isExternalPath(String path) { if (Platform.isWindows) { // Only the system drive is known to be local without a volume query. final systemDrive = Platform.environment['SystemDrive']; return systemDrive == null || p.windows.rootPrefix(path).toLowerCase() != '${systemDrive.toLowerCase()}\\'; } final normalized = p.normalize(path); return const [ '/Volumes', '/mnt', '/media', '/run/media', '/net', ].any((root) => normalized == root || p.isWithin(root, normalized)); } bool _isPermissionError(FileSystemException error) => (Platform.isWindows ? const [5, 19] : const [1, 13, 30]).contains( error.osError?.errorCode, ); Future _checkWritable(Directory directory) async { final probe = File( p.join( directory.path, '.cutdex-write-$pid-${DateTime.now().microsecondsSinceEpoch}', ), ); var created = false; try { await probe.create(exclusive: true); created = true; } finally { if (created) await probe.delete(); } } }