From 215b19d370793077effa13a9a1380473de3ae364 Mon Sep 17 00:00:00 2001 From: Mark McKinstry Date: Mon, 3 Feb 2020 13:15:53 -0800 Subject: [PATCH] add option for selinux closes https://github.com/acarl005/ls-go/issues/6 --- README.md | 1 + arguments.go | 2 ++ ls-go.go | 21 +++++++++++++++++++++ 3 files changed, 24 insertions(+) diff --git a/README.md b/README.md index 97557b5..483fd92 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ Flags: -i, --icons show folder icon before dirs -n, --nerd-font show nerd font glyphs before file names -r, --recurse traverse all dirs recursively + -Z, --selinux include security context -F, --find=FIND filter items with a regexp Args: diff --git a/arguments.go b/arguments.go index 712dff9..e870779 100644 --- a/arguments.go +++ b/arguments.go @@ -28,6 +28,7 @@ type arguments struct { icons *bool nerdfont *bool recurse *bool + selinux *bool find *string } @@ -52,6 +53,7 @@ var args = arguments{ kingpin.Flag("icons", "show folder icon before dirs").Short('i').Bool(), kingpin.Flag("nerd-font", "show nerd font glyphs before file names").Short('n').Bool(), kingpin.Flag("recurse", "traverse all dirs recursively").Short('r').Bool(), + kingpin.Flag("selinux", "include security context").Short('Z').Bool(), kingpin.Flag("find", "filter items with a regexp").Short('F').String(), } diff --git a/ls-go.go b/ls-go.go index 7ed5bfe..5e87679 100644 --- a/ls-go.go +++ b/ls-go.go @@ -13,6 +13,7 @@ import ( "strings" "time" + "github.com/opencontainers/selinux/go-selinux" "github.com/acarl005/textcol" colorable "github.com/mattn/go-colorable" "github.com/willf/pad" @@ -150,6 +151,14 @@ func listFiles(parentDir string, items *[]os.FileInfo, forceDotfiles bool) { } } + longestSELinuxLabel := 0 + if *args.selinux && selinux.GetEnabled() { + for _, fileInfo := range *items { + selinuxlabel := getSELinuxLabel(path.Join(absPath, fileInfo.Name())) + longestSELinuxLabel = max(longestSELinuxLabel, len(selinuxlabel)) + } + } + for _, fileInfo := range *items { // if this is a dotfile (hidden file) if fileInfo.Name()[0] == '.' { @@ -204,6 +213,12 @@ func listFiles(parentDir string, items *[]os.FileInfo, forceDotfiles bool) { displayItem.display += strings.Join(ownerInfo, " ") } + if *args.selinux && selinux.GetEnabled() { + selinuxLabel := getSELinuxLabel(path.Join(absPath, fileInfo.Name())) + paddedSELinuxLabel := pad.Right(selinuxLabel, longestSELinuxLabel, " ") + displayItem.display += paddedSELinuxLabel + } + if *args.bytes { if fileInfo.Mode()&os.ModeDevice != 0 { displayItem.display += deviceNumbers(path.Join(absPath, fileInfo.Name())) @@ -594,6 +609,12 @@ func splitExt(filename string) (basename, ext string) { return } +func getSELinuxLabel(absPath string) (string) { + selinuxLabel, err := selinux.FileLabel(absPath) + check(err) + return selinuxLabel +} + // Go doesn't provide a `Max` function for ints like it does for floats (wtf?) func max(a int, b int) int { if a > b {