github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/core/io/tmp.go (about) 1 package io 2 3 import ( 4 "crypto/md5" 5 "encoding/hex" 6 "io" 7 "os" 8 "strconv" 9 "time" 10 11 "github.com/lmorg/murex/lang" 12 "github.com/lmorg/murex/lang/types" 13 "github.com/lmorg/murex/utils/consts" 14 ) 15 16 func init() { 17 lang.DefineMethod("tmp", cmdTempFile, types.Any, types.String) 18 } 19 20 func cmdTempFile(p *lang.Process) error { 21 p.Stdout.SetDataType(types.String) 22 23 ext, _ := p.Parameters.String(0) 24 if ext != "" { 25 ext = "." + ext 26 } 27 28 fileId := time.Now().String() + ":" + strconv.Itoa(int(p.Id)) 29 30 h := md5.New() 31 _, err := h.Write([]byte(fileId)) 32 if err != nil { 33 return err 34 } 35 36 name := consts.TempDir + hex.EncodeToString(h.Sum(nil)) + "-" + strconv.Itoa(os.Getpid()) + ext 37 38 file, err := os.Create(name) 39 if err != nil { 40 return err 41 } 42 43 defer file.Close() 44 45 _, err = io.Copy(file, p.Stdin) 46 if err != nil { 47 return err 48 } 49 50 _, err = p.Stdout.Write([]byte(name)) 51 return err 52 }