Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add addPath option #57

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions pkg/transform/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ type TransformationConfig struct {
// TODO(bwplotka): Explain ** and * suffixes and ability to specify "invalid" paths like "/../".
Path string

// Add is an optional path for a file to be created with certain frontMatter.
// Only parses frontMatter and cannot be mentioned alongside path and glob.
AddPath string `yaml:"addPath"`
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this work, but I think I am not a fan of this approach. This is a little bit mix of functionalities. We do go through transformations and we don't transform any old things here. Also why the only frontmatter if the whole file is empty? Also where the new file is put? In provided path? What if we want to provide a file next to another file we traverse?

I think it will be unwise to abstract all Linux commands within the transform configuration ): It's so easy to create this file with simple echo ... > file.

One functionality which would be harder with Linux commands (harder than 3 words) is to add certain file content next to another file we traverse with glob 🤔

I think I would prefer something simple for now like ExtraFiles with content template or something like this 🤔

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also why the only frontmatter if the whole file is empty?

Creating a new file, with just frontmatter, was the use case I was aiming to fulfill with this, as seen here in Thanos.

Also where the new file is put? In provided path? What if we want to provide a file next to another file we traverse?

Yes, it is put in the provided path. For putting a new file next to a particular file we traverse, I think we can just mention path of the file we want to place it next to...but yes, addPath cannot work with glob.

I think it will be unwise to abstract all Linux commands within the transform configuration ): It's so easy to create this file with simple echo ... > file.

Yes, I see your point. Will try to make this simpler with ExtraFiles and content! 🙂


// FrontMatter holds front matter transformations.
FrontMatter *MatterConfig `yaml:"frontMatter"`

