Exemplo n.º 1
0
        public GitHubRequest <GistModel> CreateGist(GistCreateModel gist)
        {
            //Great... The RestSharp serializer can't handle this object...
            //Dictionary<string, obj> confuses it and converts it into {"key": "ok", "value": "dokie"}
            //instead of {"ok": "dokie"}
            var obj = new Dictionary <string, object>();

            obj.Add("description", gist.Description);
            obj.Add("public", gist.Public);

            var files = new Dictionary <string, object>();

            obj.Add("files", files);

            if (gist.Files != null)
            {
                foreach (var f in gist.Files.Keys)
                {
                    var content = new Dictionary <string, object>();
                    files.Add(f, content);
                    content.Add("content", gist.Files[f].Content);
                }
            }

            return(GitHubRequest.Post <GistModel>(Client.ApiUri + "/gists", obj));
        }
Exemplo n.º 2
0
        public GitHubRequestAsyncHandle SearchRepositoriesAsync(string repo,
                                                                Action<IEnumerable<Repository>> callback,
                                                                Action<GitHubException> onError) {
            Ensure.ArgumentNotNull(repo, "repo");

            var resource = string.Format("/repos/search/{0}", repo.Replace(' ', '+'));
            var request = new GitHubRequest(resource, API.v2, Method.GET);
            return _client.CallApiAsync<RepositorySearchResults>(
                        request,
                        resp => callback(resp.Data.Repositories.Select(
                                    r => new Repository {
                                            Owner = new User {
                                                        Login = r.Owner
                                                    },
                                            Name = r.Name,
                                            Description = r.Description,
                                            Language = r.Language,
                                            NumberOfForks = r.Forks,
                                            NumberOfWatchers = r.Watchers,
                                            Url = r.Url,
                                            CreatedDate = r.CreatedAt,
                                            LastUpdatedDate = r.PushedAt,
                                            IsFork = r.IsFork,
                                            IsPrivate = r.IsPrivate,
                                            OpenIssues = r.OpenIssues,
                                            HomePage = r.HomePage,
                                            Size = r.Size,
                                        })),
                        onError);
        }
Exemplo n.º 3
0
        public void CallApiAsync_ShouldPassRequestParameters_ToRestRequest()
        {
            var expectedKey    = "foo";
            var expectedValue  = "bar";
            var mockFactory    = new Mock <IRestClientFactory>(MockBehavior.Strict);
            var mockRestClient = new Mock <IRestClient>(MockBehavior.Strict);

            mockFactory.Setup <IRestClient>(f => f.CreateRestClient(It.IsAny <string>())).Returns(mockRestClient.Object);
            mockRestClient
            .Setup(c => c.ExecuteAsync <object>(
                       It.Is <IRestRequest>(r => r.Parameters.Where(p => (p.Name == expectedKey) &&
                                                                    ((string)p.Value == expectedValue))
                                            .Count() == 1),
                       It.IsAny <Action <IRestResponse <object>, RestRequestAsyncHandle> >()))
            .Returns(_testHandle)
            .Callback <IRestRequest,
                       Action <IRestResponse <object>,
                               RestRequestAsyncHandle> >((r, c) => c(new RestResponse <object>(), _testHandle));
            mockRestClient.SetupSet(c => c.Authenticator = It.IsAny <IAuthenticator>());
            var client = CreateClient(mockFactory.Object);

            var request = new GitHubRequest("resource", API.v2,
                                            NGitHub.Web.Method.POST,
                                            new NGitHub.Web.Parameter(expectedKey, expectedValue));

            client.CallApiAsync <object>(request, o => { }, e => { });

            mockRestClient.VerifyAll();
        }
Exemplo n.º 4
0
        public GitHubRequestAsyncHandle CreateIssueAsync(string user,
                                                         string repo,
                                                         string title,
                                                         string body,
                                                         string assignee,
                                                         string mileStone,
                                                         string[] labels,
                                                         Action <Issue> callback,
                                                         Action <GitHubException> onError)
        {
            Requires.ArgumentNotNull("user", user);
            Requires.ArgumentNotNull("repo", repo);
            Requires.ArgumentNotNull("title", title);

            var resource = string.Format("/repos/{0}/{1}/issues", user, repo);
            var request  = new GitHubRequest(resource,
                                             API.v3,
                                             Method.POST,
                                             new IssueDto {
                Title     = title,
                Body      = body,
                Assignee  = assignee,
                Milestone = mileStone,
                Labels    = labels
            });

            return(_client.CallApiAsync <Issue>(request,
                                                r => callback(r.Data),
                                                onError));
        }
