Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: b73756d497afdcb1facb856647a02a111ba96fe9 (plain) (blame)
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*******************************************************************************
 *  Copyright (c) 2011 GitHub Inc.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *    Kevin Sawicki (GitHub Inc.) - initial API and implementation
 *******************************************************************************/
package org.eclipse.mylyn.internal.github.core.gist;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.egit.github.core.Comment;
import org.eclipse.egit.github.core.Gist;
import org.eclipse.egit.github.core.GistFile;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.GistService;
import org.eclipse.mylyn.commons.net.AuthenticationCredentials;
import org.eclipse.mylyn.commons.net.AuthenticationType;
import org.eclipse.mylyn.internal.github.core.GitHub;
import org.eclipse.mylyn.internal.github.core.GitHubTaskDataHandler;
import org.eclipse.mylyn.tasks.core.IRepositoryPerson;
import org.eclipse.mylyn.tasks.core.ITaskMapping;
import org.eclipse.mylyn.tasks.core.RepositoryResponse;
import org.eclipse.mylyn.tasks.core.RepositoryResponse.ResponseKind;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.TaskAttachmentMapper;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper;
import org.eclipse.mylyn.tasks.core.data.TaskData;

/**
 * Gist task data handler class.
 */
public class GistTaskDataHandler extends GitHubTaskDataHandler {

	/**
	 * SUMMARY_LENGTH
	 */
	public static final int SUMMARY_LENGTH = 80;

	/**
	 * Fill task data with comments
	 *
	 * @param repository
	 * @param data
	 * @param comments
	 * @return specified task data
	 */
	public TaskData fillComments(TaskRepository repository, TaskData data,
			List<Comment> comments) {
		addComments(data.getRoot(), comments, repository);
		return data;
	}

	/**
	 * Get gist url
	 *
	 * @param repositoryUrl
	 * @param gist
	 * @return url
	 */
	public String getGistUrl(String repositoryUrl, Gist gist) {
		return repositoryUrl + '/' + gist.getId();
	}

	/**
	 * Fill task data with data from gist
	 *
	 * @param repository
	 * @param data
	 * @param gist
	 * @return specified task data
	 */
	public TaskData fillTaskData(TaskRepository repository, TaskData data,
			Gist gist) {
		boolean isOwner = isOwner(repository, gist.getOwner());
		TaskAttributeMapper mapper = data.getAttributeMapper();

		TaskAttribute key = GistAttribute.KEY.getMetadata().create(data);
		mapper.setValue(key, gist.getId());

		TaskAttribute description = GistAttribute.DESCRIPTION.getMetadata()
				.create(data);
		description.getMetaData().setReadOnly(!isOwner);
		String gistDescription = gist.getDescription();
		if (gistDescription != null)
			mapper.setValue(description, gistDescription);

		TaskAttribute created = GistAttribute.CREATED.getMetadata()
				.create(data);
		mapper.setDateValue(created, gist.getCreatedAt());

		TaskAttribute updated = GistAttribute.UPDATED.getMetadata()
				.create(data);
		mapper.setDateValue(updated, gist.getUpdatedAt());

		TaskAttribute url = GistAttribute.URL.getMetadata().create(data);
		url.setValue(gist.getHtmlUrl());

		TaskAttribute cloneUrl = GistAttribute.CLONE_URL.getMetadata().create(
				data);
		if (isOwner)
			cloneUrl.setValue(gist.getGitPushUrl());
		else
			cloneUrl.setValue(gist.getGitPullUrl());

		IRepositoryPerson reporterPerson = null;
		User owner = gist.getOwner();
		if (owner != null) {
			TaskAttribute reporter = GistAttribute.AUTHOR.getMetadata().create(
					data);
			reporterPerson = createPerson(owner, repository);
			mapper.setRepositoryPerson(reporter, reporterPerson);

			TaskAttribute gravatar = GistAttribute.AUTHOR_GRAVATAR
					.getMetadata().create(data);
			mapper.setValue(gravatar, owner.getAvatarUrl());
		}

		Map<String, GistFile> files = gist.getFiles();
		int fileCount = 0;
		long sizeCount = 0;
		if (files != null && !files.isEmpty()) {
			int count = 1;
			for (GistFile file : files.values()) {
				fileCount++;
				sizeCount += file.getSize();
				TaskAttachmentMapper attachmentMapper = new TaskAttachmentMapper();
				attachmentMapper.setFileName(file.getFilename());
				attachmentMapper.setReplaceExisting(true);
				attachmentMapper.setLength((long) file.getSize());
				attachmentMapper.setPatch(false);
				attachmentMapper.setAuthor(reporterPerson);
				attachmentMapper.setAttachmentId(file.getFilename());
				TaskAttribute attribute = data.getRoot().createAttribute(
						TaskAttribute.PREFIX_ATTACHMENT + count);
				attachmentMapper.applyTo(attribute);

				GistAttribute.RAW_FILE_URL.getMetadata().create(attribute)
						.setValue(file.getRawUrl());

				count++;
			}
		}

		GistAttribute.COMMENT_NEW.getMetadata().create(data);

		TaskAttribute summary = GistAttribute.SUMMARY.getMetadata()
				.create(data);
		mapper.setValue(summary,
				generateSummary(fileCount, sizeCount, gist.getDescription()));

		return data;
	}