Expand Down Expand Up @@ -153,9 +157,17 @@ func ParseConfig(c []byte) (Config, error) {
cfg.OutputDir = strings.TrimSuffix(cfg.OutputDir, "/")

for _, f := range cfg.Transformations {
f._glob, err = glob.Compile(f.Glob, '/')
if err != nil {
return Config{}, errors.Wrapf(err, "compiling glob %v", f.Glob)
if f.Glob != "" {
f._glob, err = glob.Compile(f.Glob, '/')
if err != nil {
return Config{}, errors.Wrapf(err, "compiling glob %v", f.Glob)
}
}

if f.AddPath != "" {
if f.Path != "" || f._glob != nil {
return Config{}, errors.Wrapf(err, "addPath with glob or path %v, %v, %v", f.AddPath, f.Path, f.Glob)
}
}

if f.FrontMatter != nil {
Expand Down
15 changes: 15 additions & 0 deletions pkg/transform/testdata/expected/test4/4/Proposals/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
title: Proposals
slug: README.md
lastmod: 'TODO: Allow testing last mod .Origin.LastMod'
---

[RelLink](../README.md)

[RelLink](../Team/doc.md)

This should not work: [RelLink](../../test.md)

---

Found a typo, inconsistency or missing information in our docs? Help us to improve [Thanos](https://thanos.io) documentation by proposing a fix [on GitHub here](https://github.com/thanos-io/thanos/edit/main/docs/README.md) :heart:
23 changes: 23 additions & 0 deletions pkg/transform/testdata/expected/test4/4/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
title: Group Handbook
cascade:
- _target:
path: /**
type: docs
---

Yolo

[RelLink](Proposals/README.md)

[RelLink](Team/doc.md)

![Image](logo.png)

![Image](images/logo2.png)

![Outside](../../../../main.go)

---

Found a typo, inconsistency or missing information in our docs? Help us to improve [Thanos](https://thanos.io) documentation by proposing a fix [on GitHub here](https://github.com/thanos-io/thanos/edit/main/docs/README.md) :heart:
11 changes: 11 additions & 0 deletions pkg/transform/testdata/expected/test4/4/Team/doc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Some Doc

[RelLink](#some-doc)

[RelLink](../README.md#group-handbook)

[RelLink](../Proposals/README.md)

---

Found a typo, inconsistency or missing information in our docs? Help us to improve [Thanos](https://thanos.io) documentation by proposing a fix [on GitHub here](https://github.com/thanos-io/thanos/edit/main/docs/doc.md) :heart:
5 changes: 5 additions & 0 deletions pkg/transform/testdata/expected/test4/4/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
weight: 100000
---


Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
49 changes: 49 additions & 0 deletions pkg/transform/testdata/mdox4.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
version: 1

inputDir: "testdata/testproj"
outputDir: "testdata/tmp/test4/4"

gitIgnored: true

transformations:

- addPath: _index.md
frontMatter:
template: |
weight: 100000

- glob: "README.md"
path: README.md
frontMatter:
template: |
title: "{{ .Origin.FirstHeader }}"

cascade:
- type: "docs"
_target:
path: "/**"
backMatter:
template: |
Found a typo, inconsistency or missing information in our docs?
Help us to improve [Thanos](https://thanos.io) documentation by proposing a fix [on GitHub here](https://github.com/thanos-io/thanos/edit/main/docs/{{ .Origin.Filename }}) :heart:

- glob: "**/README.md"
frontMatter:
template: |
title: "{{ .Origin.FirstHeader }}"
lastmod: "TODO: Allow testing last mod .Origin.LastMod"
slug: "{{ .Target.FileName }}"
backMatter:
template: |
Found a typo, inconsistency or missing information in our docs?
Help us to improve [Thanos](https://thanos.io) documentation by proposing a fix [on GitHub here](https://github.com/thanos-io/thanos/edit/main/docs/{{ .Origin.Filename }}) :heart:


- glob: "**.md"
backMatter:
template: |
Found a typo, inconsistency or missing information in our docs?
Help us to improve [Thanos](https://thanos.io) documentation by proposing a fix [on GitHub here](https://github.com/thanos-io/thanos/edit/main/docs/{{ .Origin.Filename }}) :heart:

- glob: "**"
path: "/../4static/**"
51 changes: 49 additions & 2 deletions pkg/transform/transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"strings"
"time"

"github.com/bwplotka/mdox/pkg/mdformatter"
"github.com/efficientgo/tools/core/pkg/errcapture"
Expand Down Expand Up @@ -48,6 +49,46 @@ func prepOutputDir(d string, gitIgnored bool) error {
return nil
}

func createNewFiles(ctx context.Context, trs []*TransformationConfig, outputDir string, logger log.Logger) error {
for _, tr := range trs {
if tr.AddPath == "" {
continue
}
msg := "creating new file"
target := filepath.Join(outputDir, tr.AddPath)
_, err := os.Create(target)
if err != nil {
return errors.Wrapf(err, "creating new file %v", target)
}

var opts []mdformatter.Option
if tr.FrontMatter != nil {
if !isMDFile(target) {
return errors.Errorf("front matter option set on file that is non-markdown: %v", target)
}
msg = "creating new file with transformation"

_, targetFilename := filepath.Split(target)
opts = append(opts, mdformatter.WithFrontMatterTransformer(&frontMatterTransformer{
c: tr.FrontMatter,
origin: MatterOrigin{
LastMod: time.Now().String(),
},
target: MatterTarget{
FileName: targetFilename,
},
}))
}
level.Debug(logger).Log("msg", msg, "target", target)

err = mdformatter.Format(ctx, logger, []string{target}, opts...)
if err != nil {
return err
}
}
return nil
}

// Dir transforms directory using given configuration file.
func Dir(ctx context.Context, logger log.Logger, config []byte) error {
c, err := ParseConfig(config)
Expand All @@ -59,6 +100,10 @@ func Dir(ctx context.Context, logger log.Logger, config []byte) error {
return err
}

if err = createNewFiles(ctx, c.Transformations, c.OutputDir, logger); err != nil {
return err
}

tr := &transformer{
ctx: ctx,
c: c,
Expand Down Expand Up @@ -374,8 +419,10 @@ func (f *backMatterTransformer) Close(mdformatter.SourceContext) error { return

func firstMatch(absRelPath string, trs []*TransformationConfig) (*TransformationConfig, bool) {
for _, tr := range trs {
if tr._glob.Match(absRelPath) {
return tr, true
if tr._glob != nil {
if tr._glob.Match(absRelPath) {
return tr, true
}
}
}
return nil, false
Expand Down
9 changes: 8 additions & 1 deletion pkg/transform/transform_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,26 @@ func TestTransform(t *testing.T) {
testutil.Ok(t, transform.Dir(context.Background(), logger, mdox1))
assertDirContent(t, filepath.Join(testData, "expected", "test1"), filepath.Join(tmpDir, "test1"))
})

t.Run("mdox2.yaml", func(t *testing.T) {
mdox2, err := ioutil.ReadFile(filepath.Join(testData, "mdox2.yaml"))
testutil.Ok(t, err)
testutil.Ok(t, transform.Dir(context.Background(), logger, mdox2))
assertDirContent(t, filepath.Join(testData, "expected", "test2"), filepath.Join(tmpDir, "test2"))

})

t.Run("mdox3.yaml", func(t *testing.T) {
mdox2, err := ioutil.ReadFile(filepath.Join(testData, "mdox3.yaml"))
testutil.Ok(t, err)
testutil.Ok(t, transform.Dir(context.Background(), logger, mdox2))
assertDirContent(t, filepath.Join(testData, "expected", "test3"), filepath.Join(tmpDir, "test3"))
})

t.Run("mdox4.yaml", func(t *testing.T) {
mdox2, err := ioutil.ReadFile(filepath.Join(testData, "mdox4.yaml"))
testutil.Ok(t, err)
testutil.Ok(t, transform.Dir(context.Background(), logger, mdox2))
assertDirContent(t, filepath.Join(testData, "expected", "test4"), filepath.Join(tmpDir, "test4"))
})
}

Expand Down