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