	private String generateSummary(int files, long size, String description) {
		StringBuilder summaryText = new StringBuilder();
		if (description != null && description.length() > 0) {
			description = description.trim();
			int firstLine = description.indexOf('\n');
			if (firstLine != -1)
				description = description.substring(0, firstLine).trim();
			if (description.length() > SUMMARY_LENGTH) {
				// Break on last whitespace if maximum length is in the middle
				// of a word
				if (!Character.isWhitespace(description.charAt(SUMMARY_LENGTH))
						&& !Character.isWhitespace(description
								.charAt(SUMMARY_LENGTH - 1))) {
					int lastWhitespace = description.lastIndexOf(' ');
					if (lastWhitespace > 0)
						description = description.substring(0, lastWhitespace);
					else
						description = description.substring(0, SUMMARY_LENGTH);
				} else
					description = description.substring(0, SUMMARY_LENGTH);
				description = description.trim();
			}
			if (description.length() > 0)
				summaryText.append(description).append(' ');
		}
		if (files != 1)
			summaryText.append(MessageFormat.format(
					Messages.GistTaskDataHandler_FilesMultiple, files));
		else
			summaryText.append(Messages.GistTaskDataHandler_FilesSingle);
		summaryText.append(',').append(' ').append(formatSize(size));
		return summaryText.toString();
	}

	private String formatSize(long size) {
		if (size == 1)
			return Messages.GistTaskDataHandler_SizeByte;
		else if (size < 1024)
			return new DecimalFormat(Messages.GistTaskDataHandler_SizeBytes)
					.format(size);
		else if (size >= 1024 && size <= 1048575)
			return new DecimalFormat(Messages.GistTaskDataHandler_SizeKilobytes)
					.format(size / 1024.0);
		else if (size >= 1048576 && size <= 1073741823)
			return new DecimalFormat(Messages.GistTaskDataHandler_SizeMegabytes)
					.format(size / 1048576.0);
		else
			return new DecimalFormat(Messages.GistTaskDataHandler_SizeGigabytes)
					.format(size / 1073741824.0);
	}

	/**
	 * @see org.eclipse.mylyn.tasks.core.data.AbstractTaskDataHandler#postTaskData(org.eclipse.mylyn.tasks.core.TaskRepository,
	 *      org.eclipse.mylyn.tasks.core.data.TaskData, java.util.Set,
	 *      org.eclipse.core.runtime.IProgressMonitor)
	 */
	public RepositoryResponse postTaskData(TaskRepository repository,
			TaskData taskData, Set<TaskAttribute> oldAttributes,
			IProgressMonitor monitor) throws CoreException {
		RepositoryResponse response = null;

		Gist gist = new Gist();
		GitHubClient client = GistConnector.createClient(repository);
		AuthenticationCredentials credentials = repository
				.getCredentials(AuthenticationType.REPOSITORY);
		if (credentials != null) {
			client.setCredentials(credentials.getUserName(),
					credentials.getPassword());
			gist.setOwner(new User().setLogin(credentials.getUserName()));
		}

		GistService service = new GistService(client);
		TaskAttribute root = taskData.getRoot();
		gist.setId(taskData.getTaskId());
		gist.setDescription(root.getAttribute(
				GistAttribute.DESCRIPTION.getMetadata().getId()).getValue());

		if (taskData.isNew()) {
			try {
				gist = service.createGist(gist);
			} catch (IOException e) {
				throw new CoreException(GitHub.createWrappedStatus(e));
			}
			response = new RepositoryResponse(ResponseKind.TASK_CREATED,
					gist.getId());
		} else {
			try {
				String newComment = root.getAttribute(
						GistAttribute.COMMENT_NEW.getMetadata().getId())
						.getValue();
				if (newComment.length() > 0)
					service.createComment(taskData.getTaskId(), newComment);
				String author = GistAttribute.AUTHOR.getMetadata().getValue(
						taskData);
				if (isOwner(repository, author))
					service.updateGist(gist);
			} catch (IOException e) {
				throw new CoreException(GitHub.createWrappedStatus(e));
			}
			response = new RepositoryResponse(ResponseKind.TASK_UPDATED,
					taskData.getTaskId());
		}
		return response;
	}

	/**
	 * @see org.eclipse.mylyn.tasks.core.data.AbstractTaskDataHandler#initializeTaskData(org.eclipse.mylyn.tasks.core.TaskRepository,
	 *      org.eclipse.mylyn.tasks.core.data.TaskData,
	 *      org.eclipse.mylyn.tasks.core.ITaskMapping,
	 *      org.eclipse.core.runtime.IProgressMonitor)
	 */
	public boolean initializeTaskData(TaskRepository repository, TaskData data,
			ITaskMapping initializationData, IProgressMonitor monitor)
			throws CoreException {
		TaskAttributeMapper mapper = data.getAttributeMapper();

		TaskAttribute summary = GistAttribute.SUMMARY.getMetadata()
				.create(data);
		mapper.setValue(summary, Messages.GistTaskDataHandler_SummaryNewGist);
		GistAttribute.DESCRIPTION.getMetadata().create(data);

		return true;
	}

	/**
	 * Is the given Gist author the same user as configured via the task
	 * repository's credentials?
	 *
	 * @param repository
	 * @param author
	 * @return true if owner, false otherwise
	 */
	protected boolean isOwner(TaskRepository repository, User author) {
		if (author == null)
			return false;
		return isOwner(repository, author.getLogin());
	}

	/**
	 * Is the given Gist author the same user as configured via the task
	 * repository's credentials?
	 *
	 * @param repository
	 * @param author
	 * @return true if owner, false otherwise
	 */
	protected boolean isOwner(TaskRepository repository, String author) {
		AuthenticationCredentials creds = repository
				.getCredentials(AuthenticationType.REPOSITORY);
		if (creds == null)
			return false;
		return author != null && author.length() > 0
				&& author.equals(creds.getUserName());
	}
}

Back to the top