Exemple #1
0
func embed(paths []string, rewrite, doDiff bool) error {
	if rewrite && doDiff {
		return fmt.Errorf("error: cannot use -w and -d simulatenously")
	}

	if len(paths) == 0 {
		if rewrite {
			return fmt.Errorf("error: cannot use -w with standard input")
		}
		if !doDiff {
			return embedmd.Process(stdout, stdin)
		}

		var out, in bytes.Buffer
		if err := embedmd.Process(&out, io.TeeReader(stdin, &in)); err != nil {
			return err
		}
		d, err := diff(in.Bytes(), out.Bytes())
		if err != nil || len(d) == 0 {
			return err
		}
		fmt.Fprintf(stdout, "%s", d)
		return nil
	}

	for _, path := range paths {
		if err := processFile(path, rewrite, doDiff); err != nil {
			return fmt.Errorf("%s:%v", path, err)
		}
	}
	return nil
}
Exemple #2
0
func processFile(path string, rewrite, doDiff bool) error {
	if filepath.Ext(path) != ".md" {
		return fmt.Errorf("not a markdown file")
	}

	f, err := openFile(path)
	if err != nil {
		return err
	}
	defer f.Close()

	buf := new(bytes.Buffer)
	if err := embedmd.Process(buf, f, embedmd.WithBaseDir(filepath.Dir(path))); err != nil {
		return err
	}

	if doDiff {
		f, err := readFile(path)
		if err != nil {
			return fmt.Errorf("could not read %s for diff: %v", path, err)
		}
		data, err := diff(f, buf.Bytes())
		if err != nil || len(data) == 0 {
			return err
		}
		fmt.Fprintf(stdout, "%s", data)
		return nil
	}

	if rewrite {
		n, err := f.WriteAt(buf.Bytes(), 0)
		if err != nil {
			return fmt.Errorf("could not write: %v", err)
		}
		return f.Truncate(int64(n))
	}

	io.Copy(stdout, buf)
	return nil
}