Skip to content

Commit

Permalink
Add a way to strip top-level folder
Browse files Browse the repository at this point in the history
Closes #238
  • Loading branch information
illiliti authored and AJ ONeal committed Oct 13, 2020
1 parent c8f35d3 commit fd5996a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
3 changes: 3 additions & 0 deletions cmd/arc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ var (
mkdirAll bool
selectiveCompression bool
implicitTopLevelFolder bool
stripComponents int
continueOnError bool
specifyFileType string
)
Expand All @@ -37,6 +38,7 @@ func init() {
flag.BoolVar(&mkdirAll, "mkdirs", false, "Make all necessary directories")
flag.BoolVar(&selectiveCompression, "smart", true, "Only compress files which are not already compressed (zip only)")
flag.BoolVar(&implicitTopLevelFolder, "folder-safe", true, "If an archive does not have a single top-level folder, create one implicitly")
flag.IntVar(&stripComponents, "strip-components", 0, "Strip number of leading paths")
flag.BoolVar(&continueOnError, "allow-errors", true, "Log errors and continue processing")
flag.StringVar(&specifyFileType, "ext", "", "specify file type")
}
Expand Down Expand Up @@ -223,6 +225,7 @@ func getFormat(subcommand string) (interface{}, error) {
OverwriteExisting: overwriteExisting,
MkdirAll: mkdirAll,
ImplicitTopLevelFolder: implicitTopLevelFolder,
StripComponents: stripComponents,
ContinueOnError: continueOnError,
}

Expand Down
15 changes: 15 additions & 0 deletions tar.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ type Tar struct {
// especially on extraction.
ImplicitTopLevelFolder bool

// Strip number of leading paths. This feature is available
// only during unpacking of the entire archive.
StripComponents int

// If true, errors encountered during reading
// or writing a single file will be logged and
// the operation will continue on remaining files.
Expand Down Expand Up @@ -233,6 +237,17 @@ func (t *Tar) untarNext(destination string) error {
if errPath != nil {
return fmt.Errorf("checking path traversal attempt: %v", errPath)
}

if t.StripComponents > 0 {
if strings.Count(header.Name, "/") < t.StripComponents {
return nil // skip path with fewer components
}

for i := 0; i < t.StripComponents; i++ {
slash := strings.Index(header.Name, "/")
header.Name = header.Name[slash+1:]
}
}
return t.untarFile(f, destination, header)
}

Expand Down

0 comments on commit fd5996a

Please sign in to comment.