/
sha512sum.go
107 lines (87 loc) · 2.37 KB
/
sha512sum.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
//
// mimixbox/internal/applets/textutils/sha512sum/sha512sum.go
//
// Copyright 2021 Naohiro CHIKAMATSU
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sha512sum
import (
"crypto/sha512"
"os"
"strings"
mb "github.com/nao1215/mimixbox/internal/lib"
"github.com/jessevdk/go-flags"
)
const cmdName string = "sha512sum"
const version = "1.0.1"
var osExit = os.Exit
type options struct {
Check bool `short:"c" long:"check" description:"Check if the SHA1 value matches the file"`
Version bool `short:"v" long:"version" description:"Show sha512sum command version"`
}
func Run() (int, error) {
var opts options
var args []string
var err error = nil
hash := sha512.New()
if args, err = parseArgs(&opts); err != nil {
return mb.ExitFailure, nil
}
if mb.HasPipeData() && mb.HasNoOperand(os.Args, cmdName) {
err = mb.ChecksumOutput(hash, strings.NewReader(args[0]), "-")
if err != nil {
return mb.ExitFailure, err
}
return mb.ExitSuccess, nil
}
if len(args) == 0 || mb.Contains(args, "-") {
err = mb.ChecksumOutput(hash, os.Stdin, "-")
if err != nil {
return mb.ExitSuccess, nil
}
return mb.ExitSuccess, nil
}
if opts.Check {
err = mb.CompareChecksum(hash, args)
if err != nil {
return mb.ExitFailure, err
}
return mb.ExitSuccess, nil
}
return mb.PrintChecksums(cmdName, hash, args)
}
func parseArgs(opts *options) ([]string, error) {
p := initParser(opts)
args, err := p.Parse()
if err != nil {
return nil, err
}
if mb.HasPipeData() && len(args) == 0 {
stdin, err := mb.FromPIPE()
if err != nil {
return nil, err
}
return []string{stdin}, nil
}
if opts.Version {
mb.ShowVersion(cmdName, version)
osExit(mb.ExitSuccess)
}
return args, nil
}
func initParser(opts *options) *flags.Parser {
parser := flags.NewParser(opts, flags.Default)
parser.Name = cmdName
parser.Usage = "[OPTIONS] FILE_PATH"
return parser
}