relativePathError function

String? relativePathError(
  1. String path, {
  2. bool windows = false,
})

Why path is not a relative path spelled with /, or null when it is one.

A valid path is non-empty, spells its segments separated by /, and holds no empty, . or .. segment, no backslash, no NUL character and no absolute prefix: a leading / or \, a drive (C:) or a UNC share (\\server).

With windows, the naming rules of Windows apply to every segment as well: no colon, no trailing dot or space, and no reserved device name (CON, PRN, AUX, NUL, COM1 to COM9, LPT1 to LPT9, with or without an extension, in any case).

Implementation

String? relativePathError(String path, {bool windows = false}) {
  if (path.isEmpty) {
    return 'is empty';
  }
  if (path.startsWith('/') || path.startsWith('\\')) {
    return 'is absolute';
  }
  if (RegExp(r'^[A-Za-z]:').hasMatch(path)) {
    return 'is absolute';
  }
  if (path.contains('\\')) {
    return 'contains a backslash';
  }
  if (path.contains('\u0000')) {
    return 'contains a NUL character';
  }
  for (final String segment in path.split('/')) {
    if (segment.isEmpty) {
      return 'contains an empty segment';
    }
    if (segment == '.' || segment == '..') {
      return 'contains a "." or ".." segment';
    }
    if (!windows) {
      continue;
    }
    if (segment.contains(':')) {
      return 'contains a ":" character';
    }
    if (segment.endsWith('.') || segment.endsWith(' ')) {
      return 'ends with a dot or a space';
    }
    if (_reservedWindowsNames
        .contains(segment.split('.').first.toUpperCase())) {
      return 'names a reserved Windows device';
    }
  }
  return null;
}