1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 package org.eclipse.jgit.util;
45
46 import java.io.BufferedReader;
47 import java.io.BufferedWriter;
48 import java.io.File;
49 import java.io.IOException;
50 import java.io.InputStream;
51 import java.io.InputStreamReader;
52 import java.io.OutputStream;
53 import java.io.OutputStreamWriter;
54 import java.io.PrintStream;
55 import java.io.PrintWriter;
56 import java.nio.charset.Charset;
57 import java.security.AccessController;
58 import java.security.PrivilegedAction;
59 import java.text.MessageFormat;
60 import java.util.Arrays;
61 import java.util.HashMap;
62 import java.util.Map;
63 import java.util.concurrent.Callable;
64 import java.util.concurrent.ExecutorService;
65 import java.util.concurrent.Executors;
66 import java.util.concurrent.TimeUnit;
67 import java.util.concurrent.atomic.AtomicBoolean;
68
69 import org.eclipse.jgit.api.errors.JGitInternalException;
70 import org.eclipse.jgit.internal.JGitText;
71 import org.eclipse.jgit.lib.Constants;
72 import org.eclipse.jgit.lib.Repository;
73 import org.eclipse.jgit.util.ProcessResult.Status;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76
77
78 public abstract class FS {
79
80
81
82
83
84
85 public static class FSFactory {
86
87
88
89 protected FSFactory() {
90
91 }
92
93
94
95
96
97
98
99 public FS detect(Boolean cygwinUsed) {
100 if (SystemReader.getInstance().isWindows()) {
101 if (cygwinUsed == null)
102 cygwinUsed = Boolean.valueOf(FS_Win32_Cygwin.isCygwin());
103 if (cygwinUsed.booleanValue())
104 return new FS_Win32_Cygwin();
105 else
106 return new FS_Win32();
107 } else {
108 return new FS_POSIX();
109 }
110 }
111 }
112
113 private final static Logger LOG = LoggerFactory.getLogger(FS.class);
114
115
116 public static final FS DETECTED = detect();
117
118 private static FSFactory factory;
119
120
121
122
123
124
125 public static FS detect() {
126 return detect(null);
127 }
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150 public static FS detect(Boolean cygwinUsed) {
151 if (factory == null) {
152 factory = new FS.FSFactory();
153 }
154 return factory.detect(cygwinUsed);
155 }
156
157 private volatile Holder<File> userHome;
158
159 private volatile Holder<File> gitSystemConfig;
160
161
162
163
164 protected FS() {
165
166 }
167
168
169
170
171
172
173
174 protected FS(FS src) {
175 userHome = src.userHome;
176 gitSystemConfig = src.gitSystemConfig;
177 }
178
179
180 public abstract FS newInstance();
181
182
183
184
185
186
187
188 public abstract boolean supportsExecute();
189
190
191
192
193
194
195
196
197 public boolean supportsSymlinks() {
198 return false;
199 }
200
201
202
203
204
205
206 public abstract boolean isCaseSensitive();
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222 public abstract boolean canExecute(File f);
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237 public abstract boolean setExecute(File f, boolean canExec);
238
239
240
241
242
243
244
245
246
247
248
249 public long lastModified(File f) throws IOException {
250 return FileUtils.lastModified(f);
251 }
252
253
254
255
256
257
258
259
260
261
262 public void setLastModified(File f, long time) throws IOException {
263 FileUtils.setLastModified(f, time);
264 }
265
266
267
268
269
270
271
272
273
274
275 public long length(File path) throws IOException {
276 return FileUtils.getLength(path);
277 }
278
279
280
281
282
283
284
285
286
287 public void delete(File f) throws IOException {
288 FileUtils.delete(f);
289 }
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309 public File resolve(final File dir, final String name) {
310 final File abspn = new File(name);
311 if (abspn.isAbsolute())
312 return abspn;
313 return new File(dir, name);
314 }
315
316
317
318
319
320
321
322
323
324
325
326
327 public File userHome() {
328 Holder<File> p = userHome;
329 if (p == null) {
330 p = new Holder<File>(userHomeImpl());
331 userHome = p;
332 }
333 return p.value;
334 }
335
336
337
338
339
340
341
342
343
344 public FS setUserHome(File path) {
345 userHome = new Holder<File>(path);
346 return this;
347 }
348
349
350
351
352
353
354 public abstract boolean retryFailedLockFileCommit();
355
356
357
358
359
360
361 protected File userHomeImpl() {
362 final String home = AccessController
363 .doPrivileged(new PrivilegedAction<String>() {
364 public String run() {
365 return System.getProperty("user.home");
366 }
367 });
368 if (home == null || home.length() == 0)
369 return null;
370 return new File(home).getAbsoluteFile();
371 }
372
373
374
375
376
377
378
379
380
381
382
383
384 protected static File searchPath(final String path, final String... lookFor) {
385 if (path == null)
386 return null;
387
388 for (final String p : path.split(File.pathSeparator)) {
389 for (String command : lookFor) {
390 final File e = new File(p, command);
391 if (e.isFile())
392 return e.getAbsoluteFile();
393 }
394 }
395 return null;
396 }
397
398
399
400
401
402
403
404
405
406
407
408
409 protected static String readPipe(File dir, String[] command, String encoding) {
410 return readPipe(dir, command, encoding, null);
411 }
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428 protected static String readPipe(File dir, String[] command, String encoding, Map<String, String> env) {
429 final boolean debug = LOG.isDebugEnabled();
430 try {
431 if (debug) {
432 LOG.debug("readpipe " + Arrays.asList(command) + ","
433 + dir);
434 }
435 ProcessBuilder pb = new ProcessBuilder(command);
436 pb.directory(dir);
437 if (env != null) {
438 pb.environment().putAll(env);
439 }
440 Process p = pb.start();
441 BufferedReader lineRead = new BufferedReader(
442 new InputStreamReader(p.getInputStream(), encoding));
443 p.getOutputStream().close();
444 GobblerThread gobbler = new GobblerThread(p, command, dir);
445 gobbler.start();
446 String r = null;
447 try {
448 r = lineRead.readLine();
449 if (debug) {
450 LOG.debug("readpipe may return '" + r + "'");
451 LOG.debug("(ignoring remaing output:");
452 }
453 String l;
454 while ((l = lineRead.readLine()) != null) {
455 if (debug) {
456 LOG.debug(l);
457 }
458 }
459 } finally {
460 p.getErrorStream().close();
461 lineRead.close();
462 }
463
464 for (;;) {
465 try {
466 int rc = p.waitFor();
467 gobbler.join();
468 if (rc == 0 && r != null && r.length() > 0
469 && !gobbler.fail.get())
470 return r;
471 if (debug) {
472 LOG.debug("readpipe rc=" + rc);
473 }
474 break;
475 } catch (InterruptedException ie) {
476
477 }
478 }
479 } catch (IOException e) {
480 LOG.debug("Caught exception in FS.readPipe()", e);
481 }
482 if (debug) {
483 LOG.debug("readpipe returns null");
484 }
485 return null;
486 }
487
488 private static class GobblerThread extends Thread {
489 private final Process p;
490 private final String desc;
491 private final String dir;
492 private final boolean debug = LOG.isDebugEnabled();
493 private final AtomicBoolean fail = new AtomicBoolean();
494
495 private GobblerThread(Process p, String[] command, File dir) {
496 this.p = p;
497 if (debug) {
498 this.desc = Arrays.asList(command).toString();
499 this.dir = dir.toString();
500 } else {
501 this.desc = null;
502 this.dir = null;
503 }
504 }
505
506 public void run() {
507 InputStream is = p.getErrorStream();
508 try {
509 int ch;
510 if (debug) {
511 while ((ch = is.read()) != -1) {
512 System.err.print((char) ch);
513 }
514 } else {
515 while (is.read() != -1) {
516
517 }
518 }
519 } catch (IOException e) {
520 logError(e);
521 fail.set(true);
522 }
523 try {
524 is.close();
525 } catch (IOException e) {
526 logError(e);
527 fail.set(true);
528 }
529 }
530
531 private void logError(Throwable t) {
532 if (!debug) {
533 return;
534 }
535 String msg = MessageFormat.format(
536 JGitText.get().exceptionCaughtDuringExcecutionOfCommand, desc, dir);
537 LOG.debug(msg, t);
538 }
539 }
540
541
542
543
544
545
546 protected abstract File discoverGitExe();
547
548
549
550
551
552
553 protected File discoverGitSystemConfig() {
554 File gitExe = discoverGitExe();
555 if (gitExe == null) {
556 return null;
557 }
558
559
560
561 Map<String, String> env = new HashMap<>();
562 env.put("GIT_EDITOR", "echo");
563
564 String w = readPipe(gitExe.getParentFile(),
565 new String[] { "git", "config", "--system", "--edit" },
566 Charset.defaultCharset().name(), env);
567 if (StringUtils.isEmptyOrNull(w)) {
568 return null;
569 }
570
571 return new File(w);
572 }
573
574
575
576
577
578
579 public File getGitSystemConfig() {
580 if (gitSystemConfig == null) {
581 gitSystemConfig = new Holder<File>(discoverGitSystemConfig());
582 }
583 return gitSystemConfig.value;
584 }
585
586
587
588
589
590
591
592
593
594 public FS setGitSystemConfig(File configFile) {
595 gitSystemConfig = new Holder<File>(configFile);
596 return this;
597 }
598
599
600
601
602
603
604
605 protected static File resolveGrandparentFile(File grandchild) {
606 if (grandchild != null) {
607 File parent = grandchild.getParentFile();
608 if (parent != null)
609 return parent.getParentFile();
610 }
611 return null;
612 }
613
614
615
616
617
618
619
620
621
622 public String readSymLink(File path) throws IOException {
623 return FileUtils.readSymLink(path);
624 }
625
626
627
628
629
630
631
632 public boolean isSymLink(File path) throws IOException {
633 return FileUtils.isSymlink(path);
634 }
635
636
637
638
639
640
641
642
643
644 public boolean exists(File path) {
645 return FileUtils.exists(path);
646 }
647
648
649
650
651
652
653
654
655
656 public boolean isDirectory(File path) {
657 return FileUtils.isDirectory(path);
658 }
659
660
661
662
663
664
665
666
667
668 public boolean isFile(File path) {
669 return FileUtils.isFile(path);
670 }
671
672
673
674
675
676
677
678
679 public boolean isHidden(File path) throws IOException {
680 return FileUtils.isHidden(path);
681 }
682
683
684
685
686
687
688
689
690
691 public void setHidden(File path, boolean hidden) throws IOException {
692 FileUtils.setHidden(path, hidden);
693 }
694
695
696
697
698
699
700
701
702
703 public void createSymLink(File path, String target) throws IOException {
704 FileUtils.createSymLink(path, target);
705 }
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720 public String relativize(String base, String other) {
721 return FileUtils.relativize(base, other);
722 }
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746 public ProcessResult runHookIfPresent(Repository repository,
747 final String hookName,
748 String[] args) throws JGitInternalException {
749 return runHookIfPresent(repository, hookName, args, System.out, System.err,
750 null);
751 }
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781 public ProcessResult runHookIfPresent(Repository repository,
782 final String hookName,
783 String[] args, PrintStream outRedirect, PrintStream errRedirect,
784 String stdinArgs) throws JGitInternalException {
785 return new ProcessResult(Status.NOT_SUPPORTED);
786 }
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817 protected ProcessResult internalRunHookIfPresent(Repository repository,
818 final String hookName, String[] args, PrintStream outRedirect,
819 PrintStream errRedirect, String stdinArgs)
820 throws JGitInternalException {
821 final File hookFile = findHook(repository, hookName);
822 if (hookFile == null)
823 return new ProcessResult(Status.NOT_PRESENT);
824
825 final String hookPath = hookFile.getAbsolutePath();
826 final File runDirectory;
827 if (repository.isBare())
828 runDirectory = repository.getDirectory();
829 else
830 runDirectory = repository.getWorkTree();
831 final String cmd = relativize(runDirectory.getAbsolutePath(),
832 hookPath);
833 ProcessBuilder hookProcess = runInShell(cmd, args);
834 hookProcess.directory(runDirectory);
835 try {
836 return new ProcessResult(runProcess(hookProcess, outRedirect,
837 errRedirect, stdinArgs), Status.OK);
838 } catch (IOException e) {
839 throw new JGitInternalException(MessageFormat.format(
840 JGitText.get().exceptionCaughtDuringExecutionOfHook,
841 hookName), e);
842 } catch (InterruptedException e) {
843 throw new JGitInternalException(MessageFormat.format(
844 JGitText.get().exceptionHookExecutionInterrupted,
845 hookName), e);
846 }
847 }
848
849
850
851
852
853
854
855
856
857
858
859
860
861 public File findHook(Repository repository, final String hookName) {
862 File gitDir = repository.getDirectory();
863 if (gitDir == null)
864 return null;
865 final File hookFile = new File(new File(gitDir,
866 Constants.HOOKS), hookName);
867 return hookFile.isFile() ? hookFile : null;
868 }
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895 protected int runProcess(ProcessBuilder hookProcessBuilder,
896 OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
897 throws IOException, InterruptedException {
898 final ExecutorService executor = Executors.newFixedThreadPool(2);
899 Process process = null;
900
901
902 IOException ioException = null;
903 try {
904 process = hookProcessBuilder.start();
905 final Callable<Void> errorGobbler = new StreamGobbler(
906 process.getErrorStream(), errRedirect);
907 final Callable<Void> outputGobbler = new StreamGobbler(
908 process.getInputStream(), outRedirect);
909 executor.submit(errorGobbler);
910 executor.submit(outputGobbler);
911 if (stdinArgs != null) {
912 final PrintWriter stdinWriter = new PrintWriter(
913 process.getOutputStream());
914 stdinWriter.print(stdinArgs);
915 stdinWriter.flush();
916
917
918 stdinWriter.close();
919 }
920 return process.waitFor();
921 } catch (IOException e) {
922 ioException = e;
923 } finally {
924 shutdownAndAwaitTermination(executor);
925 if (process != null) {
926 try {
927 process.waitFor();
928 } catch (InterruptedException e) {
929
930
931
932
933 Thread.interrupted();
934 }
935
936
937
938 try {
939 process.getErrorStream().close();
940 } catch (IOException e) {
941 ioException = ioException != null ? ioException : e;
942 }
943 try {
944 process.getInputStream().close();
945 } catch (IOException e) {
946 ioException = ioException != null ? ioException : e;
947 }
948 try {
949 process.getOutputStream().close();
950 } catch (IOException e) {
951 ioException = ioException != null ? ioException : e;
952 }
953 process.destroy();
954 }
955 }
956
957 throw ioException;
958 }
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973 private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
974 boolean hasShutdown = true;
975 pool.shutdown();
976 try {
977
978 if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
979 pool.shutdownNow();
980
981 if (!pool.awaitTermination(5, TimeUnit.SECONDS))
982 hasShutdown = false;
983 }
984 } catch (InterruptedException ie) {
985
986 pool.shutdownNow();
987
988 Thread.currentThread().interrupt();
989 hasShutdown = false;
990 }
991 return hasShutdown;
992 }
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006 public abstract ProcessBuilder runInShell(String cmd, String[] args);
1007
1008 private static class Holder<V> {
1009 final V value;
1010
1011 Holder(V value) {
1012 this.value = value;
1013 }
1014 }
1015
1016
1017
1018
1019
1020
1021 public static class Attributes {
1022
1023
1024
1025
1026 public boolean isDirectory() {
1027 return isDirectory;
1028 }
1029
1030
1031
1032
1033 public boolean isExecutable() {
1034 return isExecutable;
1035 }
1036
1037
1038
1039
1040 public boolean isSymbolicLink() {
1041 return isSymbolicLink;
1042 }
1043
1044
1045
1046
1047 public boolean isRegularFile() {
1048 return isRegularFile;
1049 }
1050
1051
1052
1053
1054 public long getCreationTime() {
1055 return creationTime;
1056 }
1057
1058
1059
1060
1061
1062 public long getLastModifiedTime() {
1063 return lastModifiedTime;
1064 }
1065
1066 private final boolean isDirectory;
1067
1068 private final boolean isSymbolicLink;
1069
1070 private final boolean isRegularFile;
1071
1072 private final long creationTime;
1073
1074 private final long lastModifiedTime;
1075
1076 private final boolean isExecutable;
1077
1078 private final File file;
1079
1080 private final boolean exists;
1081
1082
1083
1084
1085 protected long length = -1;
1086
1087 final FS fs;
1088
1089 Attributes(FS fs, File file, boolean exists, boolean isDirectory,
1090 boolean isExecutable, boolean isSymbolicLink,
1091 boolean isRegularFile, long creationTime,
1092 long lastModifiedTime, long length) {
1093 this.fs = fs;
1094 this.file = file;
1095 this.exists = exists;
1096 this.isDirectory = isDirectory;
1097 this.isExecutable = isExecutable;
1098 this.isSymbolicLink = isSymbolicLink;
1099 this.isRegularFile = isRegularFile;
1100 this.creationTime = creationTime;
1101 this.lastModifiedTime = lastModifiedTime;
1102 this.length = length;
1103 }
1104
1105
1106
1107
1108
1109
1110
1111
1112 public Attributes(File path, FS fs) {
1113 this(fs, path, false, false, false, false, false, 0L, 0L, 0L);
1114 }
1115
1116
1117
1118
1119 public long getLength() {
1120 if (length == -1)
1121 return length = file.length();
1122 return length;
1123 }
1124
1125
1126
1127
1128 public String getName() {
1129 return file.getName();
1130 }
1131
1132
1133
1134
1135 public File getFile() {
1136 return file;
1137 }
1138
1139 boolean exists() {
1140 return exists;
1141 }
1142 }
1143
1144
1145
1146
1147
1148
1149 public Attributes getAttributes(File path) {
1150 boolean isDirectory = isDirectory(path);
1151 boolean isFile = !isDirectory && path.isFile();
1152 assert path.exists() == isDirectory || isFile;
1153 boolean exists = isDirectory || isFile;
1154 boolean canExecute = exists && !isDirectory && canExecute(path);
1155 boolean isSymlink = false;
1156 long lastModified = exists ? path.lastModified() : 0L;
1157 long createTime = 0L;
1158 return new Attributes(this, path, exists, isDirectory, canExecute,
1159 isSymlink, isFile, createTime, lastModified, -1);
1160 }
1161
1162
1163
1164
1165
1166
1167
1168
1169 public File normalize(File file) {
1170 return file;
1171 }
1172
1173
1174
1175
1176
1177
1178
1179
1180 public String normalize(String name) {
1181 return name;
1182 }
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196 private static class StreamGobbler implements Callable<Void> {
1197 private final BufferedReader reader;
1198
1199 private final BufferedWriter writer;
1200
1201 public StreamGobbler(InputStream stream, OutputStream output) {
1202 this.reader = new BufferedReader(new InputStreamReader(stream));
1203 if (output == null)
1204 this.writer = null;
1205 else
1206 this.writer = new BufferedWriter(new OutputStreamWriter(output));
1207 }
1208
1209 public Void call() throws IOException {
1210 boolean writeFailure = false;
1211
1212 String line = null;
1213 while ((line = reader.readLine()) != null) {
1214
1215
1216 if (!writeFailure && writer != null) {
1217 try {
1218 writer.write(line);
1219 writer.newLine();
1220 writer.flush();
1221 } catch (IOException e) {
1222 writeFailure = true;
1223 }
1224 }
1225 }
1226 return null;
1227 }
1228 }
1229 }