shithub: misc

ref: 2f6d6e90fd2ec071a45d99b9682ccb67552b18de
dir: /filecon/filecon.go/

View raw version
package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
)

func usage() {
	fmt.Printf("filecon [-v] filename")
	os.Exit(1)
}

func main() {
	var fn string
	var verbose bool

	args := append([]string{}, os.Args[1:]...)
	if len(args) == 0 {
		usage()
	}
	for len(args) > 0 {
		var arg string
		arg, args = args[0], args[1:]
		if arg == "-v" {
			verbose = true
		} else {
			fn = arg
		}
	}
	if verbose {
		log.Printf("opening %v...", fn)
	}
	f, err := os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666)
	if err != nil {
		log.Fatalf("%v", err)
	}
	defer f.Close()
	r := bufio.NewReader(f)
	rr := bufio.NewReader(os.Stdin)
	for {
		l, err := rr.ReadString('\n')
		if err != nil {
			log.Fatalf("%v", err)
		}
		if verbose {
			log.Printf("send '%v'\n", l)
		}
		fmt.Fprintf(f, "%v\n", l)
		l, err = r.ReadString('\n')
		if err == io.EOF {
			break
		} else if err != nil {
			log.Fatalf("%v", err)
		}
		if verbose {
			log.Printf("filecon: received '%v'.", l)
		} else {
			fmt.Printf(l)
		}
	}
}