File: main.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-7
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 872 kB
  • sloc: makefile: 4
file content (73 lines) | stat: -rw-r--r-- 1,615 bytes parent folder | download | duplicates (2)
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
package main

import (
	"encoding/base32"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"net/url"
	"os"
	"strings"
)

func escape(encoding string) {
	switch {
	case strings.HasPrefix("query", encoding):
		b, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		os.Stdout.Write([]byte(url.QueryEscape(string(b))))
	case strings.HasPrefix("hex", encoding):
		b, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		os.Stdout.Write([]byte(hex.EncodeToString(b)))
	default:
		fmt.Fprintf(os.Stderr, "unknown escape encoding: %q\n", encoding)
		os.Exit(2)
	}
}

func unescape(encoding string) {
	switch {
	case strings.HasPrefix("query", encoding):
		b, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		s, err := url.QueryUnescape(string(b))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		os.Stdout.Write([]byte(s))
	case strings.HasPrefix("b32", encoding):
		d := base32.NewDecoder(base32.StdEncoding, os.Stdin)
		io.Copy(os.Stdout, d)
	default:
		fmt.Fprintf(os.Stderr, "unknown unescape encoding: %q\n", encoding)
	}
}

func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "expected two arguments: <mode> <encoding>: got %d\n", len(os.Args)-1)
		os.Exit(2)
	}
	mode := os.Args[1]
	switch {
	case strings.HasPrefix("escape", mode):
		escape(os.Args[2])
	case strings.HasPrefix("unescape", mode) || strings.HasPrefix("decode", mode):
		unescape(os.Args[2])
	default:
		fmt.Fprintf(os.Stderr, "unknown mode: %q\n", mode)
		os.Exit(2)
	}
}