File: mc.go

package info (click to toggle)
golang-text 0.0~git20130502-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 92 kB
  • ctags: 44
  • sloc: makefile: 8
file content (62 lines) | stat: -rw-r--r-- 1,246 bytes parent folder | download | duplicates (3)
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
// Command mc prints in multiple columns.
//
//   Usage: mc [-] [-N] [file...]
//
// Mc splits the input into as many columns as will fit in N
// print positions. If the output is a tty, the default N is
// the number of characters in a terminal line; otherwise the
// default N is 80. Under option - each input line ending in
// a colon ':' is printed separately.
package main

import (
	"github.com/kr/pty"
	"github.com/kr/text/colwriter"
	"io"
	"log"
	"os"
	"strconv"
)

func main() {
	var width int
	var flag uint
	args := os.Args[1:]
	for len(args) > 0 && len(args[0]) > 0 && args[0][0] == '-' {
		if len(args[0]) > 1 {
			width, _ = strconv.Atoi(args[0][1:])
		} else {
			flag |= colwriter.BreakOnColon
		}
		args = args[1:]
	}
	if width < 1 {
		_, width, _ = pty.Getsize(os.Stdout)
	}
	if width < 1 {
		width = 80
	}

	w := colwriter.NewWriter(os.Stdout, width, flag)
	if len(args) > 0 {
		for _, s := range args {
			if f, err := os.Open(s); err == nil {
				copyin(w, f)
				f.Close()
			} else {
				log.Println(err)
			}
		}
	} else {
		copyin(w, os.Stdin)
	}
}

func copyin(w *colwriter.Writer, r io.Reader) {
	if _, err := io.Copy(w, r); err != nil {
		log.Println(err)
	}
	if err := w.Flush(); err != nil {
		log.Println(err)
	}
}