github.com/xyproto/orbiton/v2@v2.65.12-0.20240516144430-e10a419274ec/export.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"os"
     7  	"os/exec"
     8  	"strings"
     9  
    10  	"github.com/xyproto/files"
    11  	"github.com/xyproto/vt100"
    12  )
    13  
    14  // exportScdoc tries to export the current document as a manual page, using scdoc
    15  func (e *Editor) exportScdoc(manFilename string) error {
    16  	scdoc := exec.Command("scdoc")
    17  
    18  	// Place the current contents in a buffer, and feed it to stdin to the command
    19  	var buf bytes.Buffer
    20  	buf.WriteString(e.String())
    21  	scdoc.Stdin = &buf
    22  
    23  	// Create a new file and use it as stdout
    24  	manpageFile, err := os.Create(manFilename)
    25  	if err != nil {
    26  		return err
    27  	}
    28  
    29  	var errBuf bytes.Buffer
    30  	scdoc.Stdout = manpageFile
    31  	scdoc.Stderr = &errBuf
    32  
    33  	// Save the command in a temporary file
    34  	saveCommand(scdoc)
    35  
    36  	// Run scdoc
    37  	if err := scdoc.Run(); err != nil {
    38  		errorMessage := strings.TrimSpace(errBuf.String())
    39  		if len(errorMessage) > 0 {
    40  			return errors.New(errorMessage)
    41  		}
    42  		return err
    43  	}
    44  	return nil
    45  }
    46  
    47  // exportAdoc tries to export the current document as a manual page, using asciidoctor
    48  func (e *Editor) exportAdoc(c *vt100.Canvas, tty *vt100.TTY, manFilename string) error {
    49  	// TODO: Use a proper function for generating temporary files
    50  	tmpfn := "___o___.adoc"
    51  	if files.Exists(tmpfn) {
    52  		return errors.New(tmpfn + " already exists, please remove it")
    53  	}
    54  
    55  	// TODO: Write a SaveAs function for the Editor
    56  	oldFilename := e.filename
    57  	e.filename = tmpfn
    58  	err := e.Save(c, tty)
    59  	if err != nil {
    60  		e.filename = oldFilename
    61  		return err
    62  	}
    63  	e.filename = oldFilename
    64  
    65  	// Run asciidoctor
    66  	adocCommand := exec.Command("asciidoctor", "-b", "manpage", "-o", manFilename, tmpfn)
    67  	saveCommand(adocCommand)
    68  	if err = adocCommand.Run(); err != nil {
    69  		_ = os.Remove(tmpfn) // Try removing the temporary filename if pandoc fails
    70  		return err
    71  	}
    72  	return os.Remove(tmpfn)
    73  }