Skip to content

Commit

Permalink
fix: chattr exits with status 1 for files that are not permitted with…
Browse files Browse the repository at this point in the history
…out force flag

Signed-off-by: Shivanjan Chakravorty <[email protected]>
  • Loading branch information
Glitchfix committed Oct 3, 2023
1 parent 66c7b96 commit d59972c
Showing 1 changed file with 41 additions and 4 deletions.
45 changes: 41 additions & 4 deletions pkg/chattr/chattr.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,32 @@ const (
)

func AddImmutable(path string) error {
return ForceAddImmutable(path, false)
}

func ForceAddImmutable(path string, force bool) error {
chattrBin := which(chattrCmd)
if _, err := os.Stat(path); err == nil {
cmd := exec.Command(chattrBin, "+i", path)
var cmd *exec.Cmd
if force {
cmd = exec.Command(chattrBin, "+i", "-f", path)
} else {
cmd = exec.Command(chattrBin, "+i", path)
}
var stderr bytes.Buffer
cmd.Stderr = &stderr

if err = cmd.Run(); err != nil {
err = cmd.Run()
if err != nil {
// chattr exits with status 1 for files that are not permitted without force flag
// this will happen for files that throws the error
// "Operation not supported while reading flags"
if force && cmd.ProcessState.ExitCode() == 1 {
return nil
}
if force {
return fmt.Errorf("%s +i -f failed: %s. Err: %v", chattrBin, stderr.String(), err)
}
return fmt.Errorf("%s +i failed: %s. Err: %v", chattrBin, stderr.String(), err)
}
}
Expand All @@ -32,13 +51,31 @@ func AddImmutable(path string) error {
}

func RemoveImmutable(path string) error {
return ForceRemoveImmutable(path, false)
}
func ForceRemoveImmutable(path string, force bool) error {
chattrBin := which(chattrCmd)
if _, err := os.Stat(path); err == nil {
cmd := exec.Command(chattrBin, "-i", path)
var cmd *exec.Cmd
if force {
cmd = exec.Command(chattrBin, "-i", "-f", path)
} else {
cmd = exec.Command(chattrBin, "-i", path)
}
var stderr bytes.Buffer
cmd.Stderr = &stderr

if err = cmd.Run(); err != nil {
err = cmd.Run()
if err != nil {
// chattr exits with status 1 for files that are not permitted without force flag
// this will happen for files that throws the error
// "Operation not supported while reading flags"
if force && cmd.ProcessState.ExitCode() == 1 {
return nil
}
if force {
return fmt.Errorf("%s -i -f failed: %s. Err: %v", chattrBin, stderr.String(), err)
}
return fmt.Errorf("%s -i failed: %s. Err: %v", chattrBin, stderr.String(), err)
}
}
Expand Down

0 comments on commit d59972c

Please sign in to comment.