summaryrefslogtreecommitdiffstats
path: root/src/com/ibm/ServerWizard2/utility/GithubRepository.java
blob: 40dfbd3ce3f07f7dbd731b5eef1e9f9daddbaeb1 (plain)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package com.ibm.ServerWizard2.utility;

import java.io.File;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.RebaseResult;
import org.eclipse.jgit.api.ResetCommand.ResetType;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RepositoryCache;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.util.FS;
import org.eclipse.swt.widgets.Shell;

import com.ibm.ServerWizard2.ServerWizard2;
import com.ibm.ServerWizard2.view.PasswordPrompt;

public class GithubRepository implements Comparable<GithubRepository> {
	private String remoteUrl;
	private File rootDirectory;
	private File gitDirectory;
	private boolean needsPassword;
	private boolean passwordValidated = false;
	private Shell shell = null;
	private UsernamePasswordCredentialsProvider credentials;
	
	private boolean cloned;
	private final RefSpec refSpec = new RefSpec("+refs/heads/*:refs/remotes/origin/*");

	public GithubRepository(String remoteUrl, String localDir, boolean needsPassword) {
		this.remoteUrl = remoteUrl;
		this.needsPassword = needsPassword;
		File f = new File(remoteUrl);
		String localPath = localDir + File.separator + f.getName().replace(".git", "");
		rootDirectory = new File(localPath);
		gitDirectory = new File(localPath + File.separator + ".git");
		cloned = false;
		if (RepositoryCache.FileKey.isGitRepository(this.getGitDirectory(), FS.DETECTED)) {
			cloned = true;
		}
	}

	public void setShell(Shell shell) {
		this.shell = shell;
	}
	public File getRootDirectory() {
		return rootDirectory;
	}

	public File getGitDirectory() {
		return gitDirectory;
	}

	public void getPassword() {
		if (!this.needsPassword) {
			credentials = new UsernamePasswordCredentialsProvider("", "");
			return;
		}
		PasswordPrompt dlg = new PasswordPrompt(shell, this.remoteUrl);
		dlg.open();
		credentials = new UsernamePasswordCredentialsProvider("", dlg.passwd);
		passwordValidated = false;
	}

	public String getRemoteUrl() {
		return this.remoteUrl;
	}
	public boolean needsPassword() {
		return this.needsPassword;
	}
	public String needsPasswordStr() {
		if (this.needsPassword) {
			return "true";
		}
		return "false";
	}

	public void checkRemote() throws Exception {
		if (!passwordValidated) {
			this.getPassword();
		}

		Collection<Ref> refs;
		boolean found = false;

		try {
			refs = Git.lsRemoteRepository().setCredentialsProvider(credentials).setHeads(true).setTags(true)
					.setRemote(this.remoteUrl).call();
			if (!refs.isEmpty()) {
				found = true;
				passwordValidated = true;
				for (Ref ref : refs) {
					ServerWizard2.LOGGER.info("Ref: " + ref);
				}
			}
		} catch (Exception e) {
			ServerWizard2.LOGGER.severe(e.getMessage());
			this.betterError(e);
		}
		if (!found) {
			passwordValidated = false;
			throw new Exception("Invalid Remote Repository or bad Password:\n" + this.getRemoteUrl());
		}
	}