Exemplo n.º 5
0
        public GitHubRequestAsyncHandle CreateCommentAsync(string user,
                                                           string repo,
                                                           int issueNumber,
                                                           string comment,
                                                           Action <Comment> callback,
                                                           Action <GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");
            Requires.ArgumentNotNull(comment, "comment");

            var resource = string.Format("/repos/{0}/{1}/issues/{2}/comments",
                                         user,
                                         repo,
                                         issueNumber);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.POST,
                                            new CommentDto {
                Body = comment
            });

            return(_client.CallApiAsync <Comment>(request,
                                                  r => callback(r.Data),
                                                  onError));
        }
Exemplo n.º 6
0
        public Task <GitHubResponse <IEnumerable <IssueComment> > > IssueComments(string repoFullName, int issueNumber, DateTimeOffset?since, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            var request = new GitHubRequest($"repos/{repoFullName}/issues/{issueNumber}/comments", cacheOptions, priority);

            request.AddParameter("since", since);
            return(FetchPaged(request, (IssueComment x) => x.Id));
        }
Exemplo n.º 7
0
        public GitHubRequestAsyncHandle CreateCommentAsync(string user,
                                                           string repo,
                                                           int pullRequestId,
                                                           int commentIdToReplyTo,
                                                           string body,
                                                           Action <CommitComment> callback,
                                                           Action <GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");
            Requires.ArgumentNotNull(body, "body");

            var resource = string.Format("/repos/{0}/{1}/pulls/{2}/comments",
                                         user,
                                         repo,
                                         pullRequestId);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.POST,
                                            new ReplyCommentDto {
                Body      = body,
                InReplyTo = commentIdToReplyTo
            });

            return(_client.CallApiAsync <CommitComment>(request,
                                                        r => callback(r.Data),
                                                        onError));
        }
Exemplo n.º 8
0
        public GitHubRequestAsyncHandle CreateIssueAsync(string user,
                                                         string repo,
                                                         string title,
                                                         string body,
                                                         string assignee,
                                                         string mileStone,
                                                         string[] labels,
                                                         Action<Issue> callback,
                                                         Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull("user", user);
            Requires.ArgumentNotNull("repo", repo);
            Requires.ArgumentNotNull("title", title);

            var resource = string.Format("/repos/{0}/{1}/issues", user, repo);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.POST,
                                            new IssueDto {
                                                Title = title,
                                                Body = body,
                                                Assignee = assignee,
                                                Milestone = mileStone,
                                                Labels = labels
                                            });
            return _client.CallApiAsync<Issue>(request,
                                               r => callback(r.Data),
                                               onError);
        }
        private Task <GitHubResponse <g.Account> > GitHubUser(string accessToken, CancellationToken cancellationToken)
        {
            AccessToken = accessToken;
            var request = new GitHubRequest("user");

            return(_handlerPipeline.Fetch <g.Account>(this, request, cancellationToken));
        }
Exemplo n.º 10
0
        public GitHubRequestAsyncHandle FollowAsync(string user,
                                                    Action callback,
                                                    Action <GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");

            var resource = string.Format("/user/following/{0}", user);
            var request  = new GitHubRequest(resource, API.v3, Method.PUT);

            return(_gitHubClient.CallApiAsync <object>(
                       request,
                       r => {
                Debug.Assert(false, "all responses should be errors");
                callback();
            },
                       ex => {
                if (ex.Response.StatusCode == HttpStatusCode.NoContent)
                {
                    callback();
                    return;
                }

                onError(ex);
            }));
        }
Exemplo n.º 11
0
        public GitHubRequest <GistModel> EditGist(GistEditModel gist)
        {
            var obj = new Dictionary <string, object>();

            obj.Add("description", gist.Description);

            var files = new Dictionary <string, object>();

            obj.Add("files", files);

            if (gist.Files != null)
            {
                foreach (var f in gist.Files.Keys)
                {
                    if (gist.Files[f] == null)
                    {
                        files.Add(f, null);
                    }
                    else
                    {
                        var content = new Dictionary <string, object>();
                        files.Add(f, content);
                        content.Add("content", gist.Files[f].Content);

                        if (gist.Files[f].Filename != null)
                        {
                            content.Add("filename", gist.Files[f].Filename);
                        }
                    }
                }
            }

            return(GitHubRequest.Patch <GistModel>(Uri, obj));
        }
Exemplo n.º 12
0
        public Task <GitHubResponse <IEnumerable <Milestone> > > Milestones(string repoFullName, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            var request = new GitHubRequest($"repos/{repoFullName}/milestones", cacheOptions, priority);

            request.AddParameter("state", "all");
            return(FetchPaged(request, (Milestone x) => x.Id));
        }
