github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/cmd/fns/initialization/base/internals.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package base 19 20 import ( 21 "context" 22 "github.com/aacfactory/errors" 23 "github.com/aacfactory/fns/cmd/generates/files" 24 "os" 25 "path/filepath" 26 ) 27 28 func NewInternalGeneratorsFile(dir string) (f *InternalGeneratorsFile, err error) { 29 if !filepath.IsAbs(dir) { 30 dir, err = filepath.Abs(dir) 31 if err != nil { 32 err = errors.Warning("fns: new generator file failed").WithCause(err).WithMeta("dir", dir) 33 return 34 } 35 } 36 dir = filepath.ToSlash(filepath.Join(dir, "internal", "generator")) 37 38 f = &InternalGeneratorsFile{ 39 dir: dir, 40 filename: filepath.ToSlash(filepath.Join(dir, "main.go")), 41 } 42 return 43 } 44 45 type InternalGeneratorsFile struct { 46 filename string 47 dir string 48 } 49 50 func (f *InternalGeneratorsFile) Name() (name string) { 51 name = f.dir 52 return 53 } 54 55 func (f *InternalGeneratorsFile) Write(_ context.Context) (err error) { 56 if !files.ExistFile(f.dir) { 57 mdErr := os.MkdirAll(f.dir, 0644) 58 if mdErr != nil { 59 err = errors.Warning("fns: generator file write failed").WithCause(mdErr).WithMeta("dir", f.dir) 60 return 61 } 62 } 63 const ( 64 content = `package main 65 66 import ( 67 "context" 68 "fmt" 69 "github.com/aacfactory/fns/cmd/generates" 70 "os" 71 ) 72 73 func main() { 74 cmd := generates.New() 75 if err := cmd.Execute(context.Background(), os.Args...); err != nil { 76 fmt.Println(fmt.Sprintf("%+v", err)) 77 } 78 } 79 80 ` 81 ) 82 writeErr := os.WriteFile(f.filename, []byte(content), 0644) 83 if writeErr != nil { 84 err = errors.Warning("fns: generator file write failed").WithCause(writeErr).WithMeta("filename", f.filename) 85 return 86 } 87 return 88 }