liveScreenshotPath function

String liveScreenshotPath({
  1. required String root,
  2. required String device,
  3. required String mode,
  4. required DateTime at,
  5. String? requested,
  6. bool several = false,
  7. String suffix = '',
  8. String extension = '.png',
  9. bool exists(
    1. String path
    )?,
})

Where screenshot saves the capture of device, running in mode, taken at.

By default that's screenshots/<mode>-<device>-<yyyyMMdd-HHmm>.png in root, with suffix (e.g. -native) before the extension. When that file is there already, the seconds are added, then -2, -3 and so on, so every capture keeps its own file. With an empty extension it's a folder, named the same way.

requested is the --out value, relative to root: a .png is saved as named, and a folder gets the default name inside it. When several apps are captured, each named .png gets its device name added.

Implementation

String liveScreenshotPath({
  required String root,
  required String device,
  required String mode,
  required DateTime at,
  String? requested,
  bool several = false,
  String suffix = '',
  String extension = '.png',
  bool Function(String path)? exists,
}) {
  final bool Function(String path) taken =
      exists ??
      ((String path) =>
          FileSystemEntity.typeSync(path) != FileSystemEntityType.notFound);
  final String separator = Platform.pathSeparator;
  final String slug = liveSlug(device);

  String folder = '$root${separator}screenshots';
  if (requested != null) {
    final String path = _resolve(requested, root);
    if (!liveOutIsFolder(requested, root: root)) {
      if (!several) return path;
      final int dot = path.lastIndexOf('.');
      return '${path.substring(0, dot)}-$slug${path.substring(dot)}';
    }
    folder = path.replaceAll(RegExp(r'[\\/]+$'), '');
  }

  String two(int n) => n.toString().padLeft(2, '0');
  final String minute =
      '${at.year}${two(at.month)}${two(at.day)}-${two(at.hour)}'
      '${two(at.minute)}';
  final String name = [
    liveSlug(mode),
    slug,
    minute,
  ].where((String part) => part.isNotEmpty).join('-');
  final String path = '$folder$separator$name$suffix$extension';
  if (!taken(path)) return path;
  final String seconds = '$folder$separator$name${two(at.second)}';
  if (!taken('$seconds$suffix$extension')) return '$seconds$suffix$extension';
  for (int n = 2; ; n++) {
    if (!taken('$seconds-$n$suffix$extension')) {
      return '$seconds-$n$suffix$extension';
    }
  }
}