summaryrefslogtreecommitdiff
path: root/cmd/perc/main.go
blob: a5764b523a3f2af553c39471869217ad1e2a2804 (plain)
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
package main

import (
	"fmt"
	"os"
	"strings"

	"codeberg.org/snonux/perc/internal"
	"codeberg.org/snonux/perc/internal/calculator"
)

func main() {
	output, err := runCommand(os.Args)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	fmt.Println(output)
}

func runCommand(args []string) (string, error) {
	if len(args) < 2 {
		printUsage()
		return "", fmt.Errorf("no input provided")
	}

	if args[1] == "version" {
		return internal.Version, nil
	}

	input := strings.Join(args[1:], " ")
	result, err := calculator.Parse(input)
	if err != nil {
		return "", err
	}

	return result, nil
}

func printUsage() {
	fmt.Println("Usage: perc <calculation>")
	fmt.Println("       perc version")
	fmt.Println("\nExamples:")
	fmt.Println("  perc 20% of 150")
	fmt.Println("  perc what is 20% of 150")
	fmt.Println("  perc 30 is what % of 150")
	fmt.Println("  perc 30 is 20% of what")
}