forked from martinplaner/gunarchiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
109 lines (85 loc) · 2.45 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Copyright 2017 Martin Planer. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/martinplaner/gunarchiver/archive"
_ "github.com/martinplaner/gunarchiver/archive/rar"
_ "github.com/martinplaner/gunarchiver/archive/tar"
_ "github.com/martinplaner/gunarchiver/archive/zip"
"github.com/martinplaner/gunarchiver/progress"
"github.com/martinplaner/gunarchiver/trash"
"github.com/martinplaner/gunarchiver/ui"
)
var userInterface ui.UserInterface
func main() {
var extractErr error
var uiErr error
PrintVersion()
if len(os.Args) != 2 {
fmt.Printf("Usage: %s <archive>\n", os.Args[0])
return
}
archivePath := os.Args[1]
progressChan := make(chan progress.Progress)
progressWindow := userInterface.NewProgressWindow()
// Kick off extraction
go func() {
extractErr = extractArchiveAndDelete(archivePath, progressChan, progressWindow.RequestedCancel)
close(progressChan)
}()
// Synchronize extraction and UI progress
go progress.Sync{
UpdateCloser: progressWindow,
Progress: progressChan,
}.Run()
uiErr = progressWindow.Show()
if extractErr != nil {
errorWindow := userInterface.NewErrorWindow(extractErr.Error())
errorWindow.Show()
log.Fatalln("could not extract archive:", extractErr)
}
if uiErr != nil {
log.Fatalln("could not show user interface:", uiErr)
}
}
func extractArchiveAndDelete(path string, progressChan chan progress.Progress, shouldCancel func() bool) error {
err := extractArchive(path, progressChan, shouldCancel)
if archive.IsCanceled(err) {
return nil
} else if err != nil {
return err
}
if err := trash.MoveToTrash(path); err != nil {
return err
}
return nil
}
func extractArchive(path string, progressChan chan progress.Progress, shouldCancel func() bool) error {
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("could not open file: %v", err)
}
defer f.Close()
a, _, err := archive.Decode(f)
if err != nil {
return fmt.Errorf("could not decode archive: %v", err)
}
baseDir := filepath.Dir(path)
singleRoot := archive.HasSingleRoot(a)
if !singleRoot {
baseDir = filepath.Join(baseDir, a.Basename())
archive.CreateDir(baseDir)
}
err = archive.Extract(a, baseDir, progressChan, shouldCancel)
if archive.IsCanceled(err) {
return err
} else if err != nil {
return fmt.Errorf("could not extract archive: %v", err)
}
return nil
}