stringPermissionToOctal function
ex: stringPermissionToOctal('-rwxrwxrwx') => 777
value
input '-rwxrwxrwx' => 777
Implementation
String stringPermissionToOctal(String value, {bool withType = false}) {
// drwxr-xr-x
// skip first d
// go through remaining in sets of 3
var output = '';
var grouping = 0;
int permission = 0;
var combinedPermission = 0;
var fileType = '';
var charPosition = 1;
for (var i = 0; i < value.length; i++) {
var alpha = value[i]; //charCodeAt
// leading '-', ie. files, not directories
if (i == 0 && alpha == '-') {
grouping = 0;
if (withType) {
fileType = 'File: ';
}
continue;
}
// If first char entered is 'd' we're dealing with a directory
if (i == 0 && alpha == 'd') {
grouping = 0;
if (withType) {
fileType = 'Directory: ';
}
continue;
}
// Valid characters entered
if (i >= 1 && (alpha.allMatches('[rwx-]').toList().isEmpty == true)) {
return "Invalid";
}
// update character position validator when user starts with read
if (i == 0 && alpha == 'r') {
charPosition = 0;
}
// char positions matter drwx-rxw-x
if ((i == charPosition || i == (charPosition + 3) || i == (charPosition + 6)) &&
(alpha.allMatches('[r-]').toList().isEmpty == true)) {
return "Invalid";
}
if ((i == (charPosition + 1) || i == (charPosition + 4) || i == (charPosition + 7)) &&
(alpha.allMatches('[w-]').toList().isEmpty == true)) {
return "Invalid";
}
if ((i == (charPosition + 2) || i == (charPosition + 5) || i == (charPosition + 8)) &&
(alpha.allMatches('[x-]').toList().isEmpty == true)) {
return "Invalid";
}
switch (alpha) {
case 'r':
permission = 4;
grouping++;
break;
case 'w':
permission = 2;
grouping++;
break;
case 'x':
permission = 1;
grouping++;
break;
case '-':
permission = 0;
grouping++;
break;
default:
//permission = "Invalid";
}
combinedPermission += permission;
// Process in groups of three, then reset and continue to the next batch
if (grouping % 3 == 0) {
output = '$output$combinedPermission';
grouping = 0;
combinedPermission = 0;
permission = 0;
}
}
return fileType + output;
}