Last active
March 22, 2023 07:01
-
-
Save savaged/c473235ad3c64733911099a9018a953e to your computer and use it in GitHub Desktop.
Fun with C# and a command line tool for calculating the UNIX file permission number from the text listing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text.RegularExpressions; | |
if (args.Length == 0 || !args[0].IsUnixFileModeAndPermissionsString()) | |
{ | |
Console.WriteLine( | |
"Argument must be in the form of a UNIX file permission string, " + | |
"i.e. -rwxrwxrwx or -rwxr-xr-x etc."); | |
return; | |
} | |
Console.WriteLine(args[0].ToClasses().ToPermissionNumber()); | |
static class ChmodNumEx | |
{ | |
public static IEnumerable<string> ToClasses(this string self) => | |
new List<string> | |
{ | |
self[1..4], // group | |
self[4..7], // other | |
self[^3..] // user | |
}; | |
public static int ToPermissionNumber(this IEnumerable<string> self) => | |
int.Parse(string.Join("", | |
self.Select(@class => @class.ToPermissionNumber()).ToList())); | |
public static bool IsUnixFileModeAndPermissionsString(this string self) => | |
new Regex(@"^(-|d|l|p|s|b|c|D)((-|r)(-|w)(-|x)){3}$").IsMatch(self); | |
private static bool IsPermission(this char self) => self != '-'; | |
private static int ToInt(this bool self) => self ? 1 : 0; | |
private static int ToPermissionNumber(this string self) | |
{ | |
var bits = new int[3]; | |
for (var b = 2; b >= 0; b--) | |
{ | |
bits[b] = self[b].IsPermission().ToInt(); | |
} | |
return Convert.ToInt16(string.Join("", bits), 2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
chmodnum -rwxr--r--