Skip to content

Commit

Permalink
Add generated notice at the top of generated file (#55)
Browse files Browse the repository at this point in the history
* Add generated notice at the top of generated file

* Reword variable name
  • Loading branch information
rytswd committed Sep 28, 2021
1 parent e5aa048 commit 34ea4c9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 4 deletions.
45 changes: 41 additions & 4 deletions internal/file/write.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,52 @@
package file

import "os"
import (
"fmt"
"os"
"path/filepath"
)

// WriteAfterTo writes the processed content to the provided filepath.
func (f *File) WriteAfterTo(filepath string) error {
file, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
func (f *File) WriteAfterTo(targetFilePath string) error {
file, err := os.OpenFile(targetFilePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer file.Close()

_, err = file.Write(f.ContentAfter)
content := []byte{}
content = append(content, f.prepareGeneratedHeader(targetFilePath)...)
content = append(content, f.ContentAfter...)

_, err = file.Write(content)
return err
}

func (f *File) prepareGeneratedHeader(targetFilePath string) []byte {
fileType := filepath.Ext(f.FileName)

comment := `# == %s ==`
switch fileType {
case ".md":
comment = `<!-- == %s == -->`
case ".yaml", ".yml":
comment = `# == %s ==`
default:
}

// Compare directories of each file, rather than file itself, so that we
// don't end up with an extra "../".
relDir, err := filepath.Rel(filepath.Dir(targetFilePath), filepath.Dir(f.FileName))
if err != nil {
// This shouldn't happen, but when it does, simply ignore and return an
// empty slice.
return nil
}

baseFile := fmt.Sprintf("%s/%s", relDir, filepath.Base(f.FileName))
note := fmt.Sprintf(`improter-generated-from: %s`, baseFile)

x := fmt.Sprintf(comment+"\n", note)

return []byte(x)
}
9 changes: 9 additions & 0 deletions testdata/other/demo-generated.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!-- == improter-generated-from: ../markdown/demo-before.md == -->
# Markdown Demo

<!-- == imptr: short-description / begin from: ./snippet-description.md#[for-demo] == -->
This demonstrates how a markdown can import other file content.

Importer is a CLI tool to read and process Importer and Exporter markers.
This can be easily integrated into CI/CD and automation setup.
<!-- == imptr: short-description / end == -->

0 comments on commit 34ea4c9

Please sign in to comment.