Exemplo n.º 13
0
        public static Task RequestModel<TRequest>(this MvxViewModel viewModel, GitHubRequest<TRequest> request, bool forceDataRefresh, Action<GitHubResponse<TRequest>> update) where TRequest : new()
        {
            if (forceDataRefresh)
            {
                request.CheckIfModified = false;
                request.RequestFromCache = false;
            }

            var application = Mvx.Resolve<IApplicationService>();
            var uiThrad = Mvx.Resolve<IUIThreadService>();

			return Task.Run(async () =>
            {
				var result = await application.Client.ExecuteAsync(request).ConfigureAwait(false);
                uiThrad.MarshalOnUIThread(() => update(result));

                if (result.WasCached)
                {
                    request.RequestFromCache = false;

					Task.Run(async () =>
                    {
                        try
                        {
							var r = await application.Client.ExecuteAsync(request).ConfigureAwait(false);
                            uiThrad.MarshalOnUIThread(() => update(r));
                        }
						catch (NotModifiedException)
						{
							System.Diagnostics.Debug.WriteLine("Not modified: " + request.Url);
						}
                    }).FireAndForget();
                }
            });
		}
Exemplo n.º 14
0
        public GitHubRequestAsyncHandle CreateCommentAsync(string user,
                                                           string repo,
                                                           int pullRequestId,
                                                           string commitId,
                                                           string body,
                                                           string path,
                                                           int position,
                                                           Action<CommitComment> callback,
                                                           Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");
            Requires.ArgumentNotNull(body, "body");
            Requires.ArgumentNotNull(path, "path");

            var resource = string.Format("/repos/{0}/{1}/pulls/{2}/comments",
                                         user,
                                         repo,
                                         pullRequestId);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.POST,
                                            new {
                                                commit_id = commitId,
                                                body = body,
                                                path = path,
                                                position = position
                                            });
            return _client.CallApiAsync<CommitComment>(request,
                                                       r => callback(r.Data),
                                                       onError);
        }
Exemplo n.º 15
0
        public GitHubRequestAsyncHandle IsWatchingAsync(string user,
                                                        string repo,
                                                        Action <bool> callback,
                                                        Action <GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");


            var resource = string.Format("/user/watched/{0}/{1}", user, repo);
            var request  = new GitHubRequest(resource, API.v3, Method.GET);

            return(_client.CallApiAsync <object>(
                       request,
                       r => {
                Debug.Assert(false, "all responses should be errors");
                callback(true);
            },
                       e => {
                if (e.Response.StatusCode == HttpStatusCode.NoContent)
                {
                    callback(true);
                    return;
                }

                if (e.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    callback(false);
                    return;
                }

                onError(e);
            }));
        }
Exemplo n.º 16
0
        public Task <GitHubResponse <IEnumerable <Account> > > OrganizationMembers(string orgLogin, string role, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            // defaults: filter=all, role=all
            var request = new GitHubRequest($"orgs/{orgLogin}/members", cacheOptions, priority);

            request.AddParameter("role", role);
            return(FetchPaged(request, (Account x) => x.Id));
        }
Exemplo n.º 17
0
        public Task <GitHubResponse <IEnumerable <IssueEvent> > > Events(string repoFullName, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            var request = new GitHubRequest($"repos/{repoFullName}/issues/events", cacheOptions, priority);

            request.AddParameter("sort", "updated");
            request.AddParameter("direction", "asc");
            return(FetchPaged(request, (IssueEvent x) => x.Id));
        }
Exemplo n.º 18
0
 public GitHubRequestAsyncHandle GetAuthenticatedUserAsync(Action<User> callback,
                                                           Action<GitHubException> onError)
 {
     var request = new GitHubRequest("/user", API.v3, Method.GET);
     return _gitHubClient.CallApiAsync<User>(request,
                                             r => callback(r.Data),
                                             onError);
 }
Exemplo n.º 19
0
 public GitHubRequest <List <RepositoryModel> > GetAll(string affiliation = null, int page = 1, int perPage = 100)
 {
     return(GitHubRequest.Get <List <RepositoryModel> >(Uri + "/repos", new {
         page,
         per_page = perPage,
         affiliation
     }));
 }
Exemplo n.º 20
0
 public static Task SimpleCollectionLoad <T>(this ReactiveList <T> viewModel, GitHubRequest <List <T> > request, bool?forceDataRefresh) where T : new()
 {
     return(viewModel.RequestModel(request, forceDataRefresh, response =>
     {
         viewModel.CreateMore(response, m => { }, viewModel.AddRange);
         viewModel.Reset(response.Data);
     }));
 }
Exemplo n.º 21
0
        private Task <GitHubResponse <IEnumerable <Project> > > Projects(string endpoint, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            var request = new GitHubRequest(endpoint, cacheOptions, priority)
            {
                AcceptHeaderOverride = "application/vnd.github.inertia-preview.iso8601+json",
            };

            return(FetchPaged(request, (Project p) => p.Id));
        }
