github.com/iDigitalFlame/xmt@v0.5.4/examples/example_otto.go (about)

     1  // Copyright (C) 2020 - 2023 iDigitalFlame
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU General Public License as published by
     5  // the Free Software Foundation, either version 3 of the License, or
     6  // any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU General Public License
    14  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    15  //
    16  
    17  package main
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"time"
    23  	// You will have to enable the "sotto" package by renaming the "cmd/script/sotto/otto.go_"
    24  	// file to "cmd/script/sotto/otto.go" and run "go mod tidy; go mod verify".
    25  	//
    26  	// The un-comment the line below
    27  	// "github.com/iDigitalFlame/xmt/cmd/script/sotto"
    28  )
    29  
    30  const script1 = `
    31  // JavaScript test via Otto.
    32  //
    33  function derp() {
    34  	console.log("hello!");
    35  }
    36  
    37  derp();
    38  console.log(exec('pwd'));
    39  
    40  var a = 2;
    41  var v = exec("bash -c 'echo \"derp " + a + " value\" > /tmp/derp.txt'");
    42  console.log("got " + v);
    43  
    44  print("Sleeping 5 seconds..");
    45  sleep(0.5);
    46  print("Done!");
    47  
    48  var f = exec("cat /tmp/derp.txt");
    49  print("read " + f, f);
    50  exec("rm /tmp/derp.txt");
    51  `
    52  
    53  func exampleOtto() {
    54  	var (
    55  		l, c   = context.WithTimeout(context.Background(), time.Duration(20)*time.Second)
    56  		r, err = script1, l //  sotto.InvokeContext(l, script1)
    57  	)
    58  	fmt.Printf("output [%s], error[%s]\n", r, err)
    59  	c()
    60  }