1
2
3
4
5
6
7
8
9
10 package org.eclipse.jgit.util;
11
12 import java.io.IOException;
13 import java.text.MessageFormat;
14
15 import org.eclipse.jgit.annotations.Nullable;
16 import org.eclipse.jgit.errors.CommandFailedException;
17 import org.eclipse.jgit.internal.JGitText;
18 import org.eclipse.jgit.transport.CredentialsProvider;
19 import org.eclipse.jgit.transport.RemoteSession;
20 import org.eclipse.jgit.transport.SshSessionFactory;
21 import org.eclipse.jgit.transport.URIish;
22 import org.eclipse.jgit.util.io.MessageWriter;
23 import org.eclipse.jgit.util.io.StreamCopyThread;
24
25
26
27
28
29
30 public class SshSupport {
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54 public static String runSshCommand(URIish sshUri,
55 @Nullable CredentialsProvider provider, FS fs, String command,
56 int timeout) throws IOException, CommandFailedException {
57 RemoteSession session = null;
58 Process process = null;
59 StreamCopyThread errorThread = null;
60 StreamCopyThread outThread = null;
61 CommandFailedException failure = null;
62 @SuppressWarnings("resource")
63 MessageWriter stderr = new MessageWriter();
64 String out;
65 try (MessageWriterter.html#MessageWriter">MessageWriter stdout = new MessageWriter()) {
66 session = SshSessionFactory.getInstance().getSession(sshUri,
67 provider, fs, 1000 * timeout);
68 process = session.exec(command, 0);
69 errorThread = new StreamCopyThread(process.getErrorStream(),
70 stderr.getRawStream());
71 errorThread.start();
72 outThread = new StreamCopyThread(process.getInputStream(),
73 stdout.getRawStream());
74 outThread.start();
75 try {
76
77
78 if (process.waitFor() == 0) {
79 out = stdout.toString();
80 } else {
81 out = null;
82 }
83 } catch (InterruptedException e) {
84 out = null;
85 }
86 } finally {
87 if (errorThread != null) {
88 try {
89 errorThread.halt();
90 } catch (InterruptedException e) {
91
92 } finally {
93 errorThread = null;
94 }
95 }
96 if (outThread != null) {
97 try {
98 outThread.halt();
99 } catch (InterruptedException e) {
100
101 } finally {
102 outThread = null;
103 }
104 }
105 if (process != null) {
106 if (process.exitValue() != 0) {
107 failure = new CommandFailedException(process.exitValue(),
108 MessageFormat.format(
109 JGitText.get().sshCommandFailed, command,
110 stderr.toString()));
111 }
112 process.destroy();
113 }
114 stderr.close();
115 if (session != null) {
116 SshSessionFactory.getInstance().releaseSession(session);
117 }
118 }
119 if (failure != null) {
120 throw failure;
121 }
122 return out;
123 }
124
125 }