Skip to content

Commit

Permalink
Fixes hashicorp#370: Fix file permission handling
Browse files Browse the repository at this point in the history
- Preserve original file permissions when archiving
- Apply output_file_mode to archive file only
- Add parseFileMode function for consistent mode parsing
- Set default mode (0644) for content without specified permissions
  • Loading branch information
lewisdan91 committed Sep 18, 2024
1 parent 1647978 commit dfcb0d9
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions internal/provider/tar_archiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,16 @@ func (a *TarArchiver) open() error {
return err
}

if a.outputFileMode != "" {
fileMode, err := parseFileMode(a.outputFileMode)
if err != nil {
return fmt.Errorf("error parsing output_file_mode value: %s", err)
}
if err := a.fileWriter.Chmod(fileMode); err != nil {
return fmt.Errorf("error setting file mode on archive: %s", err)
}
}

switch a.compression {
case TarCompressionGz:
a.compressionWriter = gzip.NewWriter(a.fileWriter)
Expand Down Expand Up @@ -269,14 +279,14 @@ func (a *TarArchiver) addFile(filePath string, header *tar.Header) error {
}
defer file.Close()

if a.outputFileMode != "" {
fileMode, err := strconv.ParseInt(a.outputFileMode, 0, 32)
if err != nil {
return fmt.Errorf("error parsing output_file_mode value: %s", a.outputFileMode)
}
header.Mode = fileMode
fileInfo, err := file.Stat()
if err != nil {
return fmt.Errorf("could not get file info for '%s', got error '%w'", filePath, err)
}

header.Mode = int64(fileInfo.Mode())
header.ModTime = fileInfo.ModTime()

err = a.tarWriter.WriteHeader(header)
if err != nil {
return fmt.Errorf("could not write header for file '%s', got error '%w'", filePath, err)
Expand All @@ -295,12 +305,8 @@ func (a *TarArchiver) addContent(content []byte, header *tar.Header) error {
return errors.New("tar.Header is nil")
}

if a.outputFileMode != "" {
filemode, err := strconv.ParseInt(a.outputFileMode, 0, 32)
if err != nil {
return fmt.Errorf("error parsing output_file_mode value: %s", a.outputFileMode)
}
header.Mode = filemode
if header.Mode == 0 {
header.Mode = int64(0644)
}

if err := a.tarWriter.WriteHeader(header); err != nil {
Expand All @@ -314,3 +320,12 @@ func (a *TarArchiver) addContent(content []byte, header *tar.Header) error {

return nil
}

func parseFileMode(modeStr string) (os.FileMode, error) {
modeUint, err := strconv.ParseUint(modeStr, 8, 32)
if err != nil {
return 0, fmt.Errorf("invalid file mode '%s': %w", modeStr, err)
}

return os.FileMode(modeUint), nil
}

0 comments on commit dfcb0d9

Please sign in to comment.