|
30 | 30 | package utils
|
31 | 31 |
|
32 | 32 | import (
|
| 33 | + "archive/zip" |
33 | 34 | "crypto/md5"
|
34 | 35 | "encoding/hex"
|
| 36 | + "io" |
35 | 37 | "io/ioutil"
|
36 | 38 | "os"
|
37 | 39 | "os/exec"
|
@@ -488,3 +490,71 @@ func ParseCppString(line string) (string, string, bool) {
|
488 | 490 | i += width
|
489 | 491 | }
|
490 | 492 | }
|
| 493 | + |
| 494 | +func ExtractZip(filePath string, location string) (string, error) { |
| 495 | + r, err := zip.OpenReader(filePath) |
| 496 | + if err != nil { |
| 497 | + return location, err |
| 498 | + } |
| 499 | + |
| 500 | + var dirList []string |
| 501 | + |
| 502 | + for _, f := range r.File { |
| 503 | + dirList = append(dirList, f.Name) |
| 504 | + } |
| 505 | + |
| 506 | + basedir := findBaseDir(dirList) |
| 507 | + |
| 508 | + for _, f := range r.File { |
| 509 | + fullname := filepath.Join(location, strings.Replace(f.Name, "", "", -1)) |
| 510 | + if f.FileInfo().IsDir() { |
| 511 | + os.MkdirAll(fullname, f.FileInfo().Mode().Perm()) |
| 512 | + } else { |
| 513 | + os.MkdirAll(filepath.Dir(fullname), 0755) |
| 514 | + perms := f.FileInfo().Mode().Perm() |
| 515 | + out, err := os.OpenFile(fullname, os.O_CREATE|os.O_RDWR, perms) |
| 516 | + if err != nil { |
| 517 | + return location, err |
| 518 | + } |
| 519 | + rc, err := f.Open() |
| 520 | + if err != nil { |
| 521 | + return location, err |
| 522 | + } |
| 523 | + _, err = io.CopyN(out, rc, f.FileInfo().Size()) |
| 524 | + if err != nil { |
| 525 | + return location, err |
| 526 | + } |
| 527 | + rc.Close() |
| 528 | + out.Close() |
| 529 | + |
| 530 | + mtime := f.FileInfo().ModTime() |
| 531 | + err = os.Chtimes(fullname, mtime, mtime) |
| 532 | + if err != nil { |
| 533 | + return location, err |
| 534 | + } |
| 535 | + } |
| 536 | + } |
| 537 | + return filepath.Join(location, basedir), nil |
| 538 | +} |
| 539 | + |
| 540 | +func findBaseDir(dirList []string) string { |
| 541 | + baseDir := "" |
| 542 | + // https://github.com/backdrop-ops/contrib/issues/55#issuecomment-73814500 |
| 543 | + dontdiff := []string{"pax_global_header"} |
| 544 | + for index := range dirList { |
| 545 | + if SliceContains(dontdiff, dirList[index]) { |
| 546 | + continue |
| 547 | + } |
| 548 | + candidateBaseDir := dirList[index] |
| 549 | + for i := index; i < len(dirList); i++ { |
| 550 | + if !strings.Contains(dirList[i], candidateBaseDir) { |
| 551 | + return baseDir |
| 552 | + } |
| 553 | + } |
| 554 | + // avoid setting the candidate if it is the last file |
| 555 | + if dirList[len(dirList)-1] != candidateBaseDir { |
| 556 | + baseDir = candidateBaseDir |
| 557 | + } |
| 558 | + } |
| 559 | + return baseDir |
| 560 | +} |
0 commit comments