github.com/raphaelreyna/latte@v0.11.2-0.20220317193248-98e2fcef4eef/internal/job/job.go (about)

     1  package job
     2  
     3  import (
     4  	"encoding/json"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  	"text/template"
     9  
    10  	"errors"
    11  
    12  	"github.com/raphaelreyna/go-recon"
    13  )
    14  
    15  // Job represents the request for constructing a tex file from the template and details and then compiling that into a PDF.
    16  type Job struct {
    17  	recon.Dir
    18  	Template *template.Template
    19  	Details  map[string]interface{}
    20  	Opts     Options
    21  }
    22  
    23  func NewJob(root string, sc recon.SourceChain) *Job {
    24  	j := &Job{Opts: DefaultOptions}
    25  	j.Root = root
    26  	j.SourceChain = sc
    27  
    28  	return j
    29  }
    30  
    31  // AddResource adds resource files to the Job that should be available in the root/working directory.
    32  func (j *Job) AddResource(files ...string) {
    33  	if j.Files == nil {
    34  		j.Files = []*recon.File{}
    35  	}
    36  
    37  	for _, resource := range files {
    38  		j.Files = append(j.Files, &recon.File{
    39  			Name: resource,
    40  		})
    41  	}
    42  }
    43  
    44  // GetTemplate looks for a template named id in the SourceChain and parses it, storing the results for later use.
    45  func (j *Job) GetTemplate(id string) error {
    46  	// Make sure the delimiters aren't empty
    47  	if j.Opts.Delims == BadDefaultDelimiters || j.Opts.Delims == EmptyDelimiters {
    48  		return errors.New("invalid delimiters, cannot parse template")
    49  	}
    50  	f := recon.File{Name: id}
    51  	_, err := f.AddTo(j.Root, 0644, j.SourceChain)
    52  	if err != nil {
    53  		return err
    54  	}
    55  
    56  	name := filepath.Join(j.Root, f.Name)
    57  
    58  	data, err := ioutil.ReadFile(name)
    59  	if err != nil {
    60  		return err
    61  	}
    62  
    63  	t := template.New(id)
    64  	t = t.Delims(j.Opts.Delims.Left, j.Opts.Delims.Right)
    65  	t, err = t.Parse(string(data))
    66  	if err != nil {
    67  		return err
    68  	}
    69  
    70  	j.Template = t
    71  	return nil
    72  }
    73  
    74  // GetDetails looks for a details file named id in the SourceChain and stores the results for later.
    75  func (j *Job) GetDetails(id string) error {
    76  	f := recon.File{Name: id}
    77  	_, err := f.AddTo(j.Root, 0644, j.SourceChain)
    78  	if err != nil {
    79  		return err
    80  	}
    81  
    82  	name := filepath.Join(j.Root, f.Name)
    83  	defer os.Remove(name)
    84  
    85  	data, err := ioutil.ReadFile(name)
    86  	if err != nil {
    87  		return err
    88  	}
    89  
    90  	dtls := map[string]interface{}{}
    91  	if err = json.Unmarshal(data, &dtls); err != nil {
    92  		return err
    93  	}
    94  
    95  	j.Details = dtls
    96  	return nil
    97  }