11using System ;
22using System . IO ;
33using System . IO . Compression ;
4+ using System . Security . Cryptography ;
45using System . Text ;
56using Semmle . Util ;
67using Semmle . Util . Logging ;
@@ -170,21 +171,23 @@ public void Dispose()
170171 WriterLazy . Value . Close ( ) ;
171172 if ( TryMove ( tmpFile , TrapFile ) )
172173 return ;
173- else if ( discardDuplicates )
174+
175+ if ( discardDuplicates )
174176 {
175177 FileUtils . TryDelete ( tmpFile ) ;
176178 return ;
177179 }
178180
179- string root = TrapFile . Substring ( 0 , TrapFile . Length - 8 ) ; // Remove trailing ".trap.gz"
180-
181- // Loop until we find an available trap filename.
182- for ( int n = 0 ; n < 100 ; ++ n )
181+ var existingHash = ComputeHash ( TrapFile ) ;
182+ var hash = ComputeHash ( tmpFile ) ;
183+ if ( existingHash != hash )
183184 {
184- if ( TryMove ( tmpFile , string . Format ( "{0}.{1}.trap.gz" , root , n ) ) )
185+ var root = TrapFile . Substring ( 0 , TrapFile . Length - 8 ) ; // Remove trailing ".trap.gz"
186+ if ( TryMove ( tmpFile , $ "{ root } -{ hash } .trap.gz") )
185187 return ;
186188 }
187- Logger . Log ( Severity . Error , "Failed to move the trap file from {0} to {1}" , tmpFile , TrapFile ) ;
189+ Logger . Log ( Severity . Info , "Identical trap file for {0} already exists" , TrapFile ) ;
190+ FileUtils . TryDelete ( tmpFile ) ;
188191 }
189192 }
190193 catch ( Exception ex )
@@ -203,6 +206,19 @@ public void Emit(ITrapEmitter emitter)
203206 //#################### PRIVATE METHODS ####################
204207 #region
205208
209+ /// <summary>
210+ /// Computes the hash of <paramref name="filePath"/>.
211+ /// </summary>
212+ static string ComputeHash ( string filePath )
213+ {
214+ using ( var fileStream = new FileStream ( filePath , FileMode . Open , FileAccess . Read ) )
215+ using ( var shaAlg = new SHA256Managed ( ) )
216+ {
217+ var sha = shaAlg . ComputeHash ( fileStream ) ;
218+ return Convert . ToBase64String ( sha ) ;
219+ }
220+ }
221+
206222 class TrapBuilder : ITrapBuilder
207223 {
208224 readonly StreamWriter StreamWriter ;
0 commit comments