|
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"
|
@@ -466,3 +468,71 @@ func ParseCppString(line string) (string, string, bool) {
|
466 | 468 | i += width
|
467 | 469 | }
|
468 | 470 | }
|
| 471 | + |
| 472 | +func ExtractZip(filePath string, location string) (string, error) { |
| 473 | + r, err := zip.OpenReader(filePath) |
| 474 | + if err != nil { |
| 475 | + return location, err |
| 476 | + } |
| 477 | + |
| 478 | + var dirList []string |
| 479 | + |
| 480 | + for _, f := range r.File { |
| 481 | + dirList = append(dirList, f.Name) |
| 482 | + } |
| 483 | + |
| 484 | + basedir := findBaseDir(dirList) |
| 485 | + |
| 486 | + for _, f := range r.File { |
| 487 | + fullname := filepath.Join(location, strings.Replace(f.Name, "", "", -1)) |
| 488 | + if f.FileInfo().IsDir() { |
| 489 | + os.MkdirAll(fullname, f.FileInfo().Mode().Perm()) |
| 490 | + } else { |
| 491 | + os.MkdirAll(filepath.Dir(fullname), 0755) |
| 492 | + perms := f.FileInfo().Mode().Perm() |
| 493 | + out, err := os.OpenFile(fullname, os.O_CREATE|os.O_RDWR, perms) |
| 494 | + if err != nil { |
| 495 | + return location, err |
| 496 | + } |
| 497 | + rc, err := f.Open() |
| 498 | + if err != nil { |
| 499 | + return location, err |
| 500 | + } |
| 501 | + _, err = io.CopyN(out, rc, f.FileInfo().Size()) |
| 502 | + if err != nil { |
| 503 | + return location, err |
| 504 | + } |
| 505 | + rc.Close() |
| 506 | + out.Close() |
| 507 | + |
| 508 | + mtime := f.FileInfo().ModTime() |
| 509 | + err = os.Chtimes(fullname, mtime, mtime) |
| 510 | + if err != nil { |
| 511 | + return location, err |
| 512 | + } |
| 513 | + } |
| 514 | + } |
| 515 | + return filepath.Join(location, basedir), nil |
| 516 | +} |
| 517 | + |
| 518 | +func findBaseDir(dirList []string) string { |
| 519 | + baseDir := "" |
| 520 | + // https://github.com/backdrop-ops/contrib/issues/55#issuecomment-73814500 |
| 521 | + dontdiff := []string{"pax_global_header"} |
| 522 | + for index := range dirList { |
| 523 | + if SliceContains(dontdiff, dirList[index]) { |
| 524 | + continue |
| 525 | + } |
| 526 | + candidateBaseDir := dirList[index] |
| 527 | + for i := index; i < len(dirList); i++ { |
| 528 | + if !strings.Contains(dirList[i], candidateBaseDir) { |
| 529 | + return baseDir |
| 530 | + } |
| 531 | + } |
| 532 | + // avoid setting the candidate if it is the last file |
| 533 | + if dirList[len(dirList)-1] != candidateBaseDir { |
| 534 | + baseDir = candidateBaseDir |
| 535 | + } |
| 536 | + } |
| 537 | + return baseDir |
| 538 | +} |
0 commit comments