Exemplo n.º 22
0
        public Task <GitHubResponse <IEnumerable <PullRequestComment> > > PullRequestComments(string repoFullName, DateTimeOffset?since, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            var request = new GitHubRequest($"repos/{repoFullName}/pulls/comments", cacheOptions, priority)
                          .AddParameter("since", since)
                          .AddParameter("sort", "updated")
                          .AddParameter("direction", "asc");

            return(FetchPaged(request, (PullRequestComment x) => x.Id));
        }
Exemplo n.º 23
0
        public Task <GitHubResponse <IEnumerable <PullRequest> > > PullRequests(string repoFullName, string sort, string direction, uint skipPages, uint maxPages, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            var request = new GitHubRequest($"repos/{repoFullName}/pulls", cacheOptions, priority);

            request.AddParameter("state", "all");
            request.AddParameter("sort", sort);
            request.AddParameter("direction", direction);
            return(FetchPaged(request, (PullRequest x) => x.Id, maxPages, skipPages));
        }
Exemplo n.º 24
0
        public GitHubRequestAsyncHandle GetAuthenticatedUserAsync(Action <User> callback,
                                                                  Action <GitHubException> onError)
        {
            var request = new GitHubRequest("/user", API.v3, Method.GET);

            return(_gitHubClient.CallApiAsync <User>(request,
                                                     r => callback(r.Data),
                                                     onError));
        }
Exemplo n.º 25
0
        public Task <GitHubResponse <IEnumerable <Reaction> > > IssueCommentReactions(string repoFullName, long commentId, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            var request = new GitHubRequest($"repos/{repoFullName}/issues/comments/{commentId}/reactions", cacheOptions, priority)
            {
                // Reactions are in beta
                AcceptHeaderOverride = "application/vnd.github.squirrel-girl-preview+json",
            };

            return(FetchPaged(request, (Reaction x) => x.Id));
        }
Exemplo n.º 26
0
        public GitHubRequest <bool> MarkRepoAsRead(string username, string repository, DateTime?lastReadAt = null)
        {
            var data = new Dictionary <string, string>();

            if (lastReadAt != null)
            {
                data.Add("last_read_at", string.Concat(lastReadAt.Value.ToString("s"), "Z"));
            }
            return(GitHubRequest.Put <bool>(Client.ApiUri + "/repos/" + username + "/" + repository + "/notifications", data));
        }
Exemplo n.º 27
0
        public Task <GitHubResponse <IEnumerable <Reaction> > > PullRequestCommentReactions(string repoFullName, long commentId, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            var request = new GitHubRequest($"repos/{repoFullName}/pulls/comments/{commentId}/reactions", cacheOptions, priority)
            {
                // https://developer.github.com/v3/reactions/#list-reactions-for-a-pull-request-review-comment
                AcceptHeaderOverride = "application/vnd.github.squirrel-girl-preview+json"
            };

            return(FetchPaged(request, (Reaction x) => x.Id));
        }
Exemplo n.º 28
0
        public Task <GitHubResponse <Issue> > Issue(string repoFullName, int number, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            var request = new GitHubRequest($"repos/{repoFullName}/issues/{number}", cacheOptions, priority)
            {
                // https://developer.github.com/v3/issues/#reactions-summary
                AcceptHeaderOverride = "application/vnd.github.squirrel-girl-preview+json"
            };

            return(EnqueueRequest <Issue>(request));
        }
Exemplo n.º 29
0
        public Task <GitHubResponse <IEnumerable <ContentsFile> > > ListDirectoryContents(string repoFullName, string directoryPath, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            if (!directoryPath.StartsWith("/", StringComparison.Ordinal))
            {
                directoryPath = "/" + directoryPath;
            }
            var request = new GitHubRequest($"repos/{repoFullName}/contents{directoryPath}", cacheOptions, priority);

            return(FetchPaged(request, (ContentsFile f) => f.Path));
        }
Exemplo n.º 30
0
 public GitHubRequest <List <IssueModel> > GetAll(int page      = 1, int perPage         = 100,
                                                  string filter = null, string state     = null, string labels = null,
                                                  string sort   = null, string direction = null, string since  = null)
 {
     return(GitHubRequest.Get <List <IssueModel> >(Uri, new {
         Filter = filter, State = state, Labels = labels,
         Sort = sort, Direction = direction, Since = since,
         page = page, per_page = perPage
     }));
 }
Exemplo n.º 31
0
        public GitHubRequest <bool> MarkAsRead(DateTime?lastReadAt = null)
        {
            var data = new Dictionary <string, string>();

            if (lastReadAt != null)
            {
                data.Add("last_read_at", string.Concat(lastReadAt.Value.ToString("s"), "Z"));
            }
            return(GitHubRequest.Put <bool>(Uri, data));
        }
