diff --git a/cmd/go-semantic-release/commands/changelog.go b/cmd/go-semantic-release/commands/changelog.go index 90a0227..c6cbcc8 100644 --- a/cmd/go-semantic-release/commands/changelog.go +++ b/cmd/go-semantic-release/commands/changelog.go @@ -8,6 +8,7 @@ import ( func init() { changelogCmd.Flags().Bool("checks", false, "Check for missing values and envs") + changelogCmd.Flags().Bool("overwrite", false, "Overwrite the content of the changelog. Default is to prepend the new changelog to the existing file.") changelogCmd.Flags().StringP("out", "o", "CHANGELOG.md", "Name of the file") rootCmd.AddCommand(changelogCmd) } @@ -31,6 +32,11 @@ var changelogCmd = &cobra.Command{ return err } + overwrite, err := cmd.Flags().GetBool("overwrite") + if err != nil { + return err + } + file, err := cmd.Flags().GetString("out") if err != nil { return err @@ -61,7 +67,6 @@ var changelogCmd = &cobra.Command{ if err != nil { return err } - - return s.WriteChangeLog(generatedChangelog.Content, file) + return s.WriteChangeLog(generatedChangelog.Content, file, overwrite) }, } diff --git a/pkg/semanticrelease/semantic-release.go b/pkg/semanticrelease/semantic-release.go index 8e605c1..f2a2252 100644 --- a/pkg/semanticrelease/semantic-release.go +++ b/pkg/semanticrelease/semantic-release.go @@ -2,10 +2,11 @@ package semanticrelease import ( "fmt" - "github.com/Nightapes/go-semantic-release/internal/integrations" - "io/ioutil" + "os" "time" + "github.com/Nightapes/go-semantic-release/internal/integrations" + "github.com/Masterminds/semver" log "github.com/sirupsen/logrus" @@ -194,8 +195,21 @@ func (s *SemanticRelease) GetChangelog(releaseVersion *shared.ReleaseVersion) (* } // WriteChangeLog writes changelog content to the given file -func (s *SemanticRelease) WriteChangeLog(changelogContent, file string) error { - return ioutil.WriteFile(file, []byte(changelogContent), 0644) +func (s *SemanticRelease) WriteChangeLog(changelogContent, file string, overwrite bool) error { + newContent := make([]byte, 0) + newContent = append(newContent, []byte(changelogContent)...) + + // only prepend the new changelog content if the the given file already exists + _, err := os.Stat(file) + if !overwrite && err == nil { + content, err := os.ReadFile(file) + if err != nil { + return err + } + newContent = append(newContent, []byte("\n---\n\n")...) + newContent = append(newContent, content...) + } + return os.WriteFile(file, newContent, 0644) } // Release publish release to provider