gitlab.com/evatix-go/core@v1.3.55/chmodhelper/SimpleFileReaderWriter.go (about)

     1  package chmodhelper
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"os"
     9  	"path"
    10  	"path/filepath"
    11  	"reflect"
    12  	"strings"
    13  
    14  	"gitlab.com/evatix-go/core/constants"
    15  	"gitlab.com/evatix-go/core/coredata/corejson"
    16  )
    17  
    18  type SimpleFileReaderWriter struct {
    19  	ChmodDir, ChmodFile    os.FileMode
    20  	ParentDir              string // full path to the parent dir
    21  	FilePath               string // full path to the actual file to write to or read from.
    22  	IsMustChmodApplyOnFile bool
    23  	IsApplyChmodOnMismatch bool
    24  }
    25  
    26  func (it SimpleFileReaderWriter) InitializeDefault(
    27  	isMustApplyChmod bool,
    28  ) *SimpleFileReaderWriter {
    29  	filePath := path.Clean(it.FilePath)
    30  	parentDir := it.ParentDir
    31  
    32  	if parentDir == "" {
    33  		parentDir = filepath.Dir(filePath)
    34  	}
    35  
    36  	return &SimpleFileReaderWriter{
    37  		ChmodDir:               it.ChmodDir,
    38  		ChmodFile:              it.ChmodFile,
    39  		ParentDir:              parentDir,
    40  		FilePath:               filePath,
    41  		IsMustChmodApplyOnFile: isMustApplyChmod,
    42  		IsApplyChmodOnMismatch: true,
    43  	}
    44  }
    45  
    46  func (it SimpleFileReaderWriter) InitializeDefaultApplyChmod() *SimpleFileReaderWriter {
    47  	return it.InitializeDefault(true)
    48  }
    49  
    50  func (it SimpleFileReaderWriter) IsParentExist() bool {
    51  	return IsPathExists(it.ParentDir)
    52  }
    53  
    54  func (it SimpleFileReaderWriter) IsExist() bool {
    55  	return IsPathExists(it.FilePath)
    56  }
    57  
    58  func (it SimpleFileReaderWriter) HasPathIssues() bool {
    59  	return !IsPathExists(it.FilePath)
    60  }
    61  
    62  func (it SimpleFileReaderWriter) IsPathInvalid() bool {
    63  	return !IsPathExists(it.FilePath)
    64  }
    65  
    66  func (it SimpleFileReaderWriter) IsParentDirInvalid() bool {
    67  	return !IsPathExists(it.ParentDir)
    68  }
    69  
    70  // HasAnyIssues
    71  //
    72  //  it.IsPathInvalid() || it.IsParentDirInvalid()
    73  func (it SimpleFileReaderWriter) HasAnyIssues() bool {
    74  	return it.IsPathInvalid() || it.IsParentDirInvalid()
    75  }
    76  
    77  func (it *SimpleFileReaderWriter) ChmodApplier() fwChmodApplier {
    78  	return fwChmodApplier{
    79  		rw: it,
    80  	}
    81  }
    82  
    83  func (it *SimpleFileReaderWriter) ChmodVerifier() fwChmodVerifier {
    84  	return fwChmodVerifier{
    85  		rw: it,
    86  	}
    87  }
    88  
    89  func (it SimpleFileReaderWriter) Write(allBytes []byte) error {
    90  	err := SimpleFileWriter.WriteFile(
    91  		it.ChmodDir,
    92  		it.ChmodFile,
    93  		it.IsMustChmodApplyOnFile,
    94  		it.IsApplyChmodOnMismatch,
    95  		true,
    96  		it.ParentDir,
    97  		it.FilePath,
    98  		allBytes)
    99  
   100  	if err == nil {
   101  		return nil
   102  	}
   103  
   104  	return it.errorWrap(err)
   105  }
   106  
   107  func (it SimpleFileReaderWriter) InitializeDefaultNew() (newRw *SimpleFileReaderWriter) {
   108  	return New.SimpleFileReaderWriter.Default(
   109  		it.FilePath)
   110  }
   111  
   112  func (it SimpleFileReaderWriter) NewPath(
   113  	newLocation string,
   114  ) (newRw *SimpleFileReaderWriter) {
   115  	return New.SimpleFileReaderWriter.Path(
   116  		it.ChmodDir,
   117  		it.ChmodFile,
   118  		newLocation)
   119  }
   120  
   121  func (it SimpleFileReaderWriter) NewPathJoin(
   122  	newLocationsFromParentDir ...string,
   123  ) (newRw *SimpleFileReaderWriter) {
   124  	joined := strings.Join(
   125  		newLocationsFromParentDir,
   126  		constants.ForwardSlash)
   127  	newLocation := filepath.Join(
   128  		it.ParentDir,
   129  		joined)
   130  
   131  	return New.SimpleFileReaderWriter.Path(
   132  		it.ChmodDir,
   133  		it.ChmodFile,
   134  		newLocation)
   135  }
   136  
   137  func (it SimpleFileReaderWriter) WriteString(content string) error {
   138  	err := SimpleFileWriter.WriteFileString(
   139  		it.ChmodDir,
   140  		it.ChmodFile,
   141  		it.IsMustChmodApplyOnFile,
   142  		it.IsApplyChmodOnMismatch,
   143  		true,
   144  		it.ParentDir,
   145  		it.FilePath,
   146  		content)
   147  
   148  	if err == nil {
   149  		return nil
   150  	}
   151  
   152  	return it.errorWrap(err)
   153  }
   154  
   155  func (it SimpleFileReaderWriter) errorWrap(err error) error {
   156  	if err == nil {
   157  		return nil
   158  	}
   159  
   160  	message := fmt.Sprintf(
   161  		"err: %s simple-reader-writer: %s",
   162  		err.Error(),
   163  		it.String(),
   164  	)
   165  
   166  	return errors.New(message)
   167  }
   168  
   169  func (it SimpleFileReaderWriter) WriteAny(
   170  	anyItem interface{},
   171  ) error {
   172  	err := SimpleFileWriter.WriteAnyItem(
   173  		it.ChmodDir,
   174  		it.ChmodFile,
   175  		it.ParentDir,
   176  		it.FilePath,
   177  		anyItem)
   178  
   179  	if err == nil {
   180  		return nil
   181  	}
   182  
   183  	return it.errorWrap(err)
   184  }
   185  
   186  func (it SimpleFileReaderWriter) WriteAnyLock(
   187  	anyItem interface{},
   188  ) error {
   189  	SimpleFileWriter.Lock()
   190  	defer SimpleFileWriter.Unlock()
   191  
   192  	return it.WriteAny(anyItem)
   193  }
   194  
   195  func (it SimpleFileReaderWriter) ReadMust() []byte {
   196  	allBytes, err := it.Read()
   197  
   198  	if err != nil {
   199  		panic(err)
   200  	}
   201  
   202  	return allBytes
   203  }
   204  
   205  func (it SimpleFileReaderWriter) ReadString() (content string, err error) {
   206  	allBytes, err := it.Read()
   207  
   208  	if len(allBytes) > 0 {
   209  		return string(allBytes), err
   210  	}
   211  
   212  	return "", err
   213  }
   214  
   215  func (it SimpleFileReaderWriter) ReadStringMust() (content string) {
   216  	content, err := it.ReadString()
   217  
   218  	if err != nil {
   219  		panic(err)
   220  	}
   221  
   222  	return content
   223  }
   224  
   225  func (it SimpleFileReaderWriter) ReadStringLock() (content string, err error) {
   226  	SimpleFileWriter.Lock()
   227  	defer SimpleFileWriter.Unlock()
   228  
   229  	return it.ReadString()
   230  }
   231  
   232  func (it SimpleFileReaderWriter) Read() ([]byte, error) {
   233  	allBytes, err := ioutil.ReadFile(it.FilePath)
   234  
   235  	if err == nil {
   236  		return allBytes, err
   237  	}
   238  
   239  	message := fmt.Sprintf(
   240  		"cannot read file: %q, err: %s simple-reader-writer: %s",
   241  		it.FilePath,
   242  		err.Error(),
   243  		it.String(),
   244  	)
   245  
   246  	return allBytes, errors.New(message)
   247  }
   248  
   249  func (it SimpleFileReaderWriter) ReadLock() ([]byte, error) {
   250  	SimpleFileWriter.Lock()
   251  	defer SimpleFileWriter.Unlock()
   252  
   253  	return it.Read()
   254  }
   255  
   256  func (it SimpleFileReaderWriter) ReadOnExist() ([]byte, error) {
   257  	if it.IsExist() {
   258  		return it.Read()
   259  	}
   260  
   261  	return nil, nil
   262  }
   263  
   264  func (it SimpleFileReaderWriter) ReadStringOnExist() (content string, err error) {
   265  	if it.IsExist() {
   266  		return it.ReadString()
   267  	}
   268  
   269  	return "", nil
   270  }
   271  
   272  func (it SimpleFileReaderWriter) ReadStringOnExistLock() (content string, err error) {
   273  	SimpleFileWriter.Lock()
   274  	defer SimpleFileWriter.Unlock()
   275  
   276  	return it.ReadStringOnExist()
   277  }
   278  
   279  func (it SimpleFileReaderWriter) ReadOnExistLock() ([]byte, error) {
   280  	SimpleFileWriter.Lock()
   281  	defer SimpleFileWriter.Unlock()
   282  
   283  	return it.ReadOnExist()
   284  }
   285  
   286  func (it SimpleFileReaderWriter) Get(toPtr interface{}) error {
   287  	if it.IsExist() {
   288  		return it.getOnExist(toPtr)
   289  	}
   290  
   291  	return it.errorWrap(errors.New("cannot read cache, save first, file not exist: " + it.FilePath))
   292  }
   293  
   294  func (it SimpleFileReaderWriter) GetLock(toPtr interface{}) error {
   295  	SimpleFileWriter.Lock()
   296  	defer SimpleFileWriter.Unlock()
   297  
   298  	return it.Get(toPtr)
   299  }
   300  
   301  func (it SimpleFileReaderWriter) ReadWrite(
   302  	readToPtr interface{},
   303  	onInvalidGenerateFunc func() (interface{}, error),
   304  ) error {
   305  	return it.GetSet(
   306  		readToPtr,
   307  		onInvalidGenerateFunc)
   308  }
   309  
   310  func (it SimpleFileReaderWriter) ReadWriteLock(
   311  	readToPtr interface{},
   312  	onInvalidGenerateFunc func() (interface{}, error),
   313  ) error {
   314  	return it.GetSetLock(
   315  		readToPtr,
   316  		onInvalidGenerateFunc)
   317  }
   318  
   319  func (it SimpleFileReaderWriter) GetSetLock(
   320  	toPtr interface{},
   321  	onInvalidGenerateFunc func() (interface{}, error),
   322  ) error {
   323  	SimpleFileWriter.Lock()
   324  	defer SimpleFileWriter.Unlock()
   325  
   326  	return it.GetSet(
   327  		toPtr, onInvalidGenerateFunc)
   328  }
   329  
   330  func (it SimpleFileReaderWriter) GetSet(
   331  	toPtr interface{},
   332  	onInvalidGenerateFunc func() (interface{}, error),
   333  ) error {
   334  	readErr := it.Get(toPtr)
   335  	if readErr != nil {
   336  		// remove file
   337  		// fine swallow error
   338  		it.Expire()
   339  	}
   340  
   341  	newAnyItem, err := onInvalidGenerateFunc()
   342  
   343  	if err == nil {
   344  		// if things are all right
   345  		reflect.ValueOf(toPtr).Elem().Set(reflect.ValueOf(newAnyItem).Elem())
   346  
   347  		// save
   348  		return it.Set(newAnyItem)
   349  	}
   350  
   351  	return it.errorWrap(errors.New("read cache failed + cannot generate: " + err.Error()))
   352  }
   353  
   354  func (it SimpleFileReaderWriter) CacheGetSet(
   355  	toPtr interface{},
   356  	onInvalidGenerateFunc func() (interface{}, error),
   357  ) error {
   358  	return it.GetSet(
   359  		toPtr,
   360  		onInvalidGenerateFunc)
   361  }
   362  
   363  func (it SimpleFileReaderWriter) CacheGetSetLock(
   364  	toPtr interface{},
   365  	onInvalidGenerateFunc func() (interface{}, error),
   366  ) error {
   367  	return it.GetSetLock(
   368  		toPtr,
   369  		onInvalidGenerateFunc)
   370  }
   371  
   372  // Deserialize
   373  //
   374  //  alias for Get
   375  func (it SimpleFileReaderWriter) Deserialize(
   376  	toPtr interface{},
   377  ) error {
   378  	return it.Get(toPtr)
   379  }
   380  
   381  // DeserializeLock
   382  //
   383  //  alias for Get
   384  func (it SimpleFileReaderWriter) DeserializeLock(
   385  	toPtr interface{},
   386  ) error {
   387  	return it.GetLock(toPtr)
   388  }
   389  
   390  // Serialize
   391  //
   392  //  alias for ReadOnExist
   393  func (it SimpleFileReaderWriter) Serialize() ([]byte, error) {
   394  	return it.ReadOnExist()
   395  }
   396  
   397  // SerializeLock
   398  //
   399  //  alias for ReadOnExist
   400  func (it SimpleFileReaderWriter) SerializeLock() ([]byte, error) {
   401  	return it.ReadOnExistLock()
   402  }
   403  
   404  // Set
   405  //
   406  //  alias for WriteAny
   407  func (it SimpleFileReaderWriter) Set(toPtr interface{}) error {
   408  	return it.WriteAny(toPtr)
   409  }
   410  
   411  func (it SimpleFileReaderWriter) SetLock(toPtr interface{}) error {
   412  	return it.WriteAnyLock(toPtr)
   413  }
   414  
   415  // Expire
   416  //
   417  //  Removes file on exist only
   418  //  alias for RemoveOnExist
   419  func (it SimpleFileReaderWriter) Expire() error {
   420  	if it.IsExist() {
   421  		return os.RemoveAll(it.FilePath)
   422  	}
   423  
   424  	return nil
   425  }
   426  
   427  // ExpireLock
   428  //
   429  //  Removes file on exist only
   430  //  alias for RemoveOnExist
   431  func (it SimpleFileReaderWriter) ExpireLock() error {
   432  	SimpleFileWriter.Lock()
   433  	defer SimpleFileWriter.Unlock()
   434  
   435  	return it.Expire()
   436  }
   437  
   438  // OsFile
   439  //
   440  //  Os open files must be closed
   441  func (it SimpleFileReaderWriter) OsFile() (*os.File, error) {
   442  	return os.Open(it.FilePath)
   443  }
   444  
   445  // ExpireParentDir
   446  //
   447  //  warning: recursive process remove all files in it, undoable.
   448  func (it SimpleFileReaderWriter) ExpireParentDir() error {
   449  	if it.IsParentExist() {
   450  		return os.RemoveAll(it.ParentDir)
   451  	}
   452  
   453  	return nil
   454  }
   455  
   456  // ExpireParentDirLock
   457  //
   458  //  warning: recursive process remove all files in it, undoable.
   459  func (it SimpleFileReaderWriter) ExpireParentDirLock() error {
   460  	SimpleFileWriter.Lock()
   461  	defer SimpleFileWriter.Unlock()
   462  
   463  	return it.ExpireParentDir()
   464  }
   465  
   466  func (it SimpleFileReaderWriter) RemoveOnExist() error {
   467  	return it.Expire()
   468  }
   469  
   470  // RemoveDirOnExist
   471  //
   472  //  alias for ExpireParentDir
   473  //  warning: recursive process remove all files in it, undoable.
   474  func (it SimpleFileReaderWriter) RemoveDirOnExist() error {
   475  	return it.ExpireParentDir()
   476  }
   477  
   478  func (it SimpleFileReaderWriter) getOnExist(toPtr interface{}) error {
   479  	allBytes, err := it.Read()
   480  
   481  	if err != nil {
   482  		return err
   483  	}
   484  
   485  	return corejson.Deserialize.UsingBytes(
   486  		allBytes,
   487  		toPtr)
   488  }
   489  
   490  func (it SimpleFileReaderWriter) String() string {
   491  	jsonString, err := json.Marshal(it)
   492  
   493  	if err != nil {
   494  		return err.Error()
   495  	}
   496  
   497  	return string(jsonString)
   498  }
   499  
   500  func (it SimpleFileReaderWriter) Clone() SimpleFileReaderWriter {
   501  	return SimpleFileReaderWriter{
   502  		ChmodDir:  it.ChmodDir,
   503  		ChmodFile: it.ChmodFile,
   504  		ParentDir: it.ParentDir,
   505  		FilePath:  it.FilePath,
   506  	}
   507  }
   508  
   509  func (it *SimpleFileReaderWriter) ClonePtr() *SimpleFileReaderWriter {
   510  	if it == nil {
   511  		return nil
   512  	}
   513  
   514  	return &SimpleFileReaderWriter{
   515  		ChmodDir:  it.ChmodDir,
   516  		ChmodFile: it.ChmodFile,
   517  		ParentDir: it.ParentDir,
   518  		FilePath:  it.FilePath,
   519  	}
   520  }
   521  
   522  func (it SimpleFileReaderWriter) MarshalJSON() ([]byte, error) {
   523  	model := simpleFileReaderWriterModel{
   524  		ChmodDir:  New.RwxWrapper.UsingFileMode(it.ChmodDir),
   525  		ChmodFile: New.RwxWrapper.UsingFileMode(it.ChmodFile),
   526  		ParentDir: it.ParentDir,
   527  		FilePath:  it.FilePath,
   528  	}
   529  
   530  	return corejson.Serialize.Raw(model)
   531  }
   532  
   533  func (it *SimpleFileReaderWriter) UnmarshalJSON(jsonBytes []byte) error {
   534  	var model simpleFileReaderWriterModel
   535  	err := corejson.Deserialize.UsingBytes(
   536  		jsonBytes, &model)
   537  
   538  	if err == nil {
   539  		// success
   540  		it.ChmodDir = model.ChmodDir.ToFileMode()
   541  		it.ChmodFile = model.ChmodFile.ToFileMode()
   542  		it.ParentDir = model.ParentDir
   543  		it.FilePath = model.FilePath
   544  	}
   545  
   546  	return err
   547  }
   548  
   549  func (it SimpleFileReaderWriter) Json() corejson.Result {
   550  	return corejson.New(it)
   551  }
   552  
   553  func (it SimpleFileReaderWriter) JsonPtr() *corejson.Result {
   554  	return corejson.NewPtr(it)
   555  }
   556  
   557  func (it *SimpleFileReaderWriter) JsonParseSelfInject(
   558  	jsonResult *corejson.Result,
   559  ) error {
   560  	return jsonResult.Deserialize(it)
   561  }
   562  
   563  func (it SimpleFileReaderWriter) AsJsonContractsBinder() corejson.JsonContractsBinder {
   564  	return &it
   565  }