// Package archive reads and writes zip, tar and tar.gz archives on top of // vfs (design §5.1–5.3): an Index is built without unpacking anything to a // temp directory, NewSource feeds members to the transfer engine in one pass // over the archive (Unpack), and Create writes an archive through // transfer.WriteAtomic. package archive import ( "path" "strings" ) // Format of an archive. type Format uint8 const ( Zip Format = iota Tar TarGz ) func (f Format) String() string { switch f { case Zip: return "zip" case Tar: return "tar" case TarGz: return "tar.gz" } return "unknown" } // Ext is the file extension, with the dot. func (f Format) Ext() string { return "." + f.String() } // knownExts in match order (longest first). var knownExts = []struct { ext string f Format }{ {".tar.gz", TarGz}, {".tgz", TarGz}, {".tar", Tar}, {".zip", Zip}, } // DetectFormat guesses the format from the file name. func DetectFormat(name string) (Format, bool) { lower := strings.ToLower(name) for _, k := range knownExts { if strings.HasSuffix(lower, k.ext) && len(lower) > len(k.ext) { return k.f, true } } return 0, false } // stripArchiveExt removes a known archive extension, or else the last // extension (report.pdf → report). func stripArchiveExt(name string) string { lower := strings.ToLower(name) for _, k := range knownExts { if strings.HasSuffix(lower, k.ext) && len(name) > len(k.ext) { return name[:len(name)-len(k.ext)] } } if ext := path.Ext(name); ext != "" && ext != name { return name[:len(name)-len(ext)] } return name } // Name proposes an archive file name for the given sources (paths or base // names, slash-separated): one source → its name without extension // (foo.tar.gz → foo.zip, not foo.tar.zip; U-P2); several → the name of // their parent directory, or "archive". func Name(srcNames []string, f Format) string { if len(srcNames) == 1 { base := path.Base(strings.TrimRight(srcNames[0], "/")) if b := stripArchiveExt(base); b != "" && b != "." && b != "/" { return b + f.Ext() } } if len(srcNames) > 1 { parent := path.Base(path.Dir(srcNames[0])) if parent != "." && parent != "/" && parent != "" { return parent + f.Ext() } } return "archive" + f.Ext() }