Example #1
0
func Format(in, out string) (err error) {
	var fout io.WriteCloser
	var fin io.ReadCloser
	var ast parser.AST

	// Open input stream.
	if in == Stdin {
		fin = _stdin
	} else {
		fin, err = os.Open(in)
		if err != nil {
			return
		}
	}

	// Parse source into AST.
	err = ast.Parse(fin, in)
	fin.Close()

	if err != nil {
		return
	}

	if *strip {
		StripComments(&ast)
	}

	// Open output stream.
	if out == Stdout {
		fout = _stdout
	} else {
		fout, err = os.Create(out)
		if err != nil {
			return
		}

		defer fout.Close()
	}

	// Write source.
	sw := util.NewSourceWriter(fout, &ast)
	sw.Tabs = *tabs
	sw.TabWidth = *tabwidth
	sw.Comments = !*strip
	sw.Write()
	return
}
Example #2
0
func writeSource(ast *parser.AST, file string, doast bool) (err error) {
	var w io.Writer

	if len(file) == 0 {
		w = os.Stdout
	} else {
		fd, err := os.Create(file)
		if err != nil {
			return err
		}

		defer fd.Close()
		w = fd
	}

	if doast {
		util.NewAstWriter(w, ast).Write()
	} else {
		util.NewSourceWriter(w, ast).Write()
	}

	return
}