1
1
package com .bazel_diff ;
2
2
3
- import java .io .ByteArrayOutputStream ;
4
- import java .io .File ;
5
- import java .io .FileInputStream ;
6
- import java .io .IOException ;
7
- import java .nio .file .Files ;
3
+ import java .io .*;
4
+ import java .nio .ByteBuffer ;
5
+ import java .nio .channels .FileChannel ;
8
6
import java .nio .file .Path ;
7
+ import java .nio .file .Paths ;
8
+ import java .io .IOException ;
9
9
import java .security .MessageDigest ;
10
10
import java .security .NoSuchAlgorithmException ;
11
11
@@ -18,21 +18,44 @@ class BazelSourceFileTargetImpl implements BazelSourceFileTarget {
18
18
private String name ;
19
19
private byte [] digest ;
20
20
21
- BazelSourceFileTargetImpl (String name , byte [] digest , Path workingDirectory )
21
+ private void digestLargeFile (MessageDigest finalDigest , FileChannel inChannel ) throws IOException {
22
+ int bufferSize = 10240 ; // 10kb
23
+ ByteBuffer buffer = ByteBuffer .allocate (bufferSize );
24
+ while (inChannel .read (buffer ) != -1 ) {
25
+ buffer .flip ();
26
+ finalDigest .update (buffer );
27
+ buffer .clear ();
28
+ }
29
+ }
30
+
31
+ private void digestSmallFile (MessageDigest finalDigest , FileChannel inChannel ) throws IOException {
32
+ long fileSize = inChannel .size ();
33
+ ByteBuffer buffer = ByteBuffer .allocate ((int ) fileSize );
34
+ inChannel .read (buffer );
35
+ buffer .flip ();
36
+ finalDigest .update (buffer );
37
+ }
38
+
39
+ BazelSourceFileTargetImpl (String name , byte [] digest , Path workingDirectory , Boolean verbose )
22
40
throws IOException , NoSuchAlgorithmException {
23
41
this .name = name ;
24
42
MessageDigest finalDigest = MessageDigest .getInstance ("SHA-256" );
25
43
if (workingDirectory != null && name .startsWith ("//" )) {
26
44
String filenameSubstring = name .substring (2 );
27
45
String filenamePath = filenameSubstring .replaceFirst (":" , "/" );
28
- File sourceFile = new File (workingDirectory .toString (), filenamePath );
29
- if (sourceFile .isFile () && sourceFile .canRead ()) {
30
- byte [] buffer = new byte [16384 ];
31
- FileInputStream in = new FileInputStream (sourceFile );
32
- int rc = in .read (buffer );
33
- while (rc != -1 ) {
34
- finalDigest .update (buffer , 0 , rc );
35
- rc = in .read (buffer );
46
+ Path absoluteFilePath = Paths .get (workingDirectory .toString (), filenamePath );
47
+ try (RandomAccessFile sourceFile = new RandomAccessFile (absoluteFilePath .toString (), "r" )) {
48
+ FileChannel inChannel = sourceFile .getChannel ();
49
+ if (inChannel .size () > 1048576 ) { // 1mb
50
+ digestLargeFile (finalDigest , inChannel );
51
+ } else {
52
+ digestSmallFile (finalDigest , inChannel );
53
+ }
54
+ sourceFile .close ();
55
+ inChannel .close ();
56
+ } catch (FileNotFoundException e ) {
57
+ if (verbose ) {
58
+ System .out .printf ("BazelDiff: [Warning] file %s not found%n" , absoluteFilePath );
36
59
}
37
60
}
38
61
}
0 commit comments