	public void cloneRepository() throws Exception {
		if (!passwordValidated) {
			this.getPassword();
		}
		if (isCloned()) {
			return;
		}
		ServerWizard2.LOGGER.info("Cloning " + this.remoteUrl + " into " + this.getRootDirectory().getAbsolutePath());
		cloned = false;
		try {
			//TODO: determine MacOS hang issue with the progress monitor
			//ProgressMonitor pim = new ProgressMonitor(null, "Cloning...", "", 0, 1);
			//GitProgressMonitor gpim = new GitProgressMonitor(pim);
			Git result = Git.cloneRepository()
					.setCredentialsProvider(credentials)
					.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out)))
					.setURI(this.getRemoteUrl()).setDirectory(this.getRootDirectory()).call();

			cloned = true;
			result.close();
		} catch (Exception e1) {
			passwordValidated = false;
			this.betterError(e1);
		}
	}

	public String fetch(boolean reset) throws Exception {
		if (!passwordValidated) {
			this.getPassword();
		}

		ServerWizard2.LOGGER.info("Fetching " + this.rootDirectory.getAbsolutePath());
		String rstr = "";
		try {
			Git result = Git.open(this.rootDirectory);
			FetchResult fetch = result.fetch()
					.setRemote(this.getRemoteUrl())
					.setCredentialsProvider(credentials)
					.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out)))
					.setRefSpecs(refSpec)
					.call();

			ServerWizard2.LOGGER.info(fetch.getMessages());
			if (reset) {
				ServerWizard2.LOGGER.info("Resetting to head: " + this.getRemoteUrl());
				result.reset().setMode(ResetType.HARD).setRef("refs/remotes/origin/master").call();
				rstr = "Reset Complete";
			}
			ServerWizard2.LOGGER.info("Rebase: " + this.getRemoteUrl());
			RebaseResult r = result.rebase().setUpstream("refs/remotes/origin/master").call();
			rstr = r.getStatus().toString();
			ServerWizard2.LOGGER.info(rstr);
			result.close();
		} catch (Exception e1) {
			passwordValidated = false;
			this.betterError(e1);
		}
		return rstr;
	}

	public org.eclipse.jgit.api.Status status() {
		org.eclipse.jgit.api.Status status = null;
		try {
			Git result = Git.open(this.getRootDirectory());
			status = result.status()
					.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out)))
					.call();

			result.close();
		} catch (Exception e1) {
			ServerWizard2.LOGGER.severe(e1.getMessage());
			status = null;
		}
		return status;
	}
	
	// The chained exceptions from jgit don't explain error
	// Need to dive down to root cause and make better error message.
	public void betterError(Exception e) throws Exception {
		HashMap<String,String> errorLookup = new HashMap<String,String>();
		errorLookup.put("java.net.UnknownHostException", "Unable to connect to location:");
		errorLookup.put("org.eclipse.jgit.errors.NoRemoteRepositoryException", "Remote Repository not found:");
		errorLookup.put("org.eclipse.jgit.errors.TransportException", "Invalid Remote Repository or Incorrect Password: ");
		ServerWizard2.LOGGER.severe(e.getCause().toString());
		Throwable t = getCause(e);
		ServerWizard2.LOGGER.severe(t.toString());
		String errorMsg = t.getMessage();
		if (errorLookup.containsKey(t.getClass().getName())) {
			errorMsg = errorLookup.get(t.getClass().getName()) + "\n" + t.getMessage();
		}
		throw new Exception(errorMsg);
	}

	public boolean isCloned() {
		return cloned;
	}

	public void clear() {
		// make sure stored password is destroyed
		credentials.clear();
	}

	public String toString() {
		return this.remoteUrl + "; " + this.getGitDirectory().getAbsolutePath() + "; " + this.needsPasswordStr();
	}

	@Override
	public int compareTo(GithubRepository o) {
		return this.getRemoteUrl().compareTo(o.getRemoteUrl());
	}

	public boolean equals(Object o) {
		if (o == null)
			return false;
		if (o == this)
			return true;

		if (o instanceof String) {
			String s = (String) o;
			if (this.getRemoteUrl().equals(s)) {
				return true;
			}
			return false;
		} else if (o instanceof GithubRepository) {
			GithubRepository p = (GithubRepository) o;
			return this.compareTo(p) == 0 ? true : false;
		}
		return false;
	}
	Throwable getCause(Throwable e) {
	    Throwable cause = null; 
	    Throwable result = e;

	    while(null != (cause = result.getCause())  && (result != cause) ) {
	        result = cause;
	    }
	    return result;
	}
}
OpenPOWER on IntegriCloud