Skip to content

Commit

Permalink
fix: Include source path comment if multiple args are given
Browse files Browse the repository at this point in the history
  • Loading branch information
gabe565 committed Aug 1, 2024
1 parent 1aa57dc commit 79235dc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
25 changes: 22 additions & 3 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,19 @@ func run(cmd *cobra.Command, args []string) error {
}
}

withSrcComment := len(args) > 1
if !withSrcComment {
for _, arg := range args {
stat, err := os.Stat(arg)
if err != nil {
return err
}
if withSrcComment = stat.IsDir(); withSrcComment {
break
}
}
}

var i int
for _, arg := range args {
if err := filepath.WalkDir(arg, func(path string, d fs.DirEntry, err error) error {
Expand All @@ -107,7 +120,7 @@ func run(cmd *cobra.Command, args []string) error {
}
i++

return openAndTemplateFile(conf, cmd.OutOrStdout(), arg, path)
return openAndTemplateFile(conf, cmd.OutOrStdout(), arg, path, withSrcComment)
}); err != nil {
return err
}
Expand All @@ -116,7 +129,7 @@ func run(cmd *cobra.Command, args []string) error {
return nil
}

func openAndTemplateFile(conf *config.Config, w io.Writer, dir, path string) error {
func openAndTemplateFile(conf *config.Config, w io.Writer, dir, path string, withSrcComment bool) error {
f, err := os.Open(path)
if err != nil {
return err
Expand Down Expand Up @@ -183,7 +196,13 @@ func openAndTemplateFile(conf *config.Config, w io.Writer, dir, path string) err
}
}
} else {
if rel, err := filepath.Rel(dir, path); err == nil && rel != "." {
rel := path
if !withSrcComment {
if rel, err = filepath.Rel(dir, path); err == nil && rel != "." {
withSrcComment = true
}
}
if withSrcComment {
source := "# Source: " + rel + "\n"
if !strings.HasPrefix(s, "---") {
s = source + s
Expand Down
2 changes: 1 addition & 1 deletion cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ func Test_openAndTemplateFile(t *testing.T) {
require.NoError(t, err)

var stdoutBuf strings.Builder
err = openAndTemplateFile(tt.args.conf, &stdoutBuf, p, p)
err = openAndTemplateFile(tt.args.conf, &stdoutBuf, p, p, false)
tt.wantErr(t, err)

fileContents, err := os.ReadFile(p)
Expand Down

0 comments on commit 79235dc

Please sign in to comment.