Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
[feat] - use diff chan (#2387)
ahrav7b492a690a89
diff --git a/pkg/gitparse/gitparse.go b/pkg/gitparse/gitparse.goindex 1de5d7fea..1462b5c93 100644--- a/pkg/gitparse/gitparse.go+++ b/pkg/gitparse/gitparse.go@@ -105,6 +105,8 @@ type Diff struct {LineStart intIsBinary bool+ Commit *Commit+contentWriter contentWriter}@@ -118,9 +120,12 @@ func withCustomContentWriter(cr contentWriter) diffOption {return func(d *Diff) { d.contentWriter = cr }}-// NewDiff creates a new Diff with a threshold.-func NewDiff(opts ...diffOption) *Diff {- diff := new(Diff)+// newDiff creates a new Diff with a threshold and an associated commit.+// All Diffs must have an associated commit.+// The contentWriter is used to manage the diff's content, allowing for flexible handling of diff data.+// By default, a buffer is used as the contentWriter, but this can be overridden with a custom contentWriter.+func newDiff(commit *Commit, opts ...diffOption) *Diff {+ diff := &Diff{Commit: commit, contentWriter: newBuffer()}for _, opt := range opts {opt(diff)}@@ -151,59 +156,9 @@ type Commit struct {Author stringDate time.TimeMessage strings.Builder- Diffs []DiffSize int // in bytes}-// Equal compares the content of two Commits to determine if they are the same.-func (c1 *Commit) Equal(ctx context.Context, c2 *Commit) bool {- switch {- case c1.Hash != c2.Hash:- return false- case c1.Author != c2.Author:- return false- case !c1.Date.Equal(c2.Date):- return false- case c1.Message.String() != c2.Message.String():- return false- case len(c1.Diffs) != len(c2.Diffs):- return false- }-- // isEqualString handles the error-prone String() method calls and compares the results.- isEqualContentString := func(s1, s2 contentWriter) (bool, error) {- str1, err := s1.String()- if err != nil {- return false, err- }- str2, err := s2.String()- if err != nil {- return false, err- }- return str1 == str2, nil- }-- for i := range c1.Diffs {- d1 := c1.Diffs[i]- d2 := c2.Diffs[i]- switch {- case d1.PathB != d2.PathB:- return false- case d1.LineStart != d2.LineStart:- return false- case d1.IsBinary != d2.IsBinary:- return false- default:- equal, err := isEqualContentString(d1.contentWriter, d2.contentWriter)- if err != nil || !equal {- ctx.Logger().Error(err, "failed to compare diff content")- return false- }- }- }- return true-}-// Parser sets values used in GitParse.type Parser struct {maxDiffSize int@@ -296,7 +251,8 @@ func NewParser(options ...Option) *Parser {}// RepoPath parses the output of the `git log` command for the `source` path.-func (c *Parser) RepoPath(ctx context.Context, source string, head string, abbreviatedLog bool, excludedGlobs []string, isBare bool) (chan Commit, error) {+// The Diff chan will return diffs in the order they are parsed from the log.+func (c *Parser) RepoPath(ctx context.Context, source string, head string, abbreviatedLog bool, excludedGlobs []string, isBare bool) (chan *Diff, error) {args := []string{"-C", source, "log", "-p", "--full-history", "--date=format:%a %b %d %H:%M:%S %Y %z"}if abbreviatedLog {args = append(args, "--diff-filter=AM")@@ -334,7 +290,7 @@ func (c *Parser) RepoPath(ctx context.Context, source string, head string, abbre}// Staged parses the output of the `git diff` command for the `source` path.-func (c *Parser) Staged(ctx context.Context, source string) (chan Commit, error) {+func (c *Parser) Staged(ctx context.Context, source string) (chan *Diff, error) {// Provide the --cached flag to diff to get the diff of the staged changes.args := []string{"-C", source, "diff", "-p", "--cached", "--full-history", "--diff-filter=AM", "--date=format:%a %b %d %H:%M:%S %Y %z"}@@ -349,21 +305,21 @@ func (c *Parser) Staged(ctx context.Context, source string) (chan Commit, error)}// executeCommand runs an exec.Cmd, reads stdout and stderr, and waits for the Cmd to complete.-func (c *Parser) executeCommand(ctx context.Context, cmd *exec.Cmd, isStaged bool) (chan Commit, error) {- commitChan := make(chan Commit, 64)+func (c *Parser) executeCommand(ctx context.Context, cmd *exec.Cmd, isStaged bool) (chan *Diff, error) {+ diffChan := make(chan *Diff, 64)stdOut, err := cmd.StdoutPipe()if err != nil {- return commitChan, err+ return diffChan, err}stdErr, err := cmd.StderrPipe()if err != nil {- return commitChan, err+ return diffChan, err}err = cmd.Start()if err != nil {- return commitChan, err+ return diffChan, err}go func() {@@ -374,7 +330,7 @@ func (c *Parser) executeCommand(ctx context.Context, cmd *exec.Cmd, isStaged boo}()go func() {- c.FromReader(ctx, stdOut, commitChan, isStaged)+ c.FromReader(ctx, stdOut, diffChan, isStaged)if err := stdOut.Close(); err != nil {ctx.Logger().V(2).Info("Error closing git stdout pipe.", "error", err)}@@ -383,10 +339,10 @@ func (c *Parser) executeCommand(ctx context.Context, cmd *exec.Cmd, isStaged boo}}()- return commitChan, nil+ return diffChan, nil}-func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan chan Commit, isStaged bool) {+func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, diffChan chan *Diff, isStaged bool) {outReader := bufio.NewReader(stdOut)var (currentCommit *Commit@@ -395,20 +351,20 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan ch)var latestState = Initial- diff := func(opts ...diffOption) *Diff {+ diff := func(c *Commit, opts ...diffOption) *Diff {opts = append(opts, withCustomContentWriter(newBuffer()))- return NewDiff(opts...)+ return newDiff(c, opts...)}if c.useCustomContentWriter {- diff = func(opts ...diffOption) *Diff {+ diff = func(c *Commit, opts ...diffOption) *Diff {opts = append(opts, withCustomContentWriter(bufferedfilewriter.New()))- return NewDiff(opts...)+ return newDiff(c, opts...)}}- currentDiff := diff()+ currentDiff := diff(currentCommit)defer common.RecoverWithExit(ctx)- defer close(commitChan)+ defer close(diffChan)for {if common.IsDone(ctx) {break@@ -425,10 +381,6 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan ch// If there is a currentDiff, add it to currentCommit.if currentDiff.Len() > 0 || currentDiff.IsBinary {- // TODO: Consider modifying the diffs field in the Commit struct to be a []*Diff.- // Otherwise, we end up with this temporal coupling where we have to finalize the diff- // before we can add it to the commit. I found this out the hard way when I tried to- // test this.if err := currentDiff.finalize(); err != nil {ctx.Logger().Error(err,@@ -439,17 +391,16 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan ch"latest_state", latestState.String(),)}- currentCommit.Diffs = append(currentCommit.Diffs, *currentDiff)+ diffChan <- currentDiffcurrentCommit.Size += currentDiff.Len()}// If there is a currentCommit, send it to the channel.if currentCommit != nil {- commitChan <- *currentCommittotalLogSize += currentCommit.Size}// Create a new currentDiff and currentCommit- currentDiff = diff()currentCommit = &Commit{Message: strings.Builder{}}+ currentDiff = diff(currentCommit)// Check that the commit line contains a hash and set it.if len(line) >= 47 {currentCommit.Hash = string(line[7:47])@@ -458,8 +409,8 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan chlatestState = MergeLinecase isAuthorLine(isStaged, latestState, line):latestState = AuthorLine-currentCommit.Author = strings.TrimRight(string(line[8:]), "\n")+case isDateLine(isStaged, latestState, line):latestState = DateLine@@ -473,8 +424,8 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan ch// NoOpcase isMessageLine(isStaged, latestState, line):latestState = MessageLine+ currentCommit.Message.Write(line[4:]) // Messages are indented by 4 spaces.- currentCommit.Message.Write(line[4:]) // Messages are indented with 4 spaces.case isMessageEndLine(isStaged, latestState, line):latestState = MessageEndLine// NoOp@@ -495,36 +446,16 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan ch"latest_state", latestState.String(),)}- currentCommit.Diffs = append(currentCommit.Diffs, *currentDiff)- // If the currentDiff is over 1GB, drop it into the channel so it isn't held in memory waiting for more commits.- totalSize := 0- for _, diff := range currentCommit.Diffs {- totalSize += diff.Len()- }- if totalSize > c.maxCommitSize {- oldCommit := currentCommit- commitChan <- *currentCommit- totalLogSize += currentCommit.Size- currentCommit = &Commit{- Hash: currentCommit.Hash,- Author: currentCommit.Author,- Date: currentCommit.Date,- Message: strings.Builder{},- Diffs: []Diff{},- }- // Message needs to be recreated here otherwise writing to it again will result in a panic.- currentCommit.Message.WriteString(oldCommit.Message.String())- }+ diffChan <- currentDiff}- currentDiff = diff()- // currentDiff = NewDiff(withCustomContentWriter(c.contentWriter()))- case isModeLine(isStaged, latestState, line):+ currentDiff = diff(currentCommit)+ case isModeLine(latestState, line):latestState = ModeLine// NoOp- case isIndexLine(isStaged, latestState, line):+ case isIndexLine(latestState, line):latestState = IndexLine// NoOp- case isBinaryLine(isStaged, latestState, line):+ case isBinaryLine(latestState, line):latestState = BinaryFileLinecurrentDiff.PathB = pathFromBinaryLine(line)@@ -533,15 +464,15 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan chif currentDiff.PathB != "" {currentDiff.IsBinary = true}- case isFromFileLine(isStaged, latestState, line):+ case isFromFileLine(latestState, line):latestState = FromFileLine// NoOp- case isToFileLine(isStaged, latestState, line):+ case isToFileLine(latestState, line):latestState = ToFileLine// TODO: Is this fix still required?currentDiff.PathB = strings.TrimRight(strings.TrimRight(string(line[6:]), "\n"), "\t") // Trim the newline and tab characters. https://github.com/trufflesecurity/trufflehog/issues/1060- case isHunkLineNumberLine(isStaged, latestState, line):+ case isHunkLineNumberLine(latestState, line):latestState = HunkLineNumberLineif currentDiff.Len() > 0 || currentDiff.IsBinary {@@ -555,9 +486,9 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan ch"latest_state", latestState.String(),)}- currentCommit.Diffs = append(currentCommit.Diffs, *currentDiff)+ diffChan <- currentDiff}- currentDiff = diff(withPathB(currentDiff.PathB))+ currentDiff = diff(currentCommit, withPathB(currentDiff.PathB))words := bytes.Split(line, []byte(" "))if len(words) >= 3 {@@ -567,7 +498,7 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan chcurrentDiff.LineStart = lineStart}}- case isHunkContextLine(isStaged, latestState, line):+ case isHunkContextLine(latestState, line):if latestState != HunkContentLine {latestState = HunkContentLine}@@ -575,7 +506,7 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan chif err := currentDiff.write(ctx, []byte("\n")); err != nil {ctx.Logger().Error(err, "failed to write to diff")}- case isHunkPlusLine(isStaged, latestState, line):+ case isHunkPlusLine(latestState, line):if latestState != HunkContentLine {latestState = HunkContentLine}@@ -584,14 +515,14 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan chctx.Logger().Error(err, "failed to write to diff")}// NoOp. We only care about additions.- case isHunkMinusLine(isStaged, latestState, line),- isHunkNewlineWarningLine(isStaged, latestState, line),- isHunkEmptyLine(isStaged, latestState, line):+ case isHunkMinusLine(latestState, line),+ isHunkNewlineWarningLine(latestState, line),+ isHunkEmptyLine(latestState, line):if latestState != HunkContentLine {latestState = HunkContentLine}// NoOp- case isCommitSeparatorLine(isStaged, latestState, line):+ case isCommitSeparatorLine(latestState, line):// NoOpdefault:// Skip ahead until we find the next diff or commit.@@ -620,7 +551,7 @@ func (c *Parser) FromReader(ctx context.Context, stdOut io.Reader, commitChan chbreak}}- cleanupParse(ctx, currentCommit, currentDiff, commitChan, &totalLogSize)+ cleanupParse(ctx, currentCommit, currentDiff, diffChan, &totalLogSize)ctx.Logger().V(2).Info("finished parsing git log.", "total_log_size", totalLogSize)}@@ -736,7 +667,7 @@ func isDiffLine(isStaged bool, latestState ParseState, line []byte) bool {// rename from old.txt// rename to new.txt// deleted file mode 100644-func isModeLine(isStaged bool, latestState ParseState, line []byte) bool {+func isModeLine(latestState ParseState, line []byte) bool {if !(latestState == DiffLine || latestState == ModeLine) {return false}@@ -755,7 +686,7 @@ func isModeLine(isStaged bool, latestState ParseState, line []byte) bool {// index 1ed6fbee1..aea1e643a 100644// index 00000000..e69de29b-func isIndexLine(isStaged bool, latestState ParseState, line []byte) bool {+func isIndexLine(latestState ParseState, line []byte) bool {if !(latestState == DiffLine || latestState == ModeLine) {return false}@@ -766,7 +697,7 @@ func isIndexLine(isStaged bool, latestState ParseState, line []byte) bool {}// Binary files /dev/null and b/plugin.sig differ-func isBinaryLine(isStaged bool, latestState ParseState, line []byte) bool {+func isBinaryLine(latestState ParseState, line []byte) bool {if latestState != IndexLine {return false}@@ -790,7 +721,7 @@ func pathFromBinaryLine(line []byte) string {// --- a/internal/addrs/move_endpoint_module.go// --- /dev/null-func isFromFileLine(isStaged bool, latestState ParseState, line []byte) bool {+func isFromFileLine(latestState ParseState, line []byte) bool {if !(latestState == IndexLine || latestState == ModeLine) {return false}@@ -801,7 +732,7 @@ func isFromFileLine(isStaged bool, latestState ParseState, line []byte) bool {}// +++ b/internal/addrs/move_endpoint_module.go-func isToFileLine(isStaged bool, latestState ParseState, line []byte) bool {+func isToFileLine(latestState ParseState, line []byte) bool {if latestState != FromFileLine {return false}@@ -812,7 +743,7 @@ func isToFileLine(isStaged bool, latestState ParseState, line []byte) bool {}// @@ -298 +298 @@ func maxRetryErrorHandler(resp *http.Response, err error, numTries int)-func isHunkLineNumberLine(isStaged bool, latestState ParseState, line []byte) bool {+func isHunkLineNumberLine(latestState ParseState, line []byte) bool {if !(latestState == ToFileLine || latestState == HunkContentLine) {return false}@@ -824,7 +755,7 @@ func isHunkLineNumberLine(isStaged bool, latestState ParseState, line []byte) bo// fmt.Println("ok")// (There's a space before `fmt` that gets removed by the formatter.)-func isHunkContextLine(isStaged bool, latestState ParseState, line []byte) bool {+func isHunkContextLine(latestState ParseState, line []byte) bool {if !(latestState == HunkLineNumberLine || latestState == HunkContentLine) {return false}@@ -835,7 +766,7 @@ func isHunkContextLine(isStaged bool, latestState ParseState, line []byte) bool}// +fmt.Println("ok")-func isHunkPlusLine(isStaged bool, latestState ParseState, line []byte) bool {+func isHunkPlusLine(latestState ParseState, line []byte) bool {if !(latestState == HunkLineNumberLine || latestState == HunkContentLine) {return false}@@ -846,7 +777,7 @@ func isHunkPlusLine(isStaged bool, latestState ParseState, line []byte) bool {}// -fmt.Println("ok")-func isHunkMinusLine(isStaged bool, latestState ParseState, line []byte) bool {+func isHunkMinusLine(latestState ParseState, line []byte) bool {if !(latestState == HunkLineNumberLine || latestState == HunkContentLine) {return false}@@ -857,7 +788,7 @@ func isHunkMinusLine(isStaged bool, latestState ParseState, line []byte) bool {}// \ No newline at end of file-func isHunkNewlineWarningLine(isStaged bool, latestState ParseState, line []byte) bool {+func isHunkNewlineWarningLine(latestState ParseState, line []byte) bool {if latestState != HunkContentLine {return false}@@ -871,7 +802,7 @@ func isHunkNewlineWarningLine(isStaged bool, latestState ParseState, line []byte// +}//// commit 00920984e3435057f09cee5468850f7546dfa637 (tag: v3.42.0)-func isHunkEmptyLine(isStaged bool, latestState ParseState, line []byte) bool {+func isHunkEmptyLine(latestState ParseState, line []byte) bool {if !(latestState == HunkLineNumberLine || latestState == HunkContentLine) {return false}@@ -882,7 +813,7 @@ func isHunkEmptyLine(isStaged bool, latestState ParseState, line []byte) bool {return false}-func isCommitSeparatorLine(isStaged bool, latestState ParseState, line []byte) bool {+func isCommitSeparatorLine(latestState ParseState, line []byte) bool {if (latestState == ModeLine || latestState == IndexLine || latestState == BinaryFileLine || latestState == ToFileLine) &&len(line) == 1 && bytes.Equal(line[:1], []byte("\n")) {return true@@ -890,17 +821,18 @@ func isCommitSeparatorLine(isStaged bool, latestState ParseState, line []byte) breturn false}-func cleanupParse(ctx context.Context, currentCommit *Commit, currentDiff *Diff, commitChan chan Commit, totalLogSize *int) {+func cleanupParse(ctx context.Context, currentCommit *Commit, currentDiff *Diff, diffChan chan *Diff, totalLogSize *int) {if err := currentDiff.finalize(); err != nil {ctx.Logger().Error(err, "failed to finalize diff")return}+// Ignore empty or binary diffs (this condition may be redundant).if currentDiff != nil && (currentDiff.Len() > 0 || currentDiff.IsBinary) {- currentCommit.Diffs = append(currentCommit.Diffs, *currentDiff)+ currentDiff.Commit = currentCommit+ diffChan <- currentDiff}if currentCommit != nil {- commitChan <- *currentCommitif totalLogSize != nil {*totalLogSize += currentCommit.Size}diff --git a/pkg/gitparse/gitparse_test.go b/pkg/gitparse/gitparse_test.goindex e5e8ad40a..505d6db9d 100644--- a/pkg/gitparse/gitparse_test.go+++ b/pkg/gitparse/gitparse_test.go@@ -17,13 +17,13 @@ type testCaseLine struct {line []byte}-type testCase struct {- passes []testCaseLine- fails []testCaseLine- function func(bool, ParseState, []byte) bool-}+func TestLineChecksWithStaged(t *testing.T) {+ type testCase struct {+ passes []testCaseLine+ fails []testCaseLine+ function func(bool, ParseState, []byte) bool+ }-func TestLineChecks(t *testing.T) {tests := map[string]testCase{"commitLine": {passes: []testCaseLine{@@ -223,6 +223,30 @@ func TestLineChecks(t *testing.T) {},function: isDiffLine,},+ }++ for name, test := range tests {+ for _, pass := range test.passes {+ if !test.function(false, pass.latestState, pass.line) {+ t.Errorf("%s: Parser did not recognize correct line. (%s)", name, string(pass.line))+ }+ }+ for _, fail := range test.fails {+ if test.function(false, fail.latestState, fail.line) {+ t.Errorf("%s: Parser did not recognize incorrect line. (%s)", name, string(fail.line))+ }+ }+ }+}++func TestLineChecksNoStaged(t *testing.T) {+ type testCase struct {+ passes []testCaseLine+ fails []testCaseLine+ function func(ParseState, []byte) bool+ }++ tests := map[string]testCase{"modeLine": {passes: []testCaseLine{{@@ -553,118 +577,18 @@ func TestLineChecks(t *testing.T) {for name, test := range tests {for _, pass := range test.passes {- if !test.function(false, pass.latestState, pass.line) {+ if !test.function(pass.latestState, pass.line) {t.Errorf("%s: Parser did not recognize correct line. (%s)", name, string(pass.line))}}for _, fail := range test.fails {- if test.function(false, fail.latestState, fail.line) {+ if test.function(fail.latestState, fail.line) {t.Errorf("%s: Parser did not recognize incorrect line. (%s)", name, string(fail.line))}}}}-type messageParsingTestCase struct {- data string- expected string-}--func TestMessageParsing(t *testing.T) {- tests := []messageParsingTestCase{- {- data: `commit 70001020fab32b1fcf2f1f0e5c66424eae649826 (HEAD -> master, origin/master, origin/HEAD)-Author: Dustin Decker <[email protected]>-Date: Mon Mar 15 23:27:16 2021 -0700-- Update aws--diff --git a/aws b/aws-index 2ee133b..12b4843 100644---- a/aws-+++ b/aws-@@ -1,7 +1,5 @@-+[default]- aws_access_key_id = AKIAXYZDQCEN4B6JSJQI-+aws_secret_access_key = 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-`,- expected: "Update aws\n",- },- {- data: `commit 74ffbd28787b3bb4e6953ce1c3ee6899af650bce-Author: Zachary Rice <[email protected]>-Date: Tue Jun 13 14:49:21 2023 -0500-- add a custom detector check for logging duplicate detector (#1394)-- * add a custom detector check for logging duplicate detector-- * use pb type--diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go-index 090c6ba6..38d67dd2 100644---- a/pkg/engine/engine.go-+++ b/pkg/engine/engine.go-@@ -165,7 +165,7 @@ func Start(ctx context.Context, options ...EngineOption) *Engine {- seenDetectors := make(map[config.DetectorID]struct{}, len(dets))- for _, det := range dets {- id := config.GetDetectorID(det)-- if _, ok := seenDetectors[id]; ok {-+ if _, ok := seenDetectors[id]; ok && id.ID != detectorspb.DetectorType_CustomRegex {- ctx.Logger().Info("possible duplicate detector configured", "detector", id)- }- seenDetectors[id] = struct{}{}`,- expected: `add a custom detector check for logging duplicate detector (#1394)--* add a custom detector check for logging duplicate detector--* use pb type-`,- },- {- data: `commit a8bc99bfe2c7178d1d2de9aa2f8ea6752bcf02c8-Author: Michelle Purcell <[email protected]>-Date: Tue Jun 27 13:48:04 2023 +0100-- Update docs/src/main/asciidoc/security-vulnerability-detection.adoc-- Co-authored-by: Sergey Beryozkin <[email protected]>- (cherry picked from commit 10f04b79e0ab3a331ac1bfae78d7ed399e243bf0)--diff --git a/docs/src/main/asciidoc/security-vulnerability-detection.adoc b/docs/src/main/asciidoc/security-vulnerability-detection.adoc-index 6e90300f9f6..e3cc8d1485f 100644---- a/docs/src/main/asciidoc/security-vulnerability-detection.adoc-+++ b/docs/src/main/asciidoc/security-vulnerability-detection.adoc-@@ -139 +139 @@ You can adjust the expiry date if you need to.--* xref:security-authentication-mechanisms.adoc#other-supported-authentication-mechanisms[Other supported authentication mechanisms]-\ No newline at end of file-+* xref:security-authentication-mechanisms.adoc[Authentication mechanisms in Quarkus]-\ No newline at end of file-`,- expected: `Update docs/src/main/asciidoc/security-vulnerability-detection.adoc--Co-authored-by: Sergey Beryozkin <[email protected]>-(cherry picked from commit 10f04b79e0ab3a331ac1bfae78d7ed399e243bf0)-`,- },- }-- for _, test := range tests {- r := bytes.NewReader([]byte(test.data))- commitChan := make(chan Commit)- parser := NewParser()-- go func() {- parser.FromReader(context.Background(), r, commitChan, false)- }()- for commit := range commitChan {- if commit.Message.String() != test.expected {- t.Errorf("Message does not match. Got:\n%s\nexpected:\n%s", commit.Message.String(), test.expected)- }- }- }-}-func TestBinaryPathParse(t *testing.T) {cases := map[string]string{"Binary files /dev/null and b/plugin.sig differ\n": "plugin.sig",@@ -679,35 +603,56 @@ func TestBinaryPathParse(t *testing.T) {}}-func newTime(timestamp string) time.Time {- date, _ := time.Parse(defaultDateFormat, timestamp)- return date-}+// Equal compares the content of two Commits to determine if they are the same.+func (d1 *Diff) Equal(ctx context.Context, d2 *Diff) bool {+ // isEqualString handles the error-prone String() method calls and compares the results.+ isEqualContentString := func(s1, s2 contentWriter) (bool, error) {+ str1, err := s1.String()+ if err != nil {+ return false, err+ }+ str2, err := s2.String()+ if err != nil {+ return false, err+ }+ return str1 == str2, nil+ }-func newStringBuilderValue(value string) strings.Builder {- builder := strings.Builder{}- builder.Write([]byte(value))- return builder+ switch {+ case d1.PathB != d2.PathB:+ return false+ case d1.LineStart != d2.LineStart:+ return false+ case d1.IsBinary != d2.IsBinary:+ return false+ default:+ equal, err := isEqualContentString(d1.contentWriter, d2.contentWriter)+ if err != nil || !equal {+ ctx.Logger().Error(err, "failed to compare diff content")+ return false+ }+ }+ return true}func TestCommitParsing(t *testing.T) {- expected := expectedCommits()+ expected := expectedDiffs()- r := bytes.NewReader([]byte(commitLog))- commitChan := make(chan Commit)+ r := bytes.NewReader([]byte(diffLog))+ diffChan := make(chan *Diff)parser := NewParser()go func() {- parser.FromReader(context.Background(), r, commitChan, false)+ parser.FromReader(context.Background(), r, diffChan, false)}()i := 0- for commit := range commitChan {+ for diff := range diffChan {if len(expected) <= i {- t.Errorf("Missing expected case for commit: %+v", commit)+ t.Errorf("Missing expected case for commit: %+v", diff)break}- if !commit.Equal(context.Background(), &expected[i]) {- t.Errorf("Commit does not match.\nexpected: %+v\n%s\nactual : %+v\n%s", expected[i], expected[i].Message.String(), commit, commit.Message.String())+ if !diff.Equal(context.Background(), expected[i]) {+ t.Errorf("Diff does not match.\nexpected: %+v\n%s\nactual : %+v\n%s", expected[i], expected[i].Commit.Message.String(), diff, diff.Commit.Message.String())}i++}@@ -715,8 +660,8 @@ func TestCommitParsing(t *testing.T) {func TestIndividualCommitParsing(t *testing.T) {// Arrange- expected := expectedCommits()- commits := strings.Split(commitLog, "\ncommit ")+ expected := expectedDiffs()+ commits := strings.Split(diffLog, "\ndiff --git")for index, commit := range commits {if !strings.HasPrefix(commit, "commit") {commits[index] = "commit " + commit@@ -726,21 +671,21 @@ func TestIndividualCommitParsing(t *testing.T) {// Actfor i, commit := range commits {r := bytes.NewReader([]byte(commit))- commitChan := make(chan Commit)+ diffChan := make(chan *Diff)parser := NewParser()go func() {- parser.FromReader(context.Background(), r, commitChan, false)+ parser.FromReader(context.Background(), r, diffChan, false)}()j := 0- for commit := range commitChan {+ for diff := range diffChan {if len(expected) <= i {- t.Errorf("Missing expected case for commit: %+v", commit)+ t.Errorf("Missing expected case for commit: %+v", diff)break}// Assert- if !commit.Equal(context.Background(), &expected[i]) {- t.Errorf("Commit does not match.\nexpected: %+v\n%s\nactual : %+v\n%s", expected[i], expected[j].Message.String(), commit, commit.Message.String())+ if !diff.Equal(context.Background(), expected[i]) {+ t.Errorf("Diff does not match.\nexpected: %+v\n%s\nactual : %+v\n%s", expected[i], expected[j].Commit.Message.String(), diff, diff.Commit.Message.String())}j++}@@ -763,264 +708,202 @@ func newBufferWithContent(content []byte) *buffer {}func TestStagedDiffParsing(t *testing.T) {- expected := []Commit{+ expected := []*Diff{{- Hash: "",- Author: "",- Date: newTime("0001-01-01 00:00:00 +0000 UTC"),- Message: strings.Builder{},- Diffs: []Diff{- {- PathB: "aws",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("[default]\naws_access_key_id = AKIAXYZDQCEN4B6JSJQI\naws_secret_access_key = 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\noutput = json\nregion = us-east-2\n")),- IsBinary: false,- },- {- PathB: "aws2",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("\n\nthis is the secret: [Default]\nAccess key Id: AKIAILE3JG6KMS3HZGCA\nSecret Access Key: 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\n\nokay thank you bye\n")),- IsBinary: false,- },- {- PathB: "core/runtime/src/main/java/io/quarkus/runtime/QuarkusApplication.java",- LineStart: 3,- contentWriter: newBufferWithContent([]byte("/**\n * This is usually used for command mode applications with a startup logic. The logic is executed inside\n * {@link QuarkusApplication#run} method before the main application exits.\n */\n")),- IsBinary: false,- },- {- PathB: "trufflehog_3.42.0_linux_arm64.tar.gz",- IsBinary: true,- contentWriter: newBufferWithContent(nil),- },- {- PathB: "tzu",- LineStart: 11,- contentWriter: newBufferWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),- IsBinary: false,- },- {- PathB: "lao",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("The Way that can be told of is not the eternal Way;\nThe name that can be named is not the eternal name.\nThe Nameless is the origin of Heaven and Earth;\nThe Named is the mother of all things.\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\n")),- IsBinary: false,- },- {- PathB: "tzu",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),- IsBinary: false,- },- },+ PathB: "aws",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("[default]\naws_access_key_id = AKIAXYZDQCEN4B6JSJQI\naws_secret_access_key = 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\noutput = json\nregion = us-east-2\n")),+ IsBinary: false,+ },+ {+ PathB: "aws2",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("\n\nthis is the secret: [Default]\nAccess key Id: AKIAILE3JG6KMS3HZGCA\nSecret Access Key: 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\n\nokay thank you bye\n")),+ IsBinary: false,+ },+ {+ PathB: "core/runtime/src/main/java/io/quarkus/runtime/QuarkusApplication.java",+ LineStart: 3,+ contentWriter: newBufferWithContent([]byte("/**\n * This is usually used for command mode applications with a startup logic. The logic is executed inside\n * {@link QuarkusApplication#run} method before the main application exits.\n */\n")),+ IsBinary: false,+ },+ {+ PathB: "trufflehog_3.42.0_linux_arm64.tar.gz",+ IsBinary: true,+ contentWriter: newBufferWithContent(nil),+ },+ {+ PathB: "tzu",+ LineStart: 11,+ contentWriter: newBufferWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),+ IsBinary: false,+ },+ {+ PathB: "lao",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("The Way that can be told of is not the eternal Way;\nThe name that can be named is not the eternal name.\nThe Nameless is the origin of Heaven and Earth;\nThe Named is the mother of all things.\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\n")),+ IsBinary: false,+ },+ {+ PathB: "tzu",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),+ IsBinary: false,},}r := bytes.NewReader([]byte(stagedDiffs))- commitChan := make(chan Commit)+ diffChan := make(chan *Diff)parser := NewParser()go func() {- parser.FromReader(context.Background(), r, commitChan, true)+ parser.FromReader(context.Background(), r, diffChan, true)}()i := 0- for commit := range commitChan {+ for diff := range diffChan {if len(expected) <= i {- t.Errorf("Missing expected case for commit: %+v", commit)+ t.Errorf("Missing expected case for commit: %+v", diff)break}- if !commit.Equal(context.Background(), &expected[i]) {- t.Errorf("Commit does not match.\nexpected:\n%+v\n\nactual:\n%+v\n", expected[i], commit)+ if !diff.Equal(context.Background(), expected[i]) {+ t.Errorf("Diff does not match.\nexpected:\n%+v\n\nactual:\n%+v\n", expected[i], diff)}i++}}func TestStagedDiffParsingBufferedFileWriter(t *testing.T) {- expected := []Commit{+ expected := []*Diff{{- Hash: "",- Author: "",- Date: newTime("0001-01-01 00:00:00 +0000 UTC"),- Message: strings.Builder{},- Diffs: []Diff{- {- PathB: "aws",- LineStart: 1,- contentWriter: newBufferedFileWriterWithContent([]byte("[default]\naws_access_key_id = AKIAXYZDQCEN4B6JSJQI\naws_secret_access_key = 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\noutput = json\nregion = us-east-2\n")),- IsBinary: false,- },- {- PathB: "aws2",- LineStart: 1,- contentWriter: newBufferedFileWriterWithContent([]byte("\n\nthis is the secret: [Default]\nAccess key Id: AKIAILE3JG6KMS3HZGCA\nSecret Access Key: 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\n\nokay thank you bye\n")),- IsBinary: false,- },- {- PathB: "core/runtime/src/main/java/io/quarkus/runtime/QuarkusApplication.java",- LineStart: 3,- contentWriter: newBufferedFileWriterWithContent([]byte("/**\n * This is usually used for command mode applications with a startup logic. The logic is executed inside\n * {@link QuarkusApplication#run} method before the main application exits.\n */\n")),- IsBinary: false,- },- {- PathB: "trufflehog_3.42.0_linux_arm64.tar.gz",- IsBinary: true,- contentWriter: newBufferedFileWriterWithContent(nil),- },- {- PathB: "tzu",- LineStart: 11,- contentWriter: newBufferedFileWriterWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),- IsBinary: false,- },- {- PathB: "lao",- LineStart: 1,- contentWriter: newBufferedFileWriterWithContent([]byte("The Way that can be told of is not the eternal Way;\nThe name that can be named is not the eternal name.\nThe Nameless is the origin of Heaven and Earth;\nThe Named is the mother of all things.\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\n")),- IsBinary: false,- },- {- PathB: "tzu",- LineStart: 1,- contentWriter: newBufferedFileWriterWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),- IsBinary: false,- },- },+ PathB: "aws",+ LineStart: 1,+ contentWriter: newBufferedFileWriterWithContent([]byte("[default]\naws_access_key_id = AKIAXYZDQCEN4B6JSJQI\naws_secret_access_key = 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\noutput = json\nregion = us-east-2\n")),+ IsBinary: false,+ },+ {+ PathB: "aws2",+ LineStart: 1,+ contentWriter: newBufferedFileWriterWithContent([]byte("\n\nthis is the secret: [Default]\nAccess key Id: AKIAILE3JG6KMS3HZGCA\nSecret Access Key: 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\n\nokay thank you bye\n")),+ IsBinary: false,+ },+ {+ PathB: "core/runtime/src/main/java/io/quarkus/runtime/QuarkusApplication.java",+ LineStart: 3,+ contentWriter: newBufferedFileWriterWithContent([]byte("/**\n * This is usually used for command mode applications with a startup logic. The logic is executed inside\n * {@link QuarkusApplication#run} method before the main application exits.\n */\n")),+ IsBinary: false,+ },+ {+ PathB: "trufflehog_3.42.0_linux_arm64.tar.gz",+ IsBinary: true,+ contentWriter: newBufferedFileWriterWithContent(nil),+ },+ {+ PathB: "tzu",+ LineStart: 11,+ contentWriter: newBufferedFileWriterWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),+ IsBinary: false,+ },+ {+ PathB: "lao",+ LineStart: 1,+ contentWriter: newBufferedFileWriterWithContent([]byte("The Way that can be told of is not the eternal Way;\nThe name that can be named is not the eternal name.\nThe Nameless is the origin of Heaven and Earth;\nThe Named is the mother of all things.\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\n")),+ IsBinary: false,+ },+ {+ PathB: "tzu",+ LineStart: 1,+ contentWriter: newBufferedFileWriterWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),+ IsBinary: false,},}r := bytes.NewReader([]byte(stagedDiffs))- commitChan := make(chan Commit)+ diffChan := make(chan *Diff)parser := NewParser()go func() {- parser.FromReader(context.Background(), r, commitChan, true)+ parser.FromReader(context.Background(), r, diffChan, true)}()i := 0- for commit := range commitChan {+ for diff := range diffChan {if len(expected) <= i {- t.Errorf("Missing expected case for commit: %+v", commit)+ t.Errorf("Missing expected case for commit: %+v", diff)break}- if !commit.Equal(context.Background(), &expected[i]) {- t.Errorf("Commit does not match.\nexpected:\n%+v\n\nactual:\n%+v\n", expected[i], commit)+ if !diff.Equal(context.Background(), expected[i]) {+ t.Errorf("Diff does not match.\nexpected:\n%+v\n\nactual:\n%+v\n", expected[i], diff)}i++}}func TestCommitParseFailureRecovery(t *testing.T) {- expected := []Commit{- {- Hash: "df393b4125c2aa217211b2429b8963d0cefcee27",- Author: "Stephen <[email protected]>",- Date: newTime("Wed Dec 06 14:44:41 2017 -0800"),- Message: newStringBuilderValue("Add travis testing\n"),- Diffs: []Diff{- {- PathB: ".travis.yml",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("language: python\npython:\n - \"2.6\"\n - \"2.7\"\n - \"3.2\"\n - \"3.3\"\n - \"3.4\"\n - \"3.5\"\n - \"3.5-dev\" # 3.5 development branch\n - \"3.6\"\n - \"3.6-dev\" # 3.6 development branch\n - \"3.7-dev\" # 3.7 development branch\n - \"nightly\"\n")),- IsBinary: false,- },- },- },+ expected := []*Diff{{- Hash: "3d76a97faad96e0f326afb61c232b9c2a18dca35",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 18:03:54 2023 -0400"),- Message: strings.Builder{},- Diffs: []Diff{},+ PathB: ".travis.yml",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("language: python\npython:\n - \"2.6\"\n - \"2.7\"\n - \"3.2\"\n - \"3.3\"\n - \"3.4\"\n - \"3.5\"\n - \"3.5-dev\" # 3.5 development branch\n - \"3.6\"\n - \"3.6-dev\" # 3.6 development branch\n - \"3.7-dev\" # 3.7 development branch\n - \"nightly\"\n")),+ IsBinary: false,},{- Hash: "7bd16429f1f708746dabf970e54b05d2b4734997",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 18:10:49 2023 -0400"),- Message: newStringBuilderValue("Change file\n"),- Diffs: []Diff{- {- PathB: "tzu",- LineStart: 11,- contentWriter: newBufferWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),- IsBinary: false,- },- },+ PathB: "tzu",+ LineStart: 11,+ contentWriter: newBufferWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),+ IsBinary: false,},}r := bytes.NewReader([]byte(recoverableCommits))- commitChan := make(chan Commit)+ diffChan := make(chan *Diff)parser := NewParser()go func() {- parser.FromReader(context.Background(), r, commitChan, false)+ parser.FromReader(context.Background(), r, diffChan, false)}()i := 0- for commit := range commitChan {+ for diff := range diffChan {if len(expected) <= i {- t.Errorf("Missing expected case for commit: %+v", commit)+ t.Errorf("Missing expected case for commit: %+v", diff)break}- if !commit.Equal(context.Background(), &expected[i]) {- t.Errorf("Commit does not match.\nexpected: %+v\n\nactual : %+v\n", expected[i], commit)+ if !diff.Equal(context.Background(), expected[i]) {+ t.Errorf("Diff does not match.\nexpected: %+v\n\nactual : %+v\n", expected[i], diff)}i++}}func TestCommitParseFailureRecoveryBufferedFileWriter(t *testing.T) {- expected := []Commit{+ expected := []*Diff{{- Hash: "df393b4125c2aa217211b2429b8963d0cefcee27",- Author: "Stephen <[email protected]>",- Date: newTime("Wed Dec 06 14:44:41 2017 -0800"),- Message: newStringBuilderValue("Add travis testing\n"),- Diffs: []Diff{- {- PathB: ".travis.yml",- LineStart: 1,- contentWriter: newBufferedFileWriterWithContent([]byte("language: python\npython:\n - \"2.6\"\n - \"2.7\"\n - \"3.2\"\n - \"3.3\"\n - \"3.4\"\n - \"3.5\"\n - \"3.5-dev\" # 3.5 development branch\n - \"3.6\"\n - \"3.6-dev\" # 3.6 development branch\n - \"3.7-dev\" # 3.7 development branch\n - \"nightly\"\n")),- IsBinary: false,- },- },+ PathB: ".travis.yml",+ LineStart: 1,+ contentWriter: newBufferedFileWriterWithContent([]byte("language: python\npython:\n - \"2.6\"\n - \"2.7\"\n - \"3.2\"\n - \"3.3\"\n - \"3.4\"\n - \"3.5\"\n - \"3.5-dev\" # 3.5 development branch\n - \"3.6\"\n - \"3.6-dev\" # 3.6 development branch\n - \"3.7-dev\" # 3.7 development branch\n - \"nightly\"\n")),+ IsBinary: false,},{- Hash: "3d76a97faad96e0f326afb61c232b9c2a18dca35",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 18:03:54 2023 -0400"),- Message: strings.Builder{},- Diffs: []Diff{},- },- {- Hash: "7bd16429f1f708746dabf970e54b05d2b4734997",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 18:10:49 2023 -0400"),- Message: newStringBuilderValue("Change file\n"),- Diffs: []Diff{- {- PathB: "tzu",- LineStart: 11,- contentWriter: newBufferedFileWriterWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),- IsBinary: false,- },- },+ PathB: "tzu",+ LineStart: 11,+ contentWriter: newBufferedFileWriterWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),+ IsBinary: false,},}r := bytes.NewReader([]byte(recoverableCommits))- commitChan := make(chan Commit)+ diffChan := make(chan *Diff)parser := NewParser()go func() {- parser.FromReader(context.Background(), r, commitChan, false)+ parser.FromReader(context.Background(), r, diffChan, false)}()i := 0- for commit := range commitChan {+ for diff := range diffChan {if len(expected) <= i {- t.Errorf("Missing expected case for commit: %+v", commit)+ t.Errorf("Missing expected case for commit: %+v", diff)break}- if !commit.Equal(context.Background(), &expected[i]) {- t.Errorf("Commit does not match.\nexpected: %+v\n\nactual : %+v\n", expected[i], commit)+ if !diff.Equal(context.Background(), expected[i]) {+ t.Errorf("Diff does not match.\nexpected: %+v\n\nactual : %+v\n", expected[i], diff)}i++}@@ -1097,100 +980,84 @@ index 5af88a8..c729cdb 100644`func TestDiffParseFailureRecovery(t *testing.T) {- expected := []Commit{+ expected := []*Diff{{- Hash: "",- Author: "",- Date: newTime("0001-01-01 00:00:00 +0000 UTC"),- Message: strings.Builder{},- Diffs: []Diff{- {- PathB: "aws",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("[default]\naws_access_key_id = AKIAXYZDQCEN4B6JSJQI\naws_secret_access_key = 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\noutput = json\nregion = us-east-2\n")),- IsBinary: false,- },- {- PathB: "tzu",- LineStart: 11,- contentWriter: newBufferWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),- IsBinary: false,- },- {- PathB: "tzu",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),- IsBinary: false,- },- },+ PathB: "aws",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("[default]\naws_access_key_id = AKIAXYZDQCEN4B6JSJQI\naws_secret_access_key = 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\noutput = json\nregion = us-east-2\n")),+ IsBinary: false,+ },+ {+ PathB: "tzu",+ LineStart: 11,+ contentWriter: newBufferWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),+ IsBinary: false,+ },+ {+ PathB: "tzu",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),+ IsBinary: false,},}r := bytes.NewReader([]byte(recoverableDiffs))- commitChan := make(chan Commit)+ diffChan := make(chan *Diff)parser := NewParser()go func() {- parser.FromReader(context.Background(), r, commitChan, true)+ parser.FromReader(context.Background(), r, diffChan, true)}()i := 0- for commit := range commitChan {+ for diff := range diffChan {if len(expected) <= i {- t.Errorf("Missing expected case for commit: %+v", commit)+ t.Errorf("Missing expected case for commit: %+v", diff)break}- if !commit.Equal(context.Background(), &expected[i]) {- t.Errorf("Commit does not match.\nexpected: %+v\n\nactual : %+v\n", expected[i], commit)+ if !diff.Equal(context.Background(), expected[i]) {+ t.Errorf("Diff does not match.\nexpected: %+v\n\nactual : %+v\n", expected[i], diff)}i++}}func TestDiffParseFailureRecoveryBufferedFileWriter(t *testing.T) {- expected := []Commit{+ expected := []*Diff{{- Hash: "",- Author: "",- Date: newTime("0001-01-01 00:00:00 +0000 UTC"),- Message: strings.Builder{},- Diffs: []Diff{- {- PathB: "aws",- LineStart: 1,- contentWriter: newBufferedFileWriterWithContent([]byte("[default]\naws_access_key_id = AKIAXYZDQCEN4B6JSJQI\naws_secret_access_key = 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\noutput = json\nregion = us-east-2\n")),- IsBinary: false,- },- {- PathB: "tzu",- LineStart: 11,- contentWriter: newBufferedFileWriterWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),- IsBinary: false,- },- {- PathB: "tzu",- LineStart: 1,- contentWriter: newBufferedFileWriterWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),- IsBinary: false,- },- },+ PathB: "aws",+ LineStart: 1,+ contentWriter: newBufferedFileWriterWithContent([]byte("[default]\naws_access_key_id = AKIAXYZDQCEN4B6JSJQI\naws_secret_access_key = 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\noutput = json\nregion = us-east-2\n")),+ IsBinary: false,+ },+ {+ PathB: "tzu",+ LineStart: 11,+ contentWriter: newBufferedFileWriterWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),+ IsBinary: false,+ },+ {+ PathB: "tzu",+ LineStart: 1,+ contentWriter: newBufferedFileWriterWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),+ IsBinary: false,},}r := bytes.NewReader([]byte(recoverableDiffs))- commitChan := make(chan Commit)+ diffChan := make(chan *Diff)parser := NewParser()go func() {- parser.FromReader(context.Background(), r, commitChan, true)+ parser.FromReader(context.Background(), r, diffChan, true)}()i := 0- for commit := range commitChan {+ for diff := range diffChan {if len(expected) <= i {- t.Errorf("Missing expected case for commit: %+v", commit)+ t.Errorf("Missing expected case for commit: %+v", diff)break}- if !commit.Equal(context.Background(), &expected[i]) {- t.Errorf("Commit does not match.\nexpected: %+v\n\nactual : %+v\n", expected[i], commit)+ if !diff.Equal(context.Background(), expected[i]) {+ t.Errorf("Diff does not match.\nexpected: %+v\n\nactual : %+v\n", expected[i], diff)}i++}@@ -1294,18 +1161,18 @@ func TestMaxDiffSize(t *testing.T) {}bigReader := strings.NewReader(builder.String())- commitChan := make(chan Commit, 1) // Buffer to prevent blocking+ diffChan := make(chan *Diff, 1) // Buffer to prevent blockingctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) // Timeout to prevent long waitdefer cancel()go func() {- parser.FromReader(ctx, bigReader, commitChan, false)+ parser.FromReader(ctx, bigReader, diffChan, false)}()select {- case commit := <-commitChan:- if commit.Diffs[0].Len() > parser.maxDiffSize+1024 {- t.Errorf("diff did not match MaxDiffSize. Got: %d, expected (max): %d", commit.Diffs[0].Len(), parser.maxDiffSize+1024)+ case diff := <-diffChan:+ if diff.Len() > parser.maxDiffSize+1024 {+ t.Errorf("diff did not match MaxDiffSize. Got: %d, expected (max): %d", diff.Len(), parser.maxDiffSize+1024)}case <-ctx.Done():t.Fatal("Test timed out")@@ -1316,28 +1183,23 @@ func TestMaxCommitSize(t *testing.T) {parser := NewParser(WithMaxCommitSize(1))commitText := bytes.Buffer{}commitText.WriteString(singleCommitMultiDiff)- commitChan := make(chan Commit)+ diffChan := make(chan *Diff)ctx, cancel := context.WithTimeout(context.Background(), time.Duration(1)*time.Second)defer cancel()go func() {- parser.FromReader(ctx, &commitText, commitChan, false)+ parser.FromReader(ctx, &commitText, diffChan, false)}()- commitCount := 0- for range commitChan {- commitCount+++ diffCount := 0+ for range diffChan {+ diffCount++}- if commitCount != 2 {- t.Errorf("Commit count does not match. Got: %d, expected: %d", commitCount, 2)+ if diffCount != 2 {+ t.Errorf("Commit count does not match. Got: %d, expected: %d", diffCount, 2)}}-const commitLog = `commit fd6e99e7a80199b76a694603be57c5ade1de18e7-Author: Jaliborc <[email protected]>-Date: Mon Apr 25 16:28:06 2011 +0100-- Added Unusable coloring-+const diffLog = `diff --git a/components/item.lua b/components/item.luaindex fc74534..f8d7d50 100755--- a/components/item.lua@@ -1370,20 +1232,6 @@ new file mode 160000@@ -0,0 +1 @@+Subproject commit 0000000000000000000000000000000000000000-commit 4727ffb7ad6dc5130bf4b4dd166e00705abdd018 (HEAD -> master)-Author: John Smith <[email protected]>-Date: Tue Jul 11 22:26:11 2023 -0400--commit c904e0f5cd9f30ae520c66bd5f70806219fe7ca2 (HEAD -> master)-Author: John Smith <[email protected]>-Date: Mon Jul 10 10:17:11 2023 -0400-- Empty Commit--commit 3d76a97faad96e0f326afb61c232b9c2a18dca35 (HEAD -> master)-Author: John Smith <[email protected]>-Date: Tue Jul 11 18:03:54 2023 -0400-diff --git a/sample.txt b/sample.txtnew file mode 100644index 0000000..af5626b@@ -1392,12 +1240,6 @@ index 0000000..af5626b@@ -0,0 +1 @@+Hello, world!-commit df393b4125c2aa217211b2429b8963d0cefcee27-Author: Stephen <[email protected]>-Date: Wed Dec 06 14:44:41 2017 -0800-- Add travis testing-diff --git a/.gitignore b/.gitignoreindex ede6aa39..bb85dcc3 100644--- a/.gitignore@@ -1432,12 +1274,6 @@ diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 00000000..e69de29b-commit 4218c39d99b5f30153f62471c1be1c1596f0a4d4-Author: Dustin Decker <[email protected]>-Date: Thu Jan 13 12:02:24 2022 -0800-- Initial CLI w/ partially implemented Git source and demo detector (#1)-diff --git a/Dockerfile b/Dockerfilenew file mode 100644index 00000000..e69de29b@@ -1504,12 +1340,6 @@ index 0000000..451be67+++ test+-commit 2a5d703b02b52d65c65ee9f7928f158b919ab741-Author: Sergey Beryozkin <[email protected]>-Date: Fri Jul 7 17:44:26 2023 +0100-- Do not refresh OIDC session if the user is requesting logout-diff --git a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/BackChannelLogoutTokenCache.java b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/BackChannelLogoutTokenCache.javaindex 096f5b4b092..4150096851c 100644--- a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/BackChannelLogoutTokenCache.java@@ -1612,14 +1442,6 @@ index 51e1b9a932d..472c2743bc4 100644assertEquals("Welcome, clientId: quarkus-web-app", page.getBody().asNormalizedText());assertNull(getSessionCookie(webClient, "code-flow"));-commit 2a057632d7f5fa3d1c77b9aa037263211c0e0290-Author: rjtmahinay <[email protected]>-Date: Mon Jul 10 01:22:32 2023 +0800-- Add QuarkusApplication javadoc-- * Fix #34463-diff --git a/core/runtime/src/main/java/io/quarkus/runtime/QuarkusApplication.java b/core/runtime/src/main/java/io/quarkus/runtime/QuarkusApplication.javaindex 350685123d5..87d2220eb98 100644--- a/core/runtime/src/main/java/io/quarkus/runtime/QuarkusApplication.java@@ -1630,44 +1452,20 @@ index 350685123d5..87d2220eb98 100644+ * {@link QuarkusApplication#run} method before the main application exits.+ */-commit bca2d17491015ea1522f34517223b5a366aea73c (HEAD -> master)-Author: John Smith <[email protected]>-Date: Tue Jul 11 18:12:21 2023 -0400-- Delete binary file-diff --git a/trufflehog_3.42.0_linux_arm64.tar.gz b/trufflehog_3.42.0_linux_arm64.tar.gzdeleted file mode 100644index 7682212..0000000Binary files a/trufflehog_3.42.0_linux_arm64.tar.gz and /dev/null differ-commit afc6dc5d47f28366638da877ecb6b819c69e659b-Author: John Smith <[email protected]>-Date: Mon Jul 10 12:21:33 2023 -0400-- Change binary file-diff --git a/trufflehog_3.42.0_linux_arm64.tar.gz b/trufflehog_3.42.0_linux_arm64.tar.gzindex 0a7a5b4..7682212 100644Binary files a/trufflehog_3.42.0_linux_arm64.tar.gz and b/trufflehog_3.42.0_linux_arm64.tar.gz differ-commit 638595917417c5c8a956937b28c5127719023363-Author: John Smith <[email protected]>-Date: Mon Jul 10 12:20:35 2023 -0400-- Add binary file-diff --git a/trufflehog_3.42.0_linux_arm64.tar.gz b/trufflehog_3.42.0_linux_arm64.tar.gznew file mode 100644index 0000000..0a7a5b4Binary files /dev/null and b/trufflehog_3.42.0_linux_arm64.tar.gz differ-commit ce0f5d1fe0272f180ccb660196f439c0c2f4ec8e (HEAD -> master)-Author: John Smith <[email protected]>-Date: Tue Jul 11 18:08:52 2023 -0400-- Delete file-diff --git a/lao b/laodeleted file mode 100644index 635ef2c..0000000@@ -1686,23 +1484,11 @@ index 635ef2c..0000000-But after they are produced,- they have different names.-commit d606a729383371558473b70a6a7b1ca264b0d205-Author: John Smith <[email protected]>-Date: Mon Jul 10 14:17:04 2023 -0400-- Rename file-diff --git a/tzu b/tzu.txtsimilarity index 100%rename from tzurename to tzu.txt-commit 7bd16429f1f708746dabf970e54b05d2b4734997 (HEAD -> master)-Author: John Smith <[email protected]>-Date: Tue Jul 11 18:10:49 2023 -0400-- Change file-diff --git a/tzu b/tzuindex 5af88a8..c729cdb 100644--- a/tzu@@ -1714,12 +1500,6 @@ index 5af88a8..c729cdb 100644++Source: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format-commit c7062674c17192caa284615ab2fa9778c6602164 (HEAD -> master)-Author: John Smith <[email protected]>-Date: Mon Jul 10 10:15:18 2023 -0400-- Create files-diff --git a/lao b/laonew file mode 100644index 0000000..635ef2c@@ -1759,81 +1539,42 @@ index 0000000..5af88a8`// This throws a nasty panic if it's a top-level var.-func expectedCommits() []Commit {- return []Commit{- // a+func expectedDiffs() []*Diff {+ return []*Diff{{- Hash: "fd6e99e7a80199b76a694603be57c5ade1de18e7",- Author: "Jaliborc <[email protected]>",- Date: newTime("Mon Apr 25 16:28:06 2011 +0100"),- Message: newStringBuilderValue("Added Unusable coloring\n"),- Diffs: []Diff{- {- PathB: "components/item.lua",- LineStart: 9,- contentWriter: newBufferWithContent([]byte("\n\nlocal Unfit = LibStub('Unfit-1.0')\n\n\n")),- IsBinary: false,- },- {- PathB: "embeds.xml",- LineStart: 6,- contentWriter: newBufferWithContent([]byte("\n\n <Script file=\"libs\\Unfit-1.0\\Unfit-1.0.lua\"/>\n\n\n\n")),- IsBinary: false,- },- {- PathB: "libs/Unfit-1.0",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("Subproject commit 0000000000000000000000000000000000000000\n")),- IsBinary: false,- },- },+ PathB: "components/item.lua",+ LineStart: 9,+ contentWriter: newBufferWithContent([]byte("\n\nlocal Unfit = LibStub('Unfit-1.0')\n\n\n")),+ IsBinary: false,},- // Empty commit and message. Lord help us.{- Hash: "4727ffb7ad6dc5130bf4b4dd166e00705abdd018",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 22:26:11 2023 -0400"),- Message: strings.Builder{},- Diffs: []Diff{},+ PathB: "embeds.xml",+ LineStart: 6,+ contentWriter: newBufferWithContent([]byte("\n\n <Script file=\"libs\\Unfit-1.0\\Unfit-1.0.lua\"/>\n\n\n\n")),+ IsBinary: false,},- // Empty commit.{- Hash: "c904e0f5cd9f30ae520c66bd5f70806219fe7ca2",- Author: "John Smith <[email protected]>",- Date: newTime("Mon Jul 10 10:17:11 2023 -0400"),- Message: newStringBuilderValue("Empty Commit\n"),- Diffs: []Diff{},+ PathB: "libs/Unfit-1.0",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("Subproject commit 0000000000000000000000000000000000000000\n")),+ IsBinary: false,},{- Hash: "3d76a97faad96e0f326afb61c232b9c2a18dca35",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 18:03:54 2023 -0400"),- Message: strings.Builder{},- Diffs: []Diff{- {- PathB: "sample.txt",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("Hello, world!\n")),- IsBinary: false,- },- },+ PathB: "sample.txt",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("Hello, world!\n")),+ IsBinary: false,},{- Hash: "df393b4125c2aa217211b2429b8963d0cefcee27",- Author: "Stephen <[email protected]>",- Date: newTime("Wed Dec 06 14:44:41 2017 -0800"),- Message: newStringBuilderValue("Add travis testing\n"),- Diffs: []Diff{- {- PathB: ".gitignore",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("\n\n\n**/__pycache__/\n**/*.pyc\n")),- IsBinary: false,- },- {- PathB: ".travis.yml",- LineStart: 1,- contentWriter: newBufferWithContent([]byte(`language: python+ PathB: ".gitignore",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("\n\n\n**/__pycache__/\n**/*.pyc\n")),+ IsBinary: false,+ },+ {+ PathB: ".travis.yml",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte(`language: pythonpython:- "2.6"- "2.7"@@ -1847,20 +1588,12 @@ python:- "3.7-dev" # 3.7 development branch- "nightly"`)),- IsBinary: false,- },- },+ IsBinary: false,},{- Hash: "4218c39d99b5f30153f62471c1be1c1596f0a4d4",- Author: "Dustin Decker <[email protected]>",- Date: newTime("Thu Jan 13 12:02:24 2022 -0800"),- Message: newStringBuilderValue("Initial CLI w/ partially implemented Git source and demo detector (#1)\n"),- Diffs: []Diff{- {- PathB: "Makefile",- LineStart: 1,- contentWriter: newBufferWithContent([]byte(`PROTOS_IMAGE=us-docker.pkg.dev/thog-artifacts/public/go-ci-1.17-1+ PathB: "Makefile",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte(`PROTOS_IMAGE=us-docker.pkg.dev/thog-artifacts/public/go-ci-1.17-1.PHONY: check.PHONY: test@@ -1893,163 +1626,84 @@ run:protos:docker run -u "$(shell id -u)" -v "$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))":/pwd "${PROTOS_IMAGE}" bash -c "cd /pwd; /pwd/scripts/gen_proto.sh"`)),- IsBinary: false,- },- },+ IsBinary: false,},{- Hash: "934cf5d255fd8e28b33f5a6ba64276caf0b284bf",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 18:43:22 2023 -0400"),- Message: newStringBuilderValue("Test toFile/plusLine parsing\n"),- Diffs: []Diff{- {- PathB: "plusLine.txt",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("-- test\n++ test\n\n")),- IsBinary: false,- },- },+ PathB: "plusLine.txt",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("-- test\n++ test\n\n")),+ IsBinary: false,},{- Hash: "2a5d703b02b52d65c65ee9f7928f158b919ab741",- Author: "Sergey Beryozkin <[email protected]>",- Date: newTime("Fri Jul 7 17:44:26 2023 +0100"),- Message: newStringBuilderValue("Do not refresh OIDC session if the user is requesting logout\n"),- Diffs: []Diff{- {- PathB: "extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/BackChannelLogoutTokenCache.java",- LineStart: 45,- contentWriter: newBufferWithContent([]byte("\n\n public boolean containsTokenVerification(String token) {\n return cacheMap.containsKey(token);\n }\n\n\n\n\n")),- IsBinary: false,- },- {- PathB: "extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java",- LineStart: 1023,- contentWriter: newBufferWithContent([]byte("\n\n private boolean isRpInitiatedLogout(RoutingContext context, TenantConfigContext configContext) {\n\n\n")),- IsBinary: false,- },- {- PathB: "extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java",- LineStart: 1214,- contentWriter: newBufferWithContent([]byte("\n\n\n\n private class LogoutCall implements Function<SecurityIdentity, Uni<?>> {\n RoutingContext context;\n TenantConfigContext configContext;\n String idToken;\n\n LogoutCall(RoutingContext context, TenantConfigContext configContext, String idToken) {\n this.context = context;\n this.configContext = configContext;\n this.idToken = idToken;\n }\n\n @Override\n public Uni<Void> apply(SecurityIdentity identity) {\n if (isRpInitiatedLogout(context, configContext)) {\n LOG.debug(\"Performing an RP initiated logout\");\n fireEvent(SecurityEvent.Type.OIDC_LOGOUT_RP_INITIATED, identity);\n return buildLogoutRedirectUriUni(context, configContext, idToken);\n }\n if (isBackChannelLogoutPendingAndValid(configContext, identity)\n || isFrontChannelLogoutValid(context, configContext,\n identity)) {\n return removeSessionCookie(context, configContext.oidcConfig)\n .map(new Function<Void, Void>() {\n @Override\n public Void apply(Void t) {\n throw new LogoutException();\n }\n });\n\n }\n return VOID_UNI;\n }\n }\n\n")),- IsBinary: false,- },- {- PathB: "integration-tests/oidc-wiremock/src/main/resources/application.properties",- LineStart: 20,- contentWriter: newBufferWithContent([]byte("\n\n\nquarkus.oidc.code-flow.token.refresh-expired=true\nquarkus.oidc.code-flow.token.refresh-token-time-skew=5M\n\n\n")),- IsBinary: false,- },- // WTF, shouldn't this be filtered out?- {- PathB: "integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/CodeFlowAuthorizationTest.java",- LineStart: 6,- contentWriter: newBufferWithContent([]byte("\n\n\n\n\n\n")),- IsBinary: false,- },- {- PathB: "integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/CodeFlowAuthorizationTest.java",- LineStart: 76,- contentWriter: newBufferWithContent([]byte("\n\n // Logout\n\n\n\n")),- IsBinary: false,- },- },+ PathB: "extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/BackChannelLogoutTokenCache.java",+ LineStart: 45,+ contentWriter: newBufferWithContent([]byte("\n\n public boolean containsTokenVerification(String token) {\n return cacheMap.containsKey(token);\n }\n\n\n\n\n")),+ IsBinary: false,},{- Hash: "2a057632d7f5fa3d1c77b9aa037263211c0e0290",- Author: "rjtmahinay <[email protected]>",- Date: newTime("Mon Jul 10 01:22:32 2023 +0800"),- Message: newStringBuilderValue("Add QuarkusApplication javadoc\n\n* Fix #34463\n"),- Diffs: []Diff{- {- PathB: "core/runtime/src/main/java/io/quarkus/runtime/QuarkusApplication.java",- LineStart: 3,- contentWriter: newBufferWithContent([]byte("/**\n * This is usually used for command mode applications with a startup logic. The logic is executed inside\n * {@link QuarkusApplication#run} method before the main application exits.\n */\n")),- IsBinary: false,- },- },+ PathB: "extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java",+ LineStart: 1023,+ contentWriter: newBufferWithContent([]byte("\n\n private boolean isRpInitiatedLogout(RoutingContext context, TenantConfigContext configContext) {\n\n\n")),+ IsBinary: false,},{- Hash: "bca2d17491015ea1522f34517223b5a366aea73c",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 18:12:21 2023 -0400"),- Message: newStringBuilderValue("Delete binary file\n"),- Diffs: []Diff{},+ PathB: "extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java",+ LineStart: 1214,+ contentWriter: newBufferWithContent([]byte("\n\n\n\n private class LogoutCall implements Function<SecurityIdentity, Uni<?>> {\n RoutingContext context;\n TenantConfigContext configContext;\n String idToken;\n\n LogoutCall(RoutingContext context, TenantConfigContext configContext, String idToken) {\n this.context = context;\n this.configContext = configContext;\n this.idToken = idToken;\n }\n\n @Override\n public Uni<Void> apply(SecurityIdentity identity) {\n if (isRpInitiatedLogout(context, configContext)) {\n LOG.debug(\"Performing an RP initiated logout\");\n fireEvent(SecurityEvent.Type.OIDC_LOGOUT_RP_INITIATED, identity);\n return buildLogoutRedirectUriUni(context, configContext, idToken);\n }\n if (isBackChannelLogoutPendingAndValid(configContext, identity)\n || isFrontChannelLogoutValid(context, configContext,\n identity)) {\n return removeSessionCookie(context, configContext.oidcConfig)\n .map(new Function<Void, Void>() {\n @Override\n public Void apply(Void t) {\n throw new LogoutException();\n }\n });\n\n }\n return VOID_UNI;\n }\n }\n\n")),+ IsBinary: false,},{- Hash: "afc6dc5d47f28366638da877ecb6b819c69e659b",- Author: "John Smith <[email protected]>",- Date: newTime("Mon Jul 10 12:21:33 2023 -0400"),- Message: newStringBuilderValue("Change binary file\n"),- Diffs: []Diff{- {- PathB: "trufflehog_3.42.0_linux_arm64.tar.gz",- contentWriter: newBufferWithContent([]byte("")),- IsBinary: true,- },- },+ PathB: "integration-tests/oidc-wiremock/src/main/resources/application.properties",+ LineStart: 20,+ contentWriter: newBufferWithContent([]byte("\n\n\nquarkus.oidc.code-flow.token.refresh-expired=true\nquarkus.oidc.code-flow.token.refresh-token-time-skew=5M\n\n\n")),+ IsBinary: false,},+ // WTF, shouldn't this be filtered out?{- Hash: "638595917417c5c8a956937b28c5127719023363",- Author: "John Smith <[email protected]>",- Date: newTime("Mon Jul 10 12:20:35 2023 -0400"),- Message: newStringBuilderValue("Add binary file\n"),- Diffs: []Diff{- {- PathB: "trufflehog_3.42.0_linux_arm64.tar.gz",- contentWriter: newBufferWithContent([]byte("")),- IsBinary: true,- },- },+ PathB: "integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/CodeFlowAuthorizationTest.java",+ LineStart: 6,+ contentWriter: newBufferWithContent([]byte("\n\n\n\n\n\n")),+ IsBinary: false,},{- Hash: "ce0f5d1fe0272f180ccb660196f439c0c2f4ec8e",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 18:08:52 2023 -0400"),- Message: newStringBuilderValue("Delete file\n"),- Diffs: []Diff{},+ PathB: "integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/CodeFlowAuthorizationTest.java",+ LineStart: 76,+ contentWriter: newBufferWithContent([]byte("\n\n // Logout\n\n\n\n")),+ IsBinary: false,},{- Hash: "d606a729383371558473b70a6a7b1ca264b0d205",- Author: "John Smith <[email protected]>",- Date: newTime("Mon Jul 10 14:17:04 2023 -0400"),- Message: newStringBuilderValue("Rename file\n"),- Diffs: []Diff{},+ PathB: "core/runtime/src/main/java/io/quarkus/runtime/QuarkusApplication.java",+ LineStart: 3,+ contentWriter: newBufferWithContent([]byte("/**\n * This is usually used for command mode applications with a startup logic. The logic is executed inside\n * {@link QuarkusApplication#run} method before the main application exits.\n */\n")),+ IsBinary: false,},{- Hash: "7bd16429f1f708746dabf970e54b05d2b4734997",- Author: "John Smith <[email protected]>",- Date: newTime("Tue Jul 11 18:10:49 2023 -0400"),- Message: newStringBuilderValue("Change file\n"),- Diffs: []Diff{- {- PathB: "tzu",- LineStart: 11,- contentWriter: newBufferWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),- IsBinary: false,- },- },+ PathB: "trufflehog_3.42.0_linux_arm64.tar.gz",+ contentWriter: newBufferWithContent([]byte("")),+ IsBinary: true,},{- Hash: "c7062674c17192caa284615ab2fa9778c6602164",- Author: "John Smith <[email protected]>",- Date: newTime("Mon Jul 10 10:15:18 2023 -0400"),- Message: newStringBuilderValue("Create files\n"),- Diffs: []Diff{- {- PathB: "lao",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("The Way that can be told of is not the eternal Way;\nThe name that can be named is not the eternal name.\nThe Nameless is the origin of Heaven and Earth;\nThe Named is the mother of all things.\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\n")),- IsBinary: false,- },- {- PathB: "tzu",- LineStart: 1,- contentWriter: newBufferWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),- IsBinary: false,- },- },+ PathB: "trufflehog_3.42.0_linux_arm64.tar.gz",+ contentWriter: newBufferWithContent([]byte("")),+ IsBinary: true,+ },+ {+ PathB: "tzu",+ LineStart: 11,+ contentWriter: newBufferWithContent([]byte("\n\n\n\nSource: https://www.gnu.org/software/diffutils/manual/diffutils.html#An-Example-of-Unified-Format\n")),+ IsBinary: false,+ },+ {+ PathB: "lao",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("The Way that can be told of is not the eternal Way;\nThe name that can be named is not the eternal name.\nThe Nameless is the origin of Heaven and Earth;\nThe Named is the mother of all things.\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\n")),+ IsBinary: false,+ },+ {+ PathB: "tzu",+ LineStart: 1,+ contentWriter: newBufferWithContent([]byte("The Nameless is the origin of Heaven and Earth;\nThe named is the mother of all things.\n\nTherefore let there always be non-being,\n so we may see their subtlety,\nAnd let there always be being,\n so we may see their outcome.\nThe two are the same,\nBut after they are produced,\n they have different names.\nThey both may be called deep and profound.\nDeeper and more profound,\nThe door of all subtleties!\n")),+ IsBinary: false,},}}diff --git a/pkg/sources/git/git.go b/pkg/sources/git/git.goindex 279b9acaa..3a1512cb5 100644--- a/pkg/sources/git/git.go+++ b/pkg/sources/git/git.go@@ -521,15 +521,14 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path stringrepoCtx = context.WithValue(ctx, "repo", path)}- commitChan, err := s.parser.RepoPath(repoCtx, path, scanOptions.HeadHash, scanOptions.BaseHash == "", scanOptions.ExcludeGlobs, scanOptions.Bare)+ diffChan, err := s.parser.RepoPath(repoCtx, path, scanOptions.HeadHash, scanOptions.BaseHash == "", scanOptions.ExcludeGlobs, scanOptions.Bare)if err != nil {return err}- if commitChan == nil {+ if diffChan == nil {return nil}- var depth int64gitDir := filepath.Join(path, gitDirName)logger := repoCtx.Logger()@@ -542,87 +541,107 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path string}logger.V(1).Info("scanning repo", logValues...)- for commit := range commitChan {- if len(scanOptions.BaseHash) > 0 {- if commit.Hash == scanOptions.BaseHash {- logger.V(1).Info("reached base commit", "commit", commit.Hash[:7])- break- }- }+ var depth int64+ var lastCommitHash string+ for diff := range diffChan {if scanOptions.MaxDepth > 0 && depth >= scanOptions.MaxDepth {logger.V(1).Info("reached max depth", "depth", depth)break}- depth++- atomic.AddUint64(&s.metrics.commitsScanned, 1)- logger.V(5).Info("scanning commit", "commit", commit.Hash[:7])- for _, diff := range commit.Diffs {- diff := diff- if !scanOptions.Filter.Pass(diff.PathB) {- continue- }- fileName := diff.PathB- if fileName == "" {- continue+ fullHash := diff.Commit.Hash+ if !strings.EqualFold(fullHash, lastCommitHash) {+ depth+++ lastCommitHash = fullHash+ atomic.AddUint64(&s.metrics.commitsScanned, 1)+ logger.V(5).Info("scanning commit", "commit", fullHash)+ }+ if len(scanOptions.BaseHash) > 0 {+ if fullHash == scanOptions.BaseHash {+ logger.V(1).Info("reached base commit", "commit", fullHash)+ break}- var email, hash, when string- email = commit.Author- hash = commit.Hash- when = commit.Date.UTC().Format("2006-01-02 15:04:05 -0700")-- // Handle binary files by reading the entire file rather than using the diff.- if diff.IsBinary {- commitHash := plumbing.NewHash(hash)- metadata := s.sourceMetadataFunc(fileName, email, hash, when, remoteURL, 0)- chunkSkel := &sources.Chunk{- SourceName: s.sourceName,- SourceID: s.sourceID,- JobID: s.jobID,- SourceType: s.sourceType,- SourceMetadata: metadata,- Verify: s.verify,- }- if err := s.handleBinary(ctx, gitDir, reporter, chunkSkel, commitHash, fileName); err != nil {- logger.V(1).Info("error handling binary file", "error", err, "filename", fileName, "commit", commitHash, "file", diff.PathB)- }- continue+ }++ if !scanOptions.Filter.Pass(diff.PathB) {+ continue+ }++ fileName := diff.PathB+ if fileName == "" {+ continue+ }+ email := diff.Commit.Author+ when := diff.Commit.Date.UTC().Format("2006-01-02 15:04:05 -0700")++ // Handle binary files by reading the entire file rather than using the diff.+ if diff.IsBinary {+ metadata := s.sourceMetadataFunc(fileName, email, fullHash, when, remoteURL, 0)+ chunkSkel := &sources.Chunk{+ SourceName: s.sourceName,+ SourceID: s.sourceID,+ JobID: s.jobID,+ SourceType: s.sourceType,+ SourceMetadata: metadata,+ Verify: s.verify,}- if diff.Len() > sources.ChunkSize+sources.PeekSize {- s.gitChunk(ctx, &diff, fileName, email, hash, when, remoteURL, reporter)- continue+ commitHash := plumbing.NewHash(fullHash)+ if err := s.handleBinary(ctx, gitDir, reporter, chunkSkel, commitHash, fileName); err != nil {+ logger.V(1).Info(+ "error handling binary file",+ "error", err,+ "filename", fileName,+ "commit", commitHash,+ "file", diff.PathB,+ )}+ continue+ }- chunkData := func(d *gitparse.Diff) error {- metadata := s.sourceMetadataFunc(fileName, email, hash, when, remoteURL, int64(diff.LineStart))+ if diff.Len() > sources.ChunkSize+sources.PeekSize {+ s.gitChunk(ctx, diff, fileName, email, fullHash, when, remoteURL, reporter)+ continue+ }- reader, err := d.ReadCloser()- if err != nil {- ctx.Logger().Error(err, "error creating reader for commits", "filename", fileName, "commit", hash, "file", diff.PathB)- return nil- }- defer reader.Close()+ chunkData := func(d *gitparse.Diff) error {+ metadata := s.sourceMetadataFunc(fileName, email, fullHash, when, remoteURL, int64(diff.LineStart))- data := make([]byte, diff.Len())- if _, err := reader.Read(data); err != nil {- ctx.Logger().Error(err, "error reading diff content for commit", "filename", fileName, "commit", hash, "file", diff.PathB)- return nil- }- chunk := sources.Chunk{- SourceName: s.sourceName,- SourceID: s.sourceID,- JobID: s.jobID,- SourceType: s.sourceType,- SourceMetadata: metadata,- Data: data,- Verify: s.verify,- }- return reporter.ChunkOk(ctx, chunk)+ reader, err := d.ReadCloser()+ if err != nil {+ ctx.Logger().Error(+ err, "error creating reader for commits",+ "filename", fileName,+ "commit", fullHash,+ "file", diff.PathB,+ )+ return nil}- if err := chunkData(&diff); err != nil {- return err+ defer reader.Close()++ data := make([]byte, d.Len())+ if _, err := reader.Read(data); err != nil {+ ctx.Logger().Error(+ err, "error reading diff content for commit",+ "filename", fileName,+ "commit", fullHash,+ "file", diff.PathB,+ )+ return nil}+ chunk := sources.Chunk{+ SourceName: s.sourceName,+ SourceID: s.sourceID,+ JobID: s.jobID,+ SourceType: s.sourceType,+ SourceMetadata: metadata,+ Data: data,+ Verify: s.verify,+ }+ return reporter.ChunkOk(ctx, chunk)+ }+ if err := chunkData(diff); err != nil {+ return err}}return nil@@ -713,100 +732,116 @@ func (s *Git) ScanStaged(ctx context.Context, repo *git.Repository, path string,// Get the URL metadata for reporting (may be empty).urlMetadata := getSafeRemoteURL(repo, "origin")- commitChan, err := gitparse.NewParser().Staged(ctx, path)+ diffChan, err := gitparse.NewParser().Staged(ctx, path)if err != nil {return err}- if commitChan == nil {+ if diffChan == nil {return nil}- var depth int64reachedBase := falsegitDir := filepath.Join(path, gitDirName)ctx.Logger().V(1).Info("scanning staged changes", "path", path)- for commit := range commitChan {- for _, diff := range commit.Diffs {- diff := diff- logger := ctx.Logger().WithValues("filename", diff.PathB, "commit", commit.Hash, "file", diff.PathB)- logger.V(2).Info("scanning staged changes from git")-- if scanOptions.MaxDepth > 0 && depth >= scanOptions.MaxDepth {- logger.V(1).Info("reached max depth")- break- }++ var depth int64+ var lastCommitHash string+ for diff := range diffChan {+ fullHash := diff.Commit.Hash+ logger := ctx.Logger().WithValues("filename", diff.PathB, "commit", fullHash, "file", diff.PathB)+ logger.V(2).Info("scanning staged changes from git")++ if scanOptions.MaxDepth > 0 && depth >= scanOptions.MaxDepth {+ logger.V(1).Info("reached max depth")+ break+ }++ if !strings.EqualFold(fullHash, lastCommitHash) {depth++- if reachedBase && commit.Hash != scanOptions.BaseHash {- break- }- if len(scanOptions.BaseHash) > 0 {- if commit.Hash == scanOptions.BaseHash {- logger.V(1).Info("reached base hash, finishing scanning files")- reachedBase = true- }- }+ lastCommitHash = fullHash+ atomic.AddUint64(&s.metrics.commitsScanned, 1)+ }- if !scanOptions.Filter.Pass(diff.PathB) {- continue+ if reachedBase && !strings.EqualFold(fullHash, scanOptions.BaseHash) {+ break+ }++ if len(scanOptions.BaseHash) > 0 {+ if strings.EqualFold(fullHash, scanOptions.BaseHash) {+ logger.V(1).Info("reached base hash, finishing scanning files")+ reachedBase = true}+ }- fileName := diff.PathB- if fileName == "" {- continue+ if !scanOptions.Filter.Pass(diff.PathB) {+ continue+ }++ fileName := diff.PathB+ if fileName == "" {+ continue+ }++ email := diff.Commit.Author+ when := diff.Commit.Date.UTC().Format("2006-01-02 15:04:05 -0700")++ // Handle binary files by reading the entire file rather than using the diff.+ if diff.IsBinary {+ commitHash := plumbing.NewHash(fullHash)+ metadata := s.sourceMetadataFunc(fileName, email, "Staged", when, urlMetadata, 0)+ chunkSkel := &sources.Chunk{+ SourceName: s.sourceName,+ SourceID: s.sourceID,+ JobID: s.jobID,+ SourceType: s.sourceType,+ SourceMetadata: metadata,+ Verify: s.verify,}- var email, hash, when string- email = commit.Author- hash = commit.Hash- when = commit.Date.UTC().Format("2006-01-02 15:04:05 -0700")-- // Handle binary files by reading the entire file rather than using the diff.- if diff.IsBinary {- commitHash := plumbing.NewHash(hash)- metadata := s.sourceMetadataFunc(fileName, email, "Staged", when, urlMetadata, 0)- chunkSkel := &sources.Chunk{- SourceName: s.sourceName,- SourceID: s.sourceID,- JobID: s.jobID,- SourceType: s.sourceType,- SourceMetadata: metadata,- Verify: s.verify,- }- if err := s.handleBinary(ctx, gitDir, reporter, chunkSkel, commitHash, fileName); err != nil {- logger.V(1).Info("error handling binary file", "error", err, "filename", fileName)- }- continue+ if err := s.handleBinary(ctx, gitDir, reporter, chunkSkel, commitHash, fileName); err != nil {+ logger.V(1).Info("error handling binary file", "error", err, "filename", fileName)}+ continue+ }- chunkData := func(d *gitparse.Diff) error {- metadata := s.sourceMetadataFunc(fileName, email, "Staged", when, urlMetadata, int64(diff.LineStart))-- reader, err := diff.ReadCloser()- if err != nil {- ctx.Logger().Error(err, "error creating reader for staged", "filename", fileName, "commit", hash, "file", diff.PathB)- return nil- }- defer reader.Close()+ chunkData := func(d *gitparse.Diff) error {+ metadata := s.sourceMetadataFunc(fileName, email, "Staged", when, urlMetadata, int64(diff.LineStart))- data := make([]byte, diff.Len())- if _, err := reader.Read(data); err != nil {- ctx.Logger().Error(err, "error reading diff content for staged", "filename", fileName, "commit", hash, "file", diff.PathB)- return nil- }- chunk := sources.Chunk{- SourceName: s.sourceName,- SourceID: s.sourceID,- JobID: s.jobID,- SourceType: s.sourceType,- SourceMetadata: metadata,- Data: data,- Verify: s.verify,- }- return reporter.ChunkOk(ctx, chunk)+ reader, err := d.ReadCloser()+ if err != nil {+ ctx.Logger().Error(+ err, "error creating reader for staged",+ "filename", fileName,+ "commit", fullHash,+ "file", diff.PathB,+ )+ return nil}- if err := chunkData(&diff); err != nil {- return err+ defer reader.Close()++ data := make([]byte, d.Len())+ if _, err := reader.Read(data); err != nil {+ ctx.Logger().Error(+ err, "error reading diff content for staged",+ "filename", fileName,+ "commit", fullHash,+ "file", diff.PathB,+ )+ return nil}+ chunk := sources.Chunk{+ SourceName: s.sourceName,+ SourceID: s.sourceID,+ JobID: s.jobID,+ SourceType: s.sourceType,+ SourceMetadata: metadata,+ Data: data,+ Verify: s.verify,+ }+ return reporter.ChunkOk(ctx, chunk)+ }+ if err := chunkData(diff); err != nil {+ return err}}return nil