github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/cmd/fns/initialization/base/hooks.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 NewHooksFile(dir string) (f *HooksFile, err error) { 29 if !filepath.IsAbs(dir) { 30 dir, err = filepath.Abs(dir) 31 if err != nil { 32 err = errors.Warning("fns: new hooks file failed").WithCause(err).WithMeta("dir", dir) 33 return 34 } 35 } 36 dir = filepath.ToSlash(filepath.Join(dir, "hooks")) 37 f = &HooksFile{ 38 dir: dir, 39 filename: filepath.ToSlash(filepath.Join(dir, "doc.go")), 40 } 41 return 42 } 43 44 type HooksFile struct { 45 dir string 46 filename string 47 } 48 49 func (f *HooksFile) Name() (name string) { 50 name = f.filename 51 return 52 } 53 54 func (f *HooksFile) Write(_ context.Context) (err error) { 55 if !files.ExistFile(f.dir) { 56 mdErr := os.MkdirAll(f.dir, 0644) 57 if mdErr != nil { 58 err = errors.Warning("fnc: hooks file write failed").WithCause(mdErr).WithMeta("dir", f.dir) 59 return 60 } 61 } 62 const ( 63 content = `// Package hooks 64 // read https://github.com/aacfactory/fns/blob/main/docs/hooks.md for more details. 65 package hooks` 66 ) 67 writeErr := os.WriteFile(f.filename, []byte(content), 0644) 68 if writeErr != nil { 69 err = errors.Warning("fns: hooks file write failed").WithCause(writeErr).WithMeta("filename", f.filename) 70 return 71 } 72 return 73 }