Exemplo n.º 32
0
        public Task <GitHubResponse <byte[]> > FileContents(string repoFullName, string filePath, GitHubCacheDetails cacheOptions, RequestPriority priority)
        {
            if (!filePath.StartsWith("/", StringComparison.Ordinal))
            {
                filePath = "/" + filePath;
            }
            var request = new GitHubRequest($"repos/{repoFullName}/contents{filePath}", cacheOptions, priority);

            return(EnqueueRequest <byte[]>(request));
        }
Exemplo n.º 33
0
        public Task <GitHubResponse <IEnumerable <Issue> > > IssueMentions(DateTimeOffset?since, uint maxPages, GitHubCacheDetails cacheOptions = null, RequestPriority priority = RequestPriority.Background)
        {
            var request = new GitHubRequest($"/issues", cacheOptions, priority)
                          .AddParameter("state", "all")
                          .AddParameter("sort", "updated")
                          .AddParameter("direction", "asc")
                          .AddParameter("filter", "mentioned")
                          .AddParameter("since", since);

            return(FetchPaged(request, (Issue x) => x.Id, maxPages));
        }
Exemplo n.º 34
0
 public GitHubRequest <List <CommitModel> > GetAll(string sha = null)
 {
     if (sha == null)
     {
         return(GitHubRequest.Get <List <CommitModel> >(Uri));
     }
     else
     {
         return(GitHubRequest.Get <List <CommitModel> >(Uri, new { sha = sha }));
     }
 }
Exemplo n.º 35
0
        public GitHubRequestAsyncHandle FollowAsync(string user,
                                                    Action callback,
                                                    Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");

            string resource = string.Format("/user/following/{0}", user);
            var request = new GitHubRequest(resource, API.v3, Method.PUT);
            return _gitHubClient.CallApiAsync<object>(request,
                                                      s => callback(),
                                                      onError);
        }
Exemplo n.º 36
0
        public GitHubRequestAsyncHandle GetOrganizationsAsync(string user,
                                                              Action<IEnumerable<User>> callback,
                                                              Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");

            var resource = string.Format("/users/{0}/orgs", user);
            var request = new GitHubRequest(resource, API.v3, Method.GET);
            return _client.CallApiAsync<List<User>>(request,
                                                    r => callback(r.Data),
                                                    onError);
        }
Exemplo n.º 37
0
        public GitHubRequestAsyncHandle GetBranchesAsync(string user,
            string repo,
            Action<IEnumerable<Branch>> callback,
            Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            var resource = string.Format("/repos/{0}/{1}/branches", user, repo);
            var request = new GitHubRequest(resource, API.v3, Method.GET);
            return _client.CallApiAsync<List<Branch>>(request,
                                                      r => callback(r.Data),
                                                      onError);
        }
Exemplo n.º 38
0
        public GitHubRequestAsyncHandle ForkAsync(string user,
            string repo,
            Action<Repository> callback,
            Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            // TODO: Allow for forking into an Org...
            var resource = string.Format("/repos/{0}/{1}/forks", user, repo);
            var request = new GitHubRequest(resource, API.v3, Method.POST);
            return _client.CallApiAsync<Repository>(request,
                                                    r => callback(r.Data),
                                                    onError);
        }
Exemplo n.º 39
0
        public GitHubRequestAsyncHandle GetMembersAsync(string organization,
                                                        int page,
                                                        Action<IEnumerable<User>> callback,
                                                        Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(organization, "organization");

            var resource = string.Format("/orgs/{0}/members", organization);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.GET,
                                            Parameter.Page(page));
            return _client.CallApiAsync<List<User>>(request,
                                                    r => callback(r.Data),
                                                    onError);
        }
Exemplo n.º 40
0
        public GitHubRequestAsyncHandle GetFollowingAsync(string user,
                                                          int page,
                                                          Action<IEnumerable<User>> callback,
                                                          Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");

            string resource = string.Format("/users/{0}/following", user);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.GET,
                                            Parameter.Page(page));
            return _gitHubClient.CallApiAsync<List<User>>(request,
                                                          r => callback(r.Data),
                                                          onError);
        }
Exemplo n.º 41
0
        public GitHubRequestAsyncHandle GetCommitAsync(string user,
            string repo,
            string sha,
            Action<Commit> callback,
            Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");
            Requires.ArgumentNotNull(sha, "sha");

            var resource = string.Format("/repos/{0}/{1}/commits/{2}", user, repo, sha);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.GET);
            return _client.CallApiAsync<Commit>(request,
                                                r => callback(r.Data),
                                                onError);
        }
Exemplo n.º 42
0
        public GitHubRequestAsyncHandle SearchUsersAsync(string query,
                                                         Action<IEnumerable<User>> callback,
                                                         Action<GitHubException> onError) {
            Ensure.ArgumentNotNull(query, "user");

            var resource = string.Format("/user/search/{0}", query.Replace(' ', '+'));
            var request = new GitHubRequest(resource, API.v2, Method.GET);
            return _client.CallApiAsync<UserSearchResults>(
                        request,
                        r => callback(r.Data.Users.Select(u => new User {
                                                            Login = u.Login,
                                                            Name = u.Name,
                                                            PublicRepos = u.PublicRepoCount,
                                                            Location = u.Location,
                                                            GravatarId = u.GravatarId,
                                                            Type = u.Type,
                                                            Followers = u.Followers
                                                          })),
                        onError);
        }
Exemplo n.º 43
0
        public GitHubRequestAsyncHandle FollowAsync(string user,
            Action callback,
            Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");

            var resource = string.Format("/user/following/{0}", user);
            var request = new GitHubRequest(resource, API.v3, Method.PUT);
            return _gitHubClient.CallApiAsync<object>(
                        request,
                        r => {
                            Debug.Assert(false, "all responses should be errors");
                            callback();
                        },
                        ex => {
                            if (ex.Response.StatusCode == HttpStatusCode.NoContent) {
                                callback();
                                return;
                            }

                            onError(ex);
                        });
        }
Exemplo n.º 44
0
        public GitHubRequestAsyncHandle CreateCommentAsync(string user,
                                                           string repo,
                                                           int issueNumber,
                                                           string comment,
                                                           Action<Comment> callback,
                                                           Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");
            Requires.ArgumentNotNull(comment, "comment");

            var resource = string.Format("/repos/{0}/{1}/issues/{2}/comments",
                                         user,
                                         repo,
                                         issueNumber);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.POST,
                                            new CommentDto { Body = comment });

            return _client.CallApiAsync<Comment>(request,
                                                 r => callback(r.Data),
                                                 onError);
        }
Exemplo n.º 45
0
 private GitHubRequestAsyncHandle GetRepositoriesAsyncInternal(
     string resource,
     int page,
     int perPage,
     Action<IEnumerable<Repository>> callback,
     Action<GitHubException> onError)
 {
     var request = new GitHubRequest(resource,
                                     API.v3,
                                     Method.GET,
                                     Parameter.Page(page),
                                     Parameter.PerPage(perPage));
     return _client.CallApiAsync<List<Repository>>(request,
                                                   r => callback(r.Data),
                                                   onError);
 }
Exemplo n.º 46
0
        public GitHubRequestAsyncHandle UnwatchAsync(string user,
            string repo,
            Action callback,
            Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            var resource = string.Format("/user/watched/{0}/{1}", user, repo);
            var request = new GitHubRequest(resource, API.v3, Method.DELETE);
            return _client.CallApiAsync<object>(
                        request,
                        r => {
                            Debug.Assert(false, "all responses should be errors");
                            callback();
                        },
                        ex => {
                            if (ex.Response.StatusCode == HttpStatusCode.NoContent) {
                                callback();
                                return;
                            }

                            onError(ex);
                        });
        }
Exemplo n.º 47
0
        public GitHubRequestAsyncHandle GetForksAsync(string user,
            string repo,
            int page,
            int perPage,
            Action<IEnumerable<Repository>> callback,
            Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            var resource = string.Format("/repos/{0}/{1}/forks", user, repo);
            var request = new GitHubRequest(resource, API.v3, Method.GET);
            return GetRepositoriesAsyncInternal(resource, page, perPage, callback, onError);
        }
Exemplo n.º 48
0
        public GitHubRequestAsyncHandle GetPullRequestAsync(string user,
                                                            string repo,
                                                            int pullRequestId,
                                                            Action<PullRequest> callback,
                                                            Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            string resource = string.Format("/repos/{0}/{1}/pulls/{2}", user, repo, pullRequestId);
            var request = new GitHubRequest(resource, API.v3, Method.GET);

            return _client.CallApiAsync<PullRequest>(request,
                                                     r => callback(r.Data),
                                                     onError);
        }
Exemplo n.º 49
0
        public GitHubRequestAsyncHandle IsPullRequestMergedAsync(string user,
                                                                 string repo,
                                                                 int pullRequestId,
                                                                 Action<bool> callback,
                                                                 Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            var resource = string.Format("/repos/{0}/{1}/pulls/{2}/merge",
                                         user,
                                         repo,
                                         pullRequestId);
            var request = new GitHubRequest(resource, API.v3, Method.GET);

            return _client.CallApiAsync<object>(
                                        request,
                                        r => {
                                            Debug.Assert(false, "all responses should be errors");
                                            callback(true);
                                        },
                                        e => {
                                            if (e.Response.StatusCode == HttpStatusCode.NoContent) {
                                                callback(true);
                                                return;
                                            }

                                            if (e.Response.StatusCode == HttpStatusCode.NotFound) {
                                                callback(false);
                                                return;
                                            }

                                            onError(e);
                                        });
        }
Exemplo n.º 50
0
        public GitHubRequestAsyncHandle GetPullRequestsAsync(string user,
                                                             string repo,
                                                             State state,
                                                             int page,
                                                             Action<IEnumerable<PullRequest>> callback,
                                                             Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            var resource = string.Format("/repos/{0}/{1}/pulls", user, repo);
            var request = new GitHubRequest(resource, API.v3, Method.GET, Parameter.State(state));

            return _client.CallApiAsync<List<PullRequest>>(request,
                                                           r => callback(r.Data),
                                                           onError);
        }
Exemplo n.º 51
0
        public void CallApiAsync_ShouldPassRequestParameters_ToRestRequest()
        {
            var expectedKey = "foo";
            var expectedValue = "bar";
            var mockFactory = new Mock<IRestClientFactory>(MockBehavior.Strict);
            var mockRestClient = new Mock<IRestClient>(MockBehavior.Strict);
            mockFactory.Setup<IRestClient>(f => f.CreateRestClient(It.IsAny<string>())).Returns(mockRestClient.Object);
            mockRestClient
                .Setup(c => c.ExecuteAsync<object>(
                    It.Is<IRestRequest>(r => r.Parameters.Where(p => (p.Name == expectedKey) &&
                                                                    ((string)p.Value == expectedValue))
                                                        .Count() == 1),
                    It.IsAny<Action<RestResponse<object>, RestRequestAsyncHandle>>()))
                .Returns(_testHandle)
                .Callback<IRestRequest,
                          Action<RestResponse<object>,
                                 RestRequestAsyncHandle>>((r, c) => c(new RestResponse<object>(), _testHandle));
            mockRestClient.SetupSet(c => c.Authenticator = It.IsAny<IAuthenticator>());
            var client = CreateClient(mockFactory.Object);

            var request = new GitHubRequest("resource", API.v2,
                                            NGitHub.Web.Method.POST,
                                            new NGitHub.Web.Parameter(expectedKey, expectedValue));
            client.CallApiAsync<object>(request, o => { }, e => { });

            mockRestClient.VerifyAll();
        }
Exemplo n.º 52
0
        public GitHubRequestAsyncHandle CreateCommentAsync(string user,
                                                           string repo,
                                                           int pullRequestId,
                                                           int commentIdToReplyTo,
                                                           string body,
                                                           Action<CommitComment> callback,
                                                           Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");
            Requires.ArgumentNotNull(body, "body");

            string resource = string.Format("/repos/{0}/{1}/pulls/{2}/comments",
                                            user,
                                            repo,
                                            pullRequestId);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.POST,
                                            new ReplyCommentDto
                                                {
                                                    Body = body,
                                                    InReplyTo = commentIdToReplyTo
                                                });
            return _client.CallApiAsync<CommitComment>(request,
                                                       r => callback(r.Data),
                                                       onError);
        }
Exemplo n.º 53
0
        public GitHubRequestAsyncHandle GetIssuesAsync(string user,
                                                       string repo,
                                                       State state,
                                                       int page,
                                                       Action<IEnumerable<Issue>> callback,
                                                       Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            var resource = string.Format("/repos/{0}/{1}/issues", user, repo);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.GET,
                                            Parameter.State(state),
                                            Parameter.Page(page));

            // We can't just deserialize every response as a List<Issue> because
            // repos that do not support issues will return:
            //  { "message": "Issues are disabled for this repo" }
            //
            return _client.CallApiAsync(
                        request,
                        r => {
                            List<Issue> issues = null;
                            try {
                                issues = JsonConvert.DeserializeObject<List<Issue>>(r.Content);
                            }
                            catch {
                                onError(new GitHubException(r, ErrorType.Unknown));
                                return;
                            }

                            callback(issues);
                        },
                        e => {
                            if (e.Response.StatusCode == HttpStatusCode.Gone) {
                                // This is the code that is returned when issues are disabled.
                                callback(new Issue[] { });
                                return;
                            }

                            onError(e);
                        });
        }
Exemplo n.º 54
0
 public GitHubRequestAsyncHandle UnfollowAsync(string user,
                                               Action callback,
                                               Action<GitHubException> onError)
 {
     string resource = string.Format("/user/unfollowing/{0}", user);
     var request = new GitHubRequest(resource, API.v3, Method.DELETE);
     return _gitHubClient.CallApiAsync<object>(request,
                                               s => callback(),
                                               onError);
 }
Exemplo n.º 55
0
        public GitHubRequestAsyncHandle GetUserAsync(string user,
                                                     Action<User> callback,
                                                     Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");

            string resource = string.Format("/users/{0}", user);
            var request = new GitHubRequest(resource, API.v3, Method.GET);
            return _gitHubClient.CallApiAsync<User>(request,
                                                    r => callback(r.Data),
                                                    onError);
        }
Exemplo n.º 56
0
        public GitHubRequestAsyncHandle GetCommentsAsync(string user,
                                                         string repo,
                                                         int issueNumber,
                                                         int page,
                                                         Action<IEnumerable<Comment>> callback,
                                                         Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            var resource = string.Format("/repos/{0}/{1}/issues/{2}/comments",
                                         user,
                                         repo,
                                         issueNumber);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.GET,
                                            Parameter.Page(page));
            return _client.CallApiAsync<List<Comment>>(request,
                                                       r => callback(r.Data),
                                                       onError);
        }
Exemplo n.º 57
0
        public GitHubRequestAsyncHandle GetCommitsAsync(string user,
            string repo,
            string branch,
            string lastSha,
            Action<IEnumerable<Commit>> callback,
            Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");
            Requires.ArgumentNotNull(branch, "branch");

            var resource = string.Format("/repos/{0}/{1}/commits", user, repo);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.GET,
                                            new Parameter("last_sha", lastSha ?? string.Empty),
                                            new Parameter("top", branch));

            // We can't just deserialize every response as a List<Commit> because
            // repos that has no commits will return:
            //  { "message": "The repository is empty." }
            //
            return _client.CallApiAsync(
                        request,
                        r => {
                            List<Commit> issues = null;
                            try {
                                issues = JsonConvert.DeserializeObject<List<Commit>>(r.Content);
                            }
                            catch {
                                onError(new GitHubException(r, ErrorType.Unknown));
                                return;
                            }

                            callback(issues);
                        },
                        e => {
                            if (e.Response.StatusCode == HttpStatusCode.Conflict) {
                                // This is the code that is returned when a repo is empty.
                                callback(new Commit[] { });
                                return;
                            }

                            onError(e);
                        });
        }
Exemplo n.º 58
0
        public GitHubRequestAsyncHandle GetFilesAsync(string user,
                                                      string repo,
                                                      int pullRequestId,
                                                      int page,
                                                      Action<IEnumerable<FileChanges>> callback,
                                                      Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            var resource = string.Format("/repos/{0}/{1}/pulls/{2}/files",
                                         user,
                                         repo,
                                         pullRequestId);
            var request = new GitHubRequest(resource, API.v3, Method.GET, Parameter.Page(page));

            return _client.CallApiAsync<List<FileChanges>>(request,
                                                           r => callback(r.Data),
                                                           onError);
        }
Exemplo n.º 59
0
        public void CallApiAsync_ShouldExecuteRestRequestWithGivenRequestMethod()
        {
            var expectedMethod = NGitHub.Web.Method.OPTIONS;
            var request = new GitHubRequest("foo/bar", API.v3, expectedMethod);
            var mockRestClient = new Mock<IRestClient>(MockBehavior.Strict);
            var mockFactory = new Mock<IRestClientFactory>(MockBehavior.Strict);
            mockFactory.Setup<IRestClient>(f => f.CreateRestClient(Constants.ApiV3Url))
                       .Returns(mockRestClient.Object);
            mockRestClient.Setup(c => c.ExecuteAsync<object>(
                It.Is<IRestRequest>(r => r.Method == expectedMethod.ToRestSharpMethod()),
                It.IsAny<Action<RestResponse<object>, RestRequestAsyncHandle>>()))
                .Returns(_testHandle);
            mockRestClient.SetupSet(c => c.Authenticator = It.IsAny<IAuthenticator>());
            var githubClient = CreateClient(mockFactory.Object);

            githubClient.CallApiAsync<object>(request, o => { }, e => { });

            mockRestClient.VerifyAll();
        }
Exemplo n.º 60
0
        public void CallApiAsync_ShouldExecuteRestRequestWithGivenRequestResource()
        {
            string expectedResource = "foo/bar";
            var request = new GitHubRequest(expectedResource, API.v3, Method.OPTIONS);
            var mockRestClient = new Mock<IRestClient>(MockBehavior.Strict);
            var mockFactory = new Mock<IRestClientFactory>(MockBehavior.Strict);
            mockFactory.Setup(f => f.CreateRestClient(Constants.ApiV3Url))
                .Returns(mockRestClient.Object);
            mockRestClient.Setup(c => c.ExecuteAsync(
                It.Is<IRestRequest>(r => r.Resource == expectedResource),
                It.IsAny<Action<IRestResponse<object>, RestRequestAsyncHandle>>()))
                .Returns(_testHandle);
            mockRestClient.SetupSet(c => c.Authenticator = It.IsAny<IAuthenticator>());
            GitHubClient githubClient = CreateClient(mockFactory.Object);

            githubClient.CallApiAsync<object>(request, o => { }, e => { });

            mockRestClient.VerifyAll();
        }