summaryrefslogtreecommitdiff
path: root/plugins/github/src/org/jetbrains/plugins/github/util/GithubUtil.java
blob: edd12ab85ab66370958d9c9533657a43fb2b1da7 (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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.plugins.github.util;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.ThrowableConsumer;
import com.intellij.util.ThrowableConvertor;
import com.intellij.util.containers.Convertor;
import git4idea.DialogManager;
import git4idea.GitUtil;
import git4idea.commands.GitCommand;
import git4idea.commands.GitSimpleHandler;
import git4idea.config.GitVcsApplicationSettings;
import git4idea.config.GitVersion;
import git4idea.i18n.GitBundle;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.github.api.GithubApiUtil;
import org.jetbrains.plugins.github.api.GithubFullPath;
import org.jetbrains.plugins.github.api.GithubUserDetailed;
import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException;
import org.jetbrains.plugins.github.exceptions.GithubOperationCanceledException;
import org.jetbrains.plugins.github.exceptions.GithubTwoFactorAuthenticationException;
import org.jetbrains.plugins.github.ui.GithubBasicLoginDialog;
import org.jetbrains.plugins.github.ui.GithubLoginDialog;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;

/**
 * Various utility methods for the GutHub plugin.
 *
 * @author oleg
 * @author Kirill Likhodedov
 * @author Aleksey Pivovarov
 */
public class GithubUtil {

  public static final Logger LOG = Logger.getInstance("github");

  // TODO: Consider sharing of GithubAuthData between actions (as member of GithubSettings)
  public static <T> T runTask(@NotNull Project project,
                              @NotNull GithubAuthDataHolder authHolder,
                              @NotNull ProgressIndicator indicator,
                              @NotNull ThrowableConvertor<GithubAuthData, T, IOException> task) throws IOException {
    GithubAuthData auth = authHolder.getAuthData();
    try {
      return task.convert(auth);
    }
    catch (GithubTwoFactorAuthenticationException e) {
      getTwoFactorAuthData(project, authHolder, indicator, auth);
      return runTask(project, authHolder, indicator, task);
    }
    catch (GithubAuthenticationException e) {
      getValidAuthData(project, authHolder, indicator, auth);
      return runTask(project, authHolder, indicator, task);
    }
  }

  public static void runTask(@NotNull Project project,
                             @NotNull GithubAuthDataHolder authHolder,
                             @NotNull ProgressIndicator indicator,
                             @NotNull ThrowableConsumer<GithubAuthData, IOException> task) throws IOException {
    GithubAuthData auth = authHolder.getAuthData();
    try {
      task.consume(auth);
    }
    catch (GithubTwoFactorAuthenticationException e) {
      getTwoFactorAuthData(project, authHolder, indicator, auth);
      runTask(project, authHolder, indicator, task);
    }
    catch (GithubAuthenticationException e) {
      getValidAuthData(project, authHolder, indicator, auth);
      runTask(project, authHolder, indicator, task);
    }
  }

  public static <T> T runTaskWithBasicAuthForHost(@NotNull Project project,
                                                  @NotNull GithubAuthDataHolder authHolder,
                                                  @NotNull ProgressIndicator indicator,
                                                  @NotNull String host,
                                                  @NotNull ThrowableConvertor<GithubAuthData, T, IOException> task) throws IOException {
    GithubAuthData auth = authHolder.getAuthData();
    try {
      if (auth.getAuthType() != GithubAuthData.AuthType.BASIC) {
        throw new GithubAuthenticationException("Expected basic authentication");
      }
      return task.convert(auth);
    }
    catch (GithubTwoFactorAuthenticationException e) {
      getTwoFactorAuthData(project, authHolder, indicator, auth);
      return runTaskWithBasicAuthForHost(project, authHolder, indicator, host, task);
    }
    catch (GithubAuthenticationException e) {
      getValidBasicAuthDataForHost(project, authHolder, indicator, auth, host);
      return runTaskWithBasicAuthForHost(project, authHolder, indicator, host, task);
    }
  }

  @NotNull
  private static GithubUserDetailed testConnection(@NotNull Project project,
                                                   @NotNull GithubAuthDataHolder authHolder,
                                                   @NotNull ProgressIndicator indicator) throws IOException {
    GithubAuthData auth = authHolder.getAuthData();
    try {
      return GithubApiUtil.getCurrentUserDetailed(auth);
    }
    catch (GithubTwoFactorAuthenticationException e) {
      getTwoFactorAuthData(project, authHolder, indicator, auth);
      return testConnection(project, authHolder, indicator);
    }
  }

  public static void getValidAuthData(@NotNull final Project project,
                                      @NotNull final GithubAuthDataHolder authHolder,
                                      @NotNull final ProgressIndicator indicator,
                                      @NotNull final GithubAuthData oldAuth) throws GithubOperationCanceledException {
    authHolder.runTransaction(oldAuth, new ThrowableComputable<GithubAuthData, GithubOperationCanceledException>() {
      @Override
      @NotNull
      public GithubAuthData compute() throws GithubOperationCanceledException {
        final GithubAuthData[] authData = new GithubAuthData[1];
        final boolean[] ok = new boolean[1];
        ApplicationManager.getApplication().invokeAndWait(new Runnable() {
          @Override
          public void run() {
            final GithubLoginDialog dialog = new GithubLoginDialog(project, oldAuth);
            DialogManager.show(dialog);
            ok[0] = dialog.isOK();

            if (ok[0]) {
              authData[0] = dialog.getAuthData();
              GithubSettings.getInstance().setAuthData(authData[0], dialog.isSavePasswordSelected());
            }
          }
        }, indicator.getModalityState());
        if (!ok[0]) {
          throw new GithubOperationCanceledException("Can't get valid credentials");
        }
        return authData[0];
      }
    });
  }

  public static void getValidBasicAuthDataForHost(@NotNull final Project project,
                                                  @NotNull final GithubAuthDataHolder authHolder,
                                                  @NotNull final ProgressIndicator indicator,
                                                  @NotNull final GithubAuthData oldAuth,
                                                  @NotNull final String host) throws GithubOperationCanceledException {
    authHolder.runTransaction(oldAuth, new ThrowableComputable<GithubAuthData, GithubOperationCanceledException>() {
      @Override
      @NotNull
      public GithubAuthData compute() throws GithubOperationCanceledException {
        final GithubAuthData[] authData = new GithubAuthData[1];
        final boolean[] ok = new boolean[1];
        ApplicationManager.getApplication().invokeAndWait(new Runnable() {
          @Override
          public void run() {
            final GithubLoginDialog dialog = new GithubBasicLoginDialog(project, oldAuth, host);
            DialogManager.show(dialog);
            ok[0] = dialog.isOK();
            if (ok[0]) {
              authData[0] = dialog.getAuthData();

              final GithubSettings settings = GithubSettings.getInstance();
              if (settings.getAuthType() != GithubAuthData.AuthType.TOKEN) {
                GithubSettings.getInstance().setAuthData(authData[0], dialog.isSavePasswordSelected());
              }
            }
          }
        }, indicator.getModalityState());
        if (!ok[0]) {
          throw new GithubOperationCanceledException("Can't get valid credentials");
        }
        return authData[0];
      }
    });
  }

  private static void getTwoFactorAuthData(@NotNull final Project project,
                                           @NotNull final GithubAuthDataHolder authHolder,
                                           @NotNull final ProgressIndicator indicator,
                                           @NotNull final GithubAuthData oldAuth) throws GithubOperationCanceledException {
    authHolder.runTransaction(oldAuth, new ThrowableComputable<GithubAuthData, GithubOperationCanceledException>() {
      @Override
      @NotNull
      public GithubAuthData compute() throws GithubOperationCanceledException {
        if (authHolder.getAuthData().getAuthType() != GithubAuthData.AuthType.BASIC) {
          throw new GithubOperationCanceledException("Two factor authentication can be used only with Login/Password");
        }

        GithubApiUtil.askForTwoFactorCodeSMS(oldAuth);

        final Ref<String> codeRef = new Ref<String>();
        ApplicationManager.getApplication().invokeAndWait(new Runnable() {
          @Override
          public void run() {
            codeRef.set(Messages.showInputDialog(project, "Authentication Code", "Github Two-Factor Authentication", null));
          }
        }, indicator.getModalityState());
        if (codeRef.isNull()) {
          throw new GithubOperationCanceledException("Can't get two factor authentication code");
        }

        GithubSettings settings = GithubSettings.getInstance();
        if (settings.getAuthType() == GithubAuthData.AuthType.BASIC &&
            StringUtil.equalsIgnoreCase(settings.getLogin(), oldAuth.getBasicAuth().getLogin())) {
          settings.setValidGitAuth(false);
        }

        return oldAuth.copyWithTwoFactorCode(codeRef.get());
      }
    });
  }

  @NotNull
  public static GithubAuthDataHolder getValidAuthDataHolderFromConfig(@NotNull Project project, @NotNull ProgressIndicator indicator)
    throws IOException {
    GithubAuthData auth = GithubAuthData.createFromSettings();
    GithubAuthDataHolder authHolder = new GithubAuthDataHolder(auth);
    try {
      checkAuthData(project, authHolder, indicator);
      return authHolder;
    }
    catch (GithubAuthenticationException e) {
      getValidAuthData(project, authHolder, indicator, auth);
      return authHolder;
    }
  }

  @NotNull
  public static GithubUserDetailed checkAuthData(@NotNull Project project,
                                                 @NotNull GithubAuthDataHolder authHolder,
                                                 @NotNull ProgressIndicator indicator) throws IOException {
    GithubAuthData auth = authHolder.getAuthData();

    if (StringUtil.isEmptyOrSpaces(auth.getHost())) {
      throw new GithubAuthenticationException("Target host not defined");
    }

    switch (auth.getAuthType()) {
      case BASIC:
        GithubAuthData.BasicAuth basicAuth = auth.getBasicAuth();
        assert basicAuth != null;
        if (StringUtil.isEmptyOrSpaces(basicAuth.getLogin()) || StringUtil.isEmptyOrSpaces(basicAuth.getPassword())) {
          throw new GithubAuthenticationException("Empty login or password");
        }
        break;
      case TOKEN:
        GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth();
        assert tokenAuth != null;
        if (StringUtil.isEmptyOrSpaces(tokenAuth.getToken())) {
          throw new GithubAuthenticationException("Empty token");
        }
        break;
      case ANONYMOUS:
        throw new GithubAuthenticationException("Anonymous connection not allowed");
    }

    return testConnection(project, authHolder, indicator);
  }

  public static <T> T computeValueInModal(@NotNull Project project,
                                          @NotNull String caption,
                                          @NotNull final ThrowableConvertor<ProgressIndicator, T, IOException> task) throws IOException {
    final Ref<T> dataRef = new Ref<T>();
    final Ref<Throwable> exceptionRef = new Ref<Throwable>();
    ProgressManager.getInstance().run(new Task.Modal(project, caption, true) {
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          dataRef.set(task.convert(indicator));
        }
        catch (IOException e) {
          exceptionRef.set(e);
        }
        catch (Error e) {
          exceptionRef.set(e);
        }
        catch (RuntimeException e) {
          exceptionRef.set(e);
        }
      }
    });
    if (!exceptionRef.isNull()) {
      Throwable e = exceptionRef.get();
      if (e instanceof IOException) throw ((IOException)e);
      if (e instanceof RuntimeException) throw ((RuntimeException)e);
      if (e instanceof Error) throw ((Error)e);
      throw new RuntimeException(e);
    }
    return dataRef.get();
  }

  public static <T> T computeValueInModal(@NotNull Project project,
                                          @NotNull String caption,
                                          @NotNull final Convertor<ProgressIndicator, T> task) {
    final Ref<T> dataRef = new Ref<T>();
    final Ref<Throwable> exceptionRef = new Ref<Throwable>();
    ProgressManager.getInstance().run(new Task.Modal(project, caption, true) {
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          dataRef.set(task.convert(indicator));
        }
        catch (Error e) {
          exceptionRef.set(e);
        }
        catch (RuntimeException e) {
          exceptionRef.set(e);
        }
      }
    });
    if (!exceptionRef.isNull()) {
      Throwable e = exceptionRef.get();
      if (e instanceof RuntimeException) throw ((RuntimeException)e);
      if (e instanceof Error) throw ((Error)e);
      throw new RuntimeException(e);
    }
    return dataRef.get();
  }

  public static void computeValueInModal(@NotNull Project project,
                                         @NotNull String caption,
                                         @NotNull final Consumer<ProgressIndicator> task) {
    final Ref<Throwable> exceptionRef = new Ref<Throwable>();
    ProgressManager.getInstance().run(new Task.Modal(project, caption, true) {
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          task.consume(indicator);
        }
        catch (Error e) {
          exceptionRef.set(e);
        }
        catch (RuntimeException e) {
          exceptionRef.set(e);
        }
      }
    });
    if (!exceptionRef.isNull()) {
      Throwable e = exceptionRef.get();
      if (e instanceof RuntimeException) throw ((RuntimeException)e);
      if (e instanceof Error) throw ((Error)e);
      throw new RuntimeException(e);
    }
  }

  /*
  * Git utils
  */

  @Nullable
  public static String findGithubRemoteUrl(@NotNull GitRepository repository) {
    Pair<GitRemote, String> remote = findGithubRemote(repository);
    if (remote == null) {
      return null;
    }
    return remote.getSecond();
  }

  @Nullable
  public static Pair<GitRemote, String> findGithubRemote(@NotNull GitRepository repository) {
    Pair<GitRemote, String> githubRemote = null;
    for (GitRemote gitRemote : repository.getRemotes()) {
      for (String remoteUrl : gitRemote.getUrls()) {
        if (GithubUrlUtil.isGithubUrl(remoteUrl)) {
          final String remoteName = gitRemote.getName();
          if ("github".equals(remoteName) || "origin".equals(remoteName)) {
            return Pair.create(gitRemote, remoteUrl);
          }
          if (githubRemote == null) {
            githubRemote = Pair.create(gitRemote, remoteUrl);
          }
          break;
        }
      }
    }
    return githubRemote;
  }

  @Nullable
  public static String findUpstreamRemote(@NotNull GitRepository repository) {
    for (GitRemote gitRemote : repository.getRemotes()) {
      final String remoteName = gitRemote.getName();
      if ("upstream".equals(remoteName)) {
        for (String remoteUrl : gitRemote.getUrls()) {
          if (GithubUrlUtil.isGithubUrl(remoteUrl)) {
            return remoteUrl;
          }
        }
        return gitRemote.getFirstUrl();
      }
    }
    return null;
  }

  @Nullable
  public static GitRemote findGithubRemote(@NotNull GitRepository gitRepository, @NotNull GithubFullPath path) {
    for (GitRemote remote : gitRepository.getRemotes()) {
      for (String url : remote.getUrls()) {
        if (path.equals(GithubUrlUtil.getUserAndRepositoryFromRemoteUrl(url))) {
          return remote;
        }
      }
    }
    return null;
  }

  public static boolean testGitExecutable(final Project project) {
    final GitVcsApplicationSettings settings = GitVcsApplicationSettings.getInstance();
    final String executable = settings.getPathToGit();
    final GitVersion version;
    try {
      version = GitVersion.identifyVersion(executable);
    }
    catch (Exception e) {
      GithubNotifications.showErrorDialog(project, GitBundle.getString("find.git.error.title"), e);
      return false;
    }

    if (!version.isSupported()) {
      GithubNotifications.showWarningDialog(project, GitBundle.message("find.git.unsupported.message", version.toString(), GitVersion.MIN),
                                            GitBundle.getString("find.git.success.title"));
      return false;
    }
    return true;
  }

  public static boolean isRepositoryOnGitHub(@NotNull GitRepository repository) {
    return findGithubRemoteUrl(repository) != null;
  }

  public static void setVisibleEnabled(AnActionEvent e, boolean visible, boolean enabled) {
    e.getPresentation().setVisible(visible);
    e.getPresentation().setEnabled(enabled);
  }

  @NotNull
  public static String getErrorTextFromException(@NotNull Exception e) {
    if (e instanceof UnknownHostException) {
      return "Unknown host: " + e.getMessage();
    }
    return e.getMessage();
  }

  @Nullable
  public static GitRepository getGitRepository(@NotNull Project project, @Nullable VirtualFile file) {
    GitRepositoryManager manager = GitUtil.getRepositoryManager(project);
    List<GitRepository> repositories = manager.getRepositories();
    if (repositories.size() == 0) {
      return null;
    }
    if (repositories.size() == 1) {
      return repositories.get(0);
    }
    if (file != null) {
      GitRepository repository = manager.getRepositoryForFile(file);
      if (repository != null) {
        return repository;
      }
    }
    return manager.getRepositoryForFile(project.getBaseDir());
  }

  public static boolean addGithubRemote(@NotNull Project project,
                                        @NotNull GitRepository repository,
                                        @NotNull String remote,
                                        @NotNull String url) {
    final GitSimpleHandler handler = new GitSimpleHandler(project, repository.getRoot(), GitCommand.REMOTE);
    handler.setSilent(true);

    try {
      handler.addParameters("add", remote, url);
      handler.run();
      if (handler.getExitCode() != 0) {
        GithubNotifications.showError(project, "Can't add remote", "Failed to add GitHub remote: '" + url + "'. " + handler.getStderr());
        return false;
      }
      // catch newly added remote
      repository.update();
      return true;
    }
    catch (VcsException e) {
      GithubNotifications.showError(project, "Can't add remote", e);
      return false;
    }
  }
}