github.com/dancsecs/gotomd@v0.0.0-20240310162206-65c4805cf510/process_in_place.go (about)

     1  /*
     2     Golang To Github Markdown Utility: gotomd
     3     Copyright (C) 2023, 2024 Leslie Dancsecs
     4  
     5     This program is free software: you can redistribute it and/or modify
     6     it under the terms of the GNU General Public License as published by
     7     the Free Software Foundation, either version 3 of the License, or
     8     (at your option) any later version.
     9  
    10     This program is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13     GNU General Public License for more details.
    14  
    15     You should have received a copy of the GNU General Public License
    16     along with this program.  If not, see <https://www.gnu.org/licenses/>.
    17  */
    18  
    19  package main
    20  
    21  import (
    22  	"bytes"
    23  	"log"
    24  	"os"
    25  	"path/filepath"
    26  	"strings"
    27  )
    28  
    29  func replaceMDInPlace(rPath string) error {
    30  	var (
    31  		err         error
    32  		rDir, rFile string
    33  		wDir, wFile string
    34  		wPath       string
    35  		fileBytes   []byte
    36  		res         string
    37  	)
    38  
    39  	rDir, rFile = filepath.Split(rPath)
    40  	wDir = rDir
    41  
    42  	if outputDir != "." {
    43  		wDir = outputDir
    44  	}
    45  
    46  	wFile = rFile
    47  	wPath = filepath.Join(wDir, wFile)
    48  
    49  	fileBytes, err = os.ReadFile(rPath) //nolint:gosec // Ok.
    50  
    51  	if verbose {
    52  		log.Printf("Expanding %s <inPlace> to: %s", rPath, wPath)
    53  	}
    54  
    55  	if err == nil {
    56  		fileData := string(bytes.TrimRight(fileBytes, "\n"))
    57  		res, err = cleanMarkDownDocument(fileData)
    58  	}
    59  
    60  	if err == nil {
    61  		res = strings.TrimRight(res, "\n")
    62  		res, err = updateMarkDownDocument(rDir, res)
    63  	}
    64  
    65  	if err == nil {
    66  		err = writeFile(wPath, res)
    67  	}
    68  
    69  	return err
    70  }