translateAbsolutePath function
Windows, an absolute path starts with \\
, or a drive letter followed by
:/
or :\
.
This method will strip the prefix so the path start with a \ or /
and the prepend the drive letter so that it becomes a valid
path. If the absolutePath
doesn't contain a drive letter
then we take the drive letter from the workingDirectory
.
If this is a linux absolute path it is returned unchanged.
C:/abc -> /CDrive/abc C:\abc -> /CDrive\abc \\abc -> \abc \abc -> abc
The context
is only used for unit testing so
we can fake the platform separator.
Implementation
@visibleForTesting
String translateAbsolutePath(
String absolutePath, {
String? workingDirectory,
p.Context? context,
}) {
final windowsStyle = context != null && context.style == Style.windows;
if (!windowsStyle && !Settings().isWindows) {
return absolutePath;
}
context ??= p.context;
// ignore: parameter_assignments
workingDirectory ??= pwd;
final parts = context.split(absolutePath);
if (parts[0].contains(':')) {
final index = parts[0].indexOf(':');
final drive = parts[0][index - 1].toUpperCase();
return context.joinAll(['\\${drive}Drive', ...parts.sublist(1)]);
}
if (parts[0].startsWith(r'\\')) {
final uncparts = parts[0].split(r'\\');
return context.joinAll([r'\UNC', ...uncparts.sublist(1)]);
}
if (absolutePath.startsWith(r'\') || absolutePath.startsWith('/')) {
String drive;
if (workingDirectory.contains(':')) {
drive = workingDirectory[0].toUpperCase();
} else {
drive = pwd[0].toUpperCase();
}
return context.joinAll(['\\${drive}Drive', ...parts.sublist(1)]);
}
/// probably not an absolute path
/// so just pass back what we were handed.
return absolutePath;
}