0
0
mirror of https://github.com/thegeeklab/github-releases-notifier.git synced 2024-11-13 21:50:39 +00:00

Update github.com/shurcooL/githubql dependency

This commit is contained in:
Matthias Loibl 2017-08-08 14:12:45 +02:00
parent 8e6851623c
commit ec6fc43ec7
No known key found for this signature in database
GPG Key ID: B1C7DF661ABB2C1A
15 changed files with 35687 additions and 690 deletions

View File

@ -10,4 +10,4 @@
// For now, see README for more details.
package githubql // import "github.com/shurcooL/githubql"
//go:generate go run internal/gen/gen.go
//go:generate go run gen.go

View File

@ -1,53 +1,5 @@
package githubql
// ProjectState represents state of the project; either 'open' or 'closed'.
type ProjectState string
// State of the project; either 'open' or 'closed'.
const (
ProjectStateOpen ProjectState = "OPEN" // The project is open.
ProjectStateClosed ProjectState = "CLOSED" // The project is closed.
)
// ProjectOrderField represents properties by which project connections can be ordered.
type ProjectOrderField string
// Properties by which project connections can be ordered.
const (
ProjectOrderFieldCreatedAt ProjectOrderField = "CREATED_AT" // Order projects by creation time.
ProjectOrderFieldUpdatedAt ProjectOrderField = "UPDATED_AT" // Order projects by update time.
ProjectOrderFieldName ProjectOrderField = "NAME" // Order projects by name.
)
// OrderDirection represents possible directions in which to order a list of items when provided an `orderBy` argument.
type OrderDirection string
// Possible directions in which to order a list of items when provided an `orderBy` argument.
const (
OrderDirectionAsc OrderDirection = "ASC" // Specifies an ascending order for a given `orderBy` argument.
OrderDirectionDesc OrderDirection = "DESC" // Specifies a descending order for a given `orderBy` argument.
)
// ProjectCardState represents various content states of a ProjectCard.
type ProjectCardState string
// Various content states of a ProjectCard.
const (
ProjectCardStateContentOnly ProjectCardState = "CONTENT_ONLY" // The card has content only.
ProjectCardStateNoteOnly ProjectCardState = "NOTE_ONLY" // The card has a note only.
ProjectCardStateRedacted ProjectCardState = "REDACTED" // The card is redacted.
)
// SubscriptionState represents the possible states of a subscription.
type SubscriptionState string
// The possible states of a subscription.
const (
SubscriptionStateUnsubscribed SubscriptionState = "UNSUBSCRIBED" // The User is only notified when particpating or @mentioned.
SubscriptionStateSubscribed SubscriptionState = "SUBSCRIBED" // The User is notified of all conversations.
SubscriptionStateIgnored SubscriptionState = "IGNORED" // The User is never notified.
)
// CommentAuthorAssociation represents a comment author association with repository.
type CommentAuthorAssociation string
@ -73,25 +25,50 @@ const (
CommentCannotUpdateReasonVerifiedEmailRequired CommentCannotUpdateReason = "VERIFIED_EMAIL_REQUIRED" // At least one email address must be verified to update this comment.
)
// ReactionContent represents emojis that can be attached to Issues, Pull Requests and Comments.
type ReactionContent string
// DefaultRepositoryPermissionField represents the possible default permissions for organization-owned repositories.
type DefaultRepositoryPermissionField string
// Emojis that can be attached to Issues, Pull Requests and Comments.
// The possible default permissions for organization-owned repositories.
const (
ReactionContentThumbsUp ReactionContent = "THUMBS_UP" // Represents the 👍 emoji.
ReactionContentThumbsDown ReactionContent = "THUMBS_DOWN" // Represents the 👎 emoji.
ReactionContentLaugh ReactionContent = "LAUGH" // Represents the 😄 emoji.
ReactionContentHooray ReactionContent = "HOORAY" // Represents the 🎉 emoji.
ReactionContentConfused ReactionContent = "CONFUSED" // Represents the 😕 emoji.
ReactionContentHeart ReactionContent = "HEART" // Represents the ❤️ emoji.
DefaultRepositoryPermissionFieldRead DefaultRepositoryPermissionField = "READ" // Members have read access to org repos by default.
DefaultRepositoryPermissionFieldWrite DefaultRepositoryPermissionField = "WRITE" // Members have read and write access to org repos by default.
DefaultRepositoryPermissionFieldAdmin DefaultRepositoryPermissionField = "ADMIN" // Members have read, write, and admin access to org repos by default.
)
// ReactionOrderField represents a list of fields that reactions can be ordered by.
type ReactionOrderField string
// DeploymentState represents the possible states in which a deployment can be.
type DeploymentState string
// A list of fields that reactions can be ordered by.
// The possible states in which a deployment can be.
const (
ReactionOrderFieldCreatedAt ReactionOrderField = "CREATED_AT" // Allows ordering a list of reactions by when they were created.
DeploymentStateAbandoned DeploymentState = "ABANDONED" // The pending deployment was not updated after 30 minutes.
DeploymentStateActive DeploymentState = "ACTIVE" // The deployment is currently active.
DeploymentStateDestroyed DeploymentState = "DESTROYED" // An inactive transient deployment.
DeploymentStateError DeploymentState = "ERROR" // The deployment experienced an error.
DeploymentStateFailure DeploymentState = "FAILURE" // The deployment has failed.
DeploymentStateInactive DeploymentState = "INACTIVE" // The deployment is inactive.
DeploymentStatePending DeploymentState = "PENDING" // The deployment is pending.
)
// DeploymentStatusState represents the possible states for a deployment status.
type DeploymentStatusState string
// The possible states for a deployment status.
const (
DeploymentStatusStatePending DeploymentStatusState = "PENDING" // The deployment is pending.
DeploymentStatusStateSuccess DeploymentStatusState = "SUCCESS" // The deployment was successful.
DeploymentStatusStateFailure DeploymentStatusState = "FAILURE" // The deployment has failed.
DeploymentStatusStateInactive DeploymentStatusState = "INACTIVE" // The deployment is inactive.
DeploymentStatusStateError DeploymentStatusState = "ERROR" // The deployment experienced an error.
)
// GistPrivacy represents the privacy of a Gist.
type GistPrivacy string
// The privacy of a Gist.
const (
GistPrivacyPublic GistPrivacy = "PUBLIC" // Public.
GistPrivacySecret GistPrivacy = "SECRET" // Secret.
GistPrivacyAll GistPrivacy = "ALL" // Gists that are public and secret.
)
// GitSignatureState represents the state of a Git signature.
@ -114,16 +91,23 @@ const (
GitSignatureStateExpiredKey GitSignatureState = "EXPIRED_KEY" // Signing key expired.
)
// StatusState represents the possible commit status states.
type StatusState string
// IssueOrderField represents properties by which issue connections can be ordered.
type IssueOrderField string
// The possible commit status states.
// Properties by which issue connections can be ordered.
const (
StatusStateExpected StatusState = "EXPECTED" // Status is expected.
StatusStateError StatusState = "ERROR" // Status is errored.
StatusStateFailure StatusState = "FAILURE" // Status is failing.
StatusStatePending StatusState = "PENDING" // Status is pending.
StatusStateSuccess StatusState = "SUCCESS" // Status is successful.
IssueOrderFieldCreatedAt IssueOrderField = "CREATED_AT" // Order issues by creation time.
IssueOrderFieldUpdatedAt IssueOrderField = "UPDATED_AT" // Order issues by update time.
IssueOrderFieldComments IssueOrderField = "COMMENTS" // Order issues by comment count.
)
// IssuePubSubTopic represents the possible PubSub channels for an issue.
type IssuePubSubTopic string
// The possible PubSub channels for an issue.
const (
IssuePubSubTopicUpdated IssuePubSubTopic = "UPDATED" // The channel ID for observing issue updates.
IssuePubSubTopicMarkasread IssuePubSubTopic = "MARKASREAD" // The channel ID for marking an issue as read.
)
// IssueState represents the possible states of an issue.
@ -135,55 +119,12 @@ const (
IssueStateClosed IssueState = "CLOSED" // An issue that has been closed.
)
// IssueOrderField represents properties by which issue connections can be ordered.
type IssueOrderField string
// LanguageOrderField represents properties by which language connections can be ordered.
type LanguageOrderField string
// Properties by which issue connections can be ordered.
// Properties by which language connections can be ordered.
const (
IssueOrderFieldCreatedAt IssueOrderField = "CREATED_AT" // Order issues by creation time.
IssueOrderFieldUpdatedAt IssueOrderField = "UPDATED_AT" // Order issues by update time.
IssueOrderFieldComments IssueOrderField = "COMMENTS" // Order issues by comment count.
)
// RepositoryPrivacy represents the privacy of a repository.
type RepositoryPrivacy string
// The privacy of a repository.
const (
RepositoryPrivacyPublic RepositoryPrivacy = "PUBLIC" // Public.
RepositoryPrivacyPrivate RepositoryPrivacy = "PRIVATE" // Private.
)
// RepositoryOrderField represents properties by which repository connections can be ordered.
type RepositoryOrderField string
// Properties by which repository connections can be ordered.
const (
RepositoryOrderFieldCreatedAt RepositoryOrderField = "CREATED_AT" // Order repositories by creation time.
RepositoryOrderFieldUpdatedAt RepositoryOrderField = "UPDATED_AT" // Order repositories by update time.
RepositoryOrderFieldPushedAt RepositoryOrderField = "PUSHED_AT" // Order repositories by push time.
RepositoryOrderFieldName RepositoryOrderField = "NAME" // Order repositories by name.
RepositoryOrderFieldStargazers RepositoryOrderField = "STARGAZERS" // Order repositories by number of stargazers.
)
// RepositoryAffiliation represents the affiliation of a user to a repository.
type RepositoryAffiliation string
// The affiliation of a user to a repository.
const (
RepositoryAffiliationOwner RepositoryAffiliation = "OWNER" // Repositories that are owned by the authenticated user.
RepositoryAffiliationCollaborator RepositoryAffiliation = "COLLABORATOR" // Repositories that the user has been added to as a collaborator.
RepositoryAffiliationOrganizationMember RepositoryAffiliation = "ORGANIZATION_MEMBER" // Repositories that the user has access to through being a member of an organization. This includes every repository on every team that the user is on.
)
// PullRequestState represents the possible states of a pull request.
type PullRequestState string
// The possible states of a pull request.
const (
PullRequestStateOpen PullRequestState = "OPEN" // A pull request that is still open.
PullRequestStateClosed PullRequestState = "CLOSED" // A pull request that has been closed without being merged.
PullRequestStateMerged PullRequestState = "MERGED" // A pull request that has been closed by being merged.
LanguageOrderFieldSize LanguageOrderField = "SIZE" // Order languages by the size of all files containing the language.
)
// MergeableState represents whether or not a PullRequest can be merged.
@ -196,13 +137,83 @@ const (
MergeableStateUnknown MergeableState = "UNKNOWN" // The mergeability of the pull request is still being calculated.
)
// IssuePubSubTopic represents the possible PubSub channels for an issue.
type IssuePubSubTopic string
// MilestoneState represents the possible states of a milestone.
type MilestoneState string
// The possible PubSub channels for an issue.
// The possible states of a milestone.
const (
IssuePubSubTopicUpdated IssuePubSubTopic = "UPDATED" // The channel ID for observing issue updates.
IssuePubSubTopicMarkasread IssuePubSubTopic = "MARKASREAD" // The channel ID for marking an issue as read.
MilestoneStateOpen MilestoneState = "OPEN" // A milestone that is still open.
MilestoneStateClosed MilestoneState = "CLOSED" // A milestone that has been closed.
)
// OrderDirection represents possible directions in which to order a list of items when provided an `orderBy` argument.
type OrderDirection string
// Possible directions in which to order a list of items when provided an `orderBy` argument.
const (
OrderDirectionAsc OrderDirection = "ASC" // Specifies an ascending order for a given `orderBy` argument.
OrderDirectionDesc OrderDirection = "DESC" // Specifies a descending order for a given `orderBy` argument.
)
// OrganizationInvitationRole represents the possible organization invitation roles.
type OrganizationInvitationRole string
// The possible organization invitation roles.
const (
OrganizationInvitationRoleDirectMember OrganizationInvitationRole = "DIRECT_MEMBER" // The user is invited to be a direct member of the organization.
OrganizationInvitationRoleAdmin OrganizationInvitationRole = "ADMIN" // The user is invited to be an admin of the organization.
OrganizationInvitationRoleBillingManager OrganizationInvitationRole = "BILLING_MANAGER" // The user is invited to be a billing manager of the organization.
OrganizationInvitationRoleReinstate OrganizationInvitationRole = "REINSTATE" // The user's previous role will be reinstated.
)
// ProjectCardState represents various content states of a ProjectCard.
type ProjectCardState string
// Various content states of a ProjectCard.
const (
ProjectCardStateContentOnly ProjectCardState = "CONTENT_ONLY" // The card has content only.
ProjectCardStateNoteOnly ProjectCardState = "NOTE_ONLY" // The card has a note only.
ProjectCardStateRedacted ProjectCardState = "REDACTED" // The card is redacted.
)
// ProjectOrderField represents properties by which project connections can be ordered.
type ProjectOrderField string
// Properties by which project connections can be ordered.
const (
ProjectOrderFieldCreatedAt ProjectOrderField = "CREATED_AT" // Order projects by creation time.
ProjectOrderFieldUpdatedAt ProjectOrderField = "UPDATED_AT" // Order projects by update time.
ProjectOrderFieldName ProjectOrderField = "NAME" // Order projects by name.
)
// ProjectState represents state of the project; either 'open' or 'closed'.
type ProjectState string
// State of the project; either 'open' or 'closed'.
const (
ProjectStateOpen ProjectState = "OPEN" // The project is open.
ProjectStateClosed ProjectState = "CLOSED" // The project is closed.
)
// PullRequestPubSubTopic represents the possible PubSub channels for a pull request.
type PullRequestPubSubTopic string
// The possible PubSub channels for a pull request.
const (
PullRequestPubSubTopicUpdated PullRequestPubSubTopic = "UPDATED" // The channel ID for observing pull request updates.
PullRequestPubSubTopicMarkasread PullRequestPubSubTopic = "MARKASREAD" // The channel ID for marking an pull request as read.
PullRequestPubSubTopicHeadRef PullRequestPubSubTopic = "HEAD_REF" // The channel ID for observing head ref updates.
)
// PullRequestReviewEvent represents the possible events to perform on a pull request review.
type PullRequestReviewEvent string
// The possible events to perform on a pull request review.
const (
PullRequestReviewEventComment PullRequestReviewEvent = "COMMENT" // Submit general feedback without explicit approval.
PullRequestReviewEventApprove PullRequestReviewEvent = "APPROVE" // Submit feedback and approve merging these changes.
PullRequestReviewEventRequestChanges PullRequestReviewEvent = "REQUEST_CHANGES" // Submit feedback that must be addressed before merging.
PullRequestReviewEventDismiss PullRequestReviewEvent = "DISMISS" // Dismiss review so it now longer effects merging.
)
// PullRequestReviewState represents the possible states of a pull request review.
@ -217,134 +228,45 @@ const (
PullRequestReviewStateDismissed PullRequestReviewState = "DISMISSED" // A review that has been dismissed.
)
// PullRequestPubSubTopic represents the possible PubSub channels for a pull request.
type PullRequestPubSubTopic string
// PullRequestState represents the possible states of a pull request.
type PullRequestState string
// The possible PubSub channels for a pull request.
// The possible states of a pull request.
const (
PullRequestPubSubTopicUpdated PullRequestPubSubTopic = "UPDATED" // The channel ID for observing pull request updates.
PullRequestPubSubTopicMarkasread PullRequestPubSubTopic = "MARKASREAD" // The channel ID for marking an pull request as read.
PullRequestPubSubTopicHeadRef PullRequestPubSubTopic = "HEAD_REF" // The channel ID for observing head ref updates.
PullRequestStateOpen PullRequestState = "OPEN" // A pull request that is still open.
PullRequestStateClosed PullRequestState = "CLOSED" // A pull request that has been closed without being merged.
PullRequestStateMerged PullRequestState = "MERGED" // A pull request that has been closed by being merged.
)
// TeamPrivacy represents the possible team privacy values.
type TeamPrivacy string
// ReactionContent represents emojis that can be attached to Issues, Pull Requests and Comments.
type ReactionContent string
// The possible team privacy values.
// Emojis that can be attached to Issues, Pull Requests and Comments.
const (
TeamPrivacySecret TeamPrivacy = "SECRET" // A secret team can only be seen by its members.
TeamPrivacyVisible TeamPrivacy = "VISIBLE" // A visible team can be seen and @mentioned by every member of the organization.
ReactionContentThumbsUp ReactionContent = "THUMBS_UP" // Represents the 👍 emoji.
ReactionContentThumbsDown ReactionContent = "THUMBS_DOWN" // Represents the 👎 emoji.
ReactionContentLaugh ReactionContent = "LAUGH" // Represents the 😄 emoji.
ReactionContentHooray ReactionContent = "HOORAY" // Represents the 🎉 emoji.
ReactionContentConfused ReactionContent = "CONFUSED" // Represents the 😕 emoji.
ReactionContentHeart ReactionContent = "HEART" // Represents the ❤️ emoji.
)
// UserOrderField represents properties by which user connections can be ordered.
type UserOrderField string
// ReactionOrderField represents a list of fields that reactions can be ordered by.
type ReactionOrderField string
// Properties by which user connections can be ordered.
// A list of fields that reactions can be ordered by.
const (
UserOrderFieldLogin UserOrderField = "LOGIN" // Allows ordering a list of users by their login.
UserOrderFieldAction UserOrderField = "ACTION" // Allows ordering a list of users by their ability action.
ReactionOrderFieldCreatedAt ReactionOrderField = "CREATED_AT" // Allows ordering a list of reactions by when they were created.
)
// OrganizationInvitationRole represents the possible organization invitation roles.
type OrganizationInvitationRole string
// RepositoryAffiliation represents the affiliation of a user to a repository.
type RepositoryAffiliation string
// The possible organization invitation roles.
// The affiliation of a user to a repository.
const (
OrganizationInvitationRoleDirectMember OrganizationInvitationRole = "DIRECT_MEMBER" // The user is invited to be a direct member of the organization.
OrganizationInvitationRoleAdmin OrganizationInvitationRole = "ADMIN" // The user is invited to be an admin of the organization.
OrganizationInvitationRoleBillingManager OrganizationInvitationRole = "BILLING_MANAGER" // The user is invited to be a billing manager of the organization.
OrganizationInvitationRoleReinstate OrganizationInvitationRole = "REINSTATE" // The user's previous role will be reinstated.
)
// TeamOrderField represents properties by which team connections can be ordered.
type TeamOrderField string
// Properties by which team connections can be ordered.
const (
TeamOrderFieldName TeamOrderField = "NAME" // Allows ordering a list of teams by name.
)
// DefaultRepositoryPermissionField represents the possible default permissions for organization-owned repositories.
type DefaultRepositoryPermissionField string
// The possible default permissions for organization-owned repositories.
const (
DefaultRepositoryPermissionFieldRead DefaultRepositoryPermissionField = "READ" // Members have read access to org repos by default.
DefaultRepositoryPermissionFieldWrite DefaultRepositoryPermissionField = "WRITE" // Members have read and write access to org repos by default.
DefaultRepositoryPermissionFieldAdmin DefaultRepositoryPermissionField = "ADMIN" // Members have read, write, and admin access to org repos by default.
)
// TeamRole represents the role of a user on a team.
type TeamRole string
// The role of a user on a team.
const (
TeamRoleAdmin TeamRole = "ADMIN" // User has admin rights on the team.
TeamRoleMember TeamRole = "MEMBER" // User is a member of the team.
)
// DeploymentStatusState represents the possible states for a deployment status.
type DeploymentStatusState string
// The possible states for a deployment status.
const (
DeploymentStatusStatePending DeploymentStatusState = "PENDING" // The deployment is pending.
DeploymentStatusStateSuccess DeploymentStatusState = "SUCCESS" // The deployment was successful.
DeploymentStatusStateFailure DeploymentStatusState = "FAILURE" // The deployment has failed.
DeploymentStatusStateInactive DeploymentStatusState = "INACTIVE" // The deployment is inactive.
DeploymentStatusStateError DeploymentStatusState = "ERROR" // The deployment experienced an error.
)
// DeploymentState represents the possible states in which a deployment can be.
type DeploymentState string
// The possible states in which a deployment can be.
const (
DeploymentStateAbandoned DeploymentState = "ABANDONED" // The pending deployment was not updated after 30 minutes.
DeploymentStateActive DeploymentState = "ACTIVE" // The deployment is currently active.
DeploymentStateDestroyed DeploymentState = "DESTROYED" // An inactive transient deployment.
DeploymentStateError DeploymentState = "ERROR" // The deployment experienced an error.
DeploymentStateFailure DeploymentState = "FAILURE" // The deployment has failed.
DeploymentStateInactive DeploymentState = "INACTIVE" // The deployment is inactive.
DeploymentStatePending DeploymentState = "PENDING" // The deployment is pending.
)
// StarOrderField represents properties by which star connections can be ordered.
type StarOrderField string
// Properties by which star connections can be ordered.
const (
StarOrderFieldStarredAt StarOrderField = "STARRED_AT" // Allows ordering a list of stars by when they were created.
)
// GistPrivacy represents the privacy of a Gist.
type GistPrivacy string
// The privacy of a Gist.
const (
GistPrivacyPublic GistPrivacy = "PUBLIC" // Public.
GistPrivacySecret GistPrivacy = "SECRET" // Secret.
GistPrivacyAll GistPrivacy = "ALL" // Gists that are public and secret.
)
// MilestoneState represents the possible states of a milestone.
type MilestoneState string
// The possible states of a milestone.
const (
MilestoneStateOpen MilestoneState = "OPEN" // A milestone that is still open.
MilestoneStateClosed MilestoneState = "CLOSED" // A milestone that has been closed.
)
// RepositoryLockReason represents the possible reasons a given repsitory could be in a locked state.
type RepositoryLockReason string
// The possible reasons a given repsitory could be in a locked state.
const (
RepositoryLockReasonMoving RepositoryLockReason = "MOVING" // The repository is locked due to a move.
RepositoryLockReasonBilling RepositoryLockReason = "BILLING" // The repository is locked due to a billing related reason.
RepositoryLockReasonRename RepositoryLockReason = "RENAME" // The repository is locked due to a rename.
RepositoryLockReasonMigrating RepositoryLockReason = "MIGRATING" // The repository is locked due to a migration.
RepositoryAffiliationOwner RepositoryAffiliation = "OWNER" // Repositories that are owned by the authenticated user.
RepositoryAffiliationCollaborator RepositoryAffiliation = "COLLABORATOR" // Repositories that the user has been added to as a collaborator.
RepositoryAffiliationOrganizationMember RepositoryAffiliation = "ORGANIZATION_MEMBER" // Repositories that the user has access to through being a member of an organization. This includes every repository on every team that the user is on.
)
// RepositoryCollaboratorAffiliation represents the affiliation type between collaborator and repository.
@ -356,12 +278,46 @@ const (
RepositoryCollaboratorAffiliationOutside RepositoryCollaboratorAffiliation = "OUTSIDE" // All outside collaborators of an organization-owned repository.
)
// LanguageOrderField represents properties by which language connections can be ordered.
type LanguageOrderField string
// RepositoryLockReason represents the possible reasons a given repository could be in a locked state.
type RepositoryLockReason string
// Properties by which language connections can be ordered.
// The possible reasons a given repository could be in a locked state.
const (
LanguageOrderFieldSize LanguageOrderField = "SIZE" // Order languages by the size of all files containing the language.
RepositoryLockReasonMoving RepositoryLockReason = "MOVING" // The repository is locked due to a move.
RepositoryLockReasonBilling RepositoryLockReason = "BILLING" // The repository is locked due to a billing related reason.
RepositoryLockReasonRename RepositoryLockReason = "RENAME" // The repository is locked due to a rename.
RepositoryLockReasonMigrating RepositoryLockReason = "MIGRATING" // The repository is locked due to a migration.
)
// RepositoryOrderField represents properties by which repository connections can be ordered.
type RepositoryOrderField string
// Properties by which repository connections can be ordered.
const (
RepositoryOrderFieldCreatedAt RepositoryOrderField = "CREATED_AT" // Order repositories by creation time.
RepositoryOrderFieldUpdatedAt RepositoryOrderField = "UPDATED_AT" // Order repositories by update time.
RepositoryOrderFieldPushedAt RepositoryOrderField = "PUSHED_AT" // Order repositories by push time.
RepositoryOrderFieldName RepositoryOrderField = "NAME" // Order repositories by name.
RepositoryOrderFieldStargazers RepositoryOrderField = "STARGAZERS" // Order repositories by number of stargazers.
)
// RepositoryPermission represents the access level to a repository.
type RepositoryPermission string
// The access level to a repository.
const (
RepositoryPermissionAdmin RepositoryPermission = "ADMIN" // Can read, clone, push, and add collaborators.
RepositoryPermissionWrite RepositoryPermission = "WRITE" // Can read, clone and push.
RepositoryPermissionRead RepositoryPermission = "READ" // Can read and clone.
)
// RepositoryPrivacy represents the privacy of a repository.
type RepositoryPrivacy string
// The privacy of a repository.
const (
RepositoryPrivacyPublic RepositoryPrivacy = "PUBLIC" // Public.
RepositoryPrivacyPrivate RepositoryPrivacy = "PRIVATE" // Private.
)
// SearchType represents represents the individual results of a search.
@ -374,15 +330,92 @@ const (
SearchTypeUser SearchType = "USER" // Returns results matching users on GitHub.
)
// PullRequestReviewEvent represents the possible events to perform on a pull request review.
type PullRequestReviewEvent string
// StarOrderField represents properties by which star connections can be ordered.
type StarOrderField string
// The possible events to perform on a pull request review.
// Properties by which star connections can be ordered.
const (
PullRequestReviewEventComment PullRequestReviewEvent = "COMMENT" // Submit general feedback without explicit approval.
PullRequestReviewEventApprove PullRequestReviewEvent = "APPROVE" // Submit feedback and approve merging these changes.
PullRequestReviewEventRequestChanges PullRequestReviewEvent = "REQUEST_CHANGES" // Submit feedback that must be addressed before merging.
PullRequestReviewEventDismiss PullRequestReviewEvent = "DISMISS" // Dismiss review so it now longer effects merging.
StarOrderFieldStarredAt StarOrderField = "STARRED_AT" // Allows ordering a list of stars by when they were created.
)
// StatusState represents the possible commit status states.
type StatusState string
// The possible commit status states.
const (
StatusStateExpected StatusState = "EXPECTED" // Status is expected.
StatusStateError StatusState = "ERROR" // Status is errored.
StatusStateFailure StatusState = "FAILURE" // Status is failing.
StatusStatePending StatusState = "PENDING" // Status is pending.
StatusStateSuccess StatusState = "SUCCESS" // Status is successful.
)
// SubscriptionState represents the possible states of a subscription.
type SubscriptionState string
// The possible states of a subscription.
const (
SubscriptionStateUnsubscribed SubscriptionState = "UNSUBSCRIBED" // The User is only notified when particpating or @mentioned.
SubscriptionStateSubscribed SubscriptionState = "SUBSCRIBED" // The User is notified of all conversations.
SubscriptionStateIgnored SubscriptionState = "IGNORED" // The User is never notified.
)
// TeamMemberRole represents the possible team member roles; either 'maintainer' or 'member'.
type TeamMemberRole string
// The possible team member roles; either 'maintainer' or 'member'.
const (
TeamMemberRoleMaintainer TeamMemberRole = "MAINTAINER" // A team maintainer has permission to add and remove team members.
TeamMemberRoleMember TeamMemberRole = "MEMBER" // A team member has no administrative permissions on the team.
)
// TeamMembershipType represents defines which types of team members are included in the returned list. Can be one of IMMEDIATE, CHILD_TEAM or ALL.
type TeamMembershipType string
// Defines which types of team members are included in the returned list. Can be one of IMMEDIATE, CHILD_TEAM or ALL.
const (
TeamMembershipTypeImmediate TeamMembershipType = "IMMEDIATE" // Includes only immediate members of the team.
TeamMembershipTypeChildTeam TeamMembershipType = "CHILD_TEAM" // Includes only child team members for the team.
TeamMembershipTypeAll TeamMembershipType = "ALL" // Includes immediate and child team members for the team.
)
// TeamOrderField represents properties by which team connections can be ordered.
type TeamOrderField string
// Properties by which team connections can be ordered.
const (
TeamOrderFieldName TeamOrderField = "NAME" // Allows ordering a list of teams by name.
)
// TeamPrivacy represents the possible team privacy values.
type TeamPrivacy string
// The possible team privacy values.
const (
TeamPrivacySecret TeamPrivacy = "SECRET" // A secret team can only be seen by its members.
TeamPrivacyVisible TeamPrivacy = "VISIBLE" // A visible team can be seen and @mentioned by every member of the organization.
)
// TeamRepositoryOrderField represents properties by which team repository connections can be ordered.
type TeamRepositoryOrderField string
// Properties by which team repository connections can be ordered.
const (
TeamRepositoryOrderFieldCreatedAt TeamRepositoryOrderField = "CREATED_AT" // Order repositories by creation time.
TeamRepositoryOrderFieldUpdatedAt TeamRepositoryOrderField = "UPDATED_AT" // Order repositories by update time.
TeamRepositoryOrderFieldPushedAt TeamRepositoryOrderField = "PUSHED_AT" // Order repositories by push time.
TeamRepositoryOrderFieldName TeamRepositoryOrderField = "NAME" // Order repositories by name.
TeamRepositoryOrderFieldPermission TeamRepositoryOrderField = "PERMISSION" // Order repositories by permission.
TeamRepositoryOrderFieldStargazers TeamRepositoryOrderField = "STARGAZERS" // Order repositories by number of stargazers.
)
// TeamRole represents the role of a user on a team.
type TeamRole string
// The role of a user on a team.
const (
TeamRoleAdmin TeamRole = "ADMIN" // User has admin rights on the team.
TeamRoleMember TeamRole = "MEMBER" // User is a member of the team.
)
// TopicSuggestionDeclineReason represents reason that the suggested topic is declined.

View File

@ -1,19 +1,15 @@
package githubql
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/shurcooL/githubql/internal/jsonutil"
"github.com/shurcooL/go/ctxhttp"
"github.com/shurcooL/graphql"
)
// Client is a GitHub GraphQL API v4 client.
type Client struct {
httpClient *http.Client
client *graphql.Client
}
// NewClient creates a new GitHub GraphQL API v4 client with the provided http.Client.
@ -22,11 +18,8 @@ type Client struct {
// Note that GitHub GraphQL API v4 requires authentication, so
// the provided http.Client is expected to take care of that.
func NewClient(httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
return &Client{
httpClient: httpClient,
client: graphql.NewClient("https://api.github.com/graphql", httpClient, scalars),
}
}
@ -34,7 +27,7 @@ func NewClient(httpClient *http.Client) *Client {
// with a query derived from q, populating the response into it.
// q should be a pointer to struct that corresponds to the GitHub GraphQL schema.
func (c *Client) Query(ctx context.Context, q interface{}, variables map[string]interface{}) error {
return c.do(ctx, queryOperation, q, variables)
return c.client.Query(ctx, q, variables)
}
// Mutate executes a single GraphQL mutation request,
@ -47,75 +40,5 @@ func (c *Client) Mutate(ctx context.Context, m interface{}, input Input, variabl
} else {
variables["input"] = input
}
return c.do(ctx, mutationOperation, m, variables)
return c.client.Mutate(ctx, m, variables)
}
// do executes a single GraphQL operation.
func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}) error {
var query string
switch op {
case queryOperation:
query = constructQuery(v, variables)
case mutationOperation:
query = constructMutation(v, variables)
}
in := struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
}{
Query: query,
Variables: variables,
}
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(in)
if err != nil {
return err
}
resp, err := ctxhttp.Post(ctx, c.httpClient, "https://api.github.com/graphql", "application/json", &buf)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status: %v", resp.Status)
}
var out struct {
Data json.RawMessage
Errors errors
//Extensions interface{} // Unused.
}
err = json.NewDecoder(resp.Body).Decode(&out)
if err != nil {
return err
}
if len(out.Errors) > 0 {
return out.Errors
}
err = jsonutil.UnmarshalGraphQL(out.Data, v)
return err
}
// errors represents the "errors" array in a response from a GraphQL server.
// If returned via error interface, the slice is expected to contain at least 1 element.
//
// Specification: https://facebook.github.io/graphql/#sec-Errors.
type errors []struct {
Message string
Locations []struct {
Line int
Column int
}
}
// Error implements error interface.
func (e errors) Error() string {
return e[0].Message
}
type operationType uint8
const (
queryOperation operationType = iota
mutationOperation
//subscriptionOperation // Unused.
)

View File

@ -2,99 +2,15 @@ package githubql
// Input represents one of the Input structs:
//
// AcceptTopicSuggestionInput, AddCommentInput, AddProjectCardInput, AddProjectColumnInput, AddPullRequestReviewCommentInput, AddPullRequestReviewInput, AddReactionInput, AddStarInput, CommitAuthor, CreateProjectInput, DeclineTopicSuggestionInput, DeleteProjectCardInput, DeleteProjectColumnInput, DeleteProjectInput, DeletePullRequestReviewInput, DismissPullRequestReviewInput, DraftPullRequestReviewComment, IssueOrder, LanguageOrder, MemberOrder, MoveProjectCardInput, MoveProjectColumnInput, ProjectOrder, ReactionOrder, RemoveOutsideCollaboratorInput, RemoveReactionInput, RemoveStarInput, RepositoryOrder, RequestReviewsInput, StarOrder, SubmitPullRequestReviewInput, TeamOrder, UpdateProjectCardInput, UpdateProjectColumnInput, UpdateProjectInput, UpdatePullRequestReviewCommentInput, UpdatePullRequestReviewInput, UpdateSubscriptionInput, UpdateTopicsInput.
// AcceptTopicSuggestionInput, AddCommentInput, AddProjectCardInput, AddProjectColumnInput, AddPullRequestReviewCommentInput, AddPullRequestReviewInput, AddReactionInput, AddStarInput, CommitAuthor, CreateProjectInput, DeclineTopicSuggestionInput, DeleteProjectCardInput, DeleteProjectColumnInput, DeleteProjectInput, DeletePullRequestReviewInput, DismissPullRequestReviewInput, DraftPullRequestReviewComment, IssueOrder, LanguageOrder, MoveProjectCardInput, MoveProjectColumnInput, ProjectOrder, ReactionOrder, RemoveOutsideCollaboratorInput, RemoveReactionInput, RemoveStarInput, RepositoryOrder, RequestReviewsInput, StarOrder, SubmitPullRequestReviewInput, TeamOrder, TeamRepositoryOrder, UpdateProjectCardInput, UpdateProjectColumnInput, UpdateProjectInput, UpdatePullRequestReviewCommentInput, UpdatePullRequestReviewInput, UpdateSubscriptionInput, UpdateTopicsInput.
type Input interface{}
// ProjectOrder represents ways in which lists of projects can be ordered upon return.
type ProjectOrder struct {
// The field in which to order projects by. (Required.)
Field ProjectOrderField `json:"field"`
// The direction in which to order projects by the specified field. (Required.)
Direction OrderDirection `json:"direction"`
}
// CommitAuthor specifies an author for filtering Git commits.
type CommitAuthor struct {
// ID of a User to filter by. If non-null, only commits authored by this user will be returned. This field takes precedence over emails. (Optional.)
ID *ID `json:"id,omitempty"`
// Email addresses to filter by. Commits authored by any of the specified email addresses will be returned. (Optional.)
Emails *[]String `json:"emails,omitempty"`
}
// ReactionOrder represents ways in which lists of reactions can be ordered upon return.
type ReactionOrder struct {
// The field in which to order reactions by. (Required.)
Field ReactionOrderField `json:"field"`
// The direction in which to order reactions by the specified field. (Required.)
Direction OrderDirection `json:"direction"`
}
// IssueOrder represents ways in which lists of issues can be ordered upon return.
type IssueOrder struct {
// The field in which to order issues by. (Required.)
Field IssueOrderField `json:"field"`
// The direction in which to order issues by the specified field. (Required.)
Direction OrderDirection `json:"direction"`
}
// RepositoryOrder represents ordering options for repository connections.
type RepositoryOrder struct {
// The field to order repositories by. (Required.)
Field RepositoryOrderField `json:"field"`
// The ordering direction. (Required.)
Direction OrderDirection `json:"direction"`
}
// MemberOrder represents ways in which member connections can be ordered.
type MemberOrder struct {
// The field in which to order nodes by. (Required.)
Field UserOrderField `json:"field"`
// The direction in which to order nodes. (Required.)
Direction OrderDirection `json:"direction"`
}
// TeamOrder represents ways in which team connections can be ordered.
type TeamOrder struct {
// The field in which to order nodes by. (Required.)
Field TeamOrderField `json:"field"`
// The direction in which to order nodes. (Required.)
Direction OrderDirection `json:"direction"`
}
// StarOrder represents ways in which star connections can be ordered.
type StarOrder struct {
// The field in which to order nodes by. (Required.)
Field StarOrderField `json:"field"`
// The direction in which to order nodes. (Required.)
Direction OrderDirection `json:"direction"`
}
// LanguageOrder represents ordering options for language connections.
type LanguageOrder struct {
// The field to order languages by. (Required.)
Field LanguageOrderField `json:"field"`
// The ordering direction. (Required.)
Direction OrderDirection `json:"direction"`
}
// AddReactionInput is an autogenerated input type of AddReaction.
type AddReactionInput struct {
// The Node ID of the subject to modify. (Required.)
SubjectID ID `json:"subjectId"`
// The name of the emoji to react with. (Required.)
Content ReactionContent `json:"content"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// RemoveReactionInput is an autogenerated input type of RemoveReaction.
type RemoveReactionInput struct {
// The Node ID of the subject to modify. (Required.)
SubjectID ID `json:"subjectId"`
// The name of the emoji to react with. (Required.)
Content ReactionContent `json:"content"`
// AcceptTopicSuggestionInput is an autogenerated input type of AcceptTopicSuggestion.
type AcceptTopicSuggestionInput struct {
// The Node ID of the repository. (Required.)
RepositoryID ID `json:"repositoryId"`
// The name of the suggested topic. (Required.)
Name String `json:"name"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
@ -111,96 +27,6 @@ type AddCommentInput struct {
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// UpdateSubscriptionInput is an autogenerated input type of UpdateSubscription.
type UpdateSubscriptionInput struct {
// The Node ID of the subscribable object to modify. (Required.)
SubscribableID ID `json:"subscribableId"`
// The new state of the subscription. (Required.)
State SubscriptionState `json:"state"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// CreateProjectInput is an autogenerated input type of CreateProject.
type CreateProjectInput struct {
// The owner ID to create the project under. (Required.)
OwnerID ID `json:"ownerId"`
// The name of project. (Required.)
Name String `json:"name"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// The description of project. (Optional.)
Body *String `json:"body,omitempty"`
}
// UpdateProjectInput is an autogenerated input type of UpdateProject.
type UpdateProjectInput struct {
// The Project ID to update. (Required.)
ProjectID ID `json:"projectId"`
// The name of project. (Required.)
Name String `json:"name"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// The description of project. (Optional.)
Body *String `json:"body,omitempty"`
// Whether the project is open or closed. (Optional.)
State *ProjectState `json:"state,omitempty"`
}
// DeleteProjectInput is an autogenerated input type of DeleteProject.
type DeleteProjectInput struct {
// The Project ID to update. (Required.)
ProjectID ID `json:"projectId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// AddProjectColumnInput is an autogenerated input type of AddProjectColumn.
type AddProjectColumnInput struct {
// The Node ID of the project. (Required.)
ProjectID ID `json:"projectId"`
// The name of the column. (Required.)
Name String `json:"name"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// MoveProjectColumnInput is an autogenerated input type of MoveProjectColumn.
type MoveProjectColumnInput struct {
// The id of the column to move. (Required.)
ColumnID ID `json:"columnId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// Place the new column after the column with this id. Pass null to place it at the front. (Optional.)
AfterColumnID *ID `json:"afterColumnId,omitempty"`
}
// UpdateProjectColumnInput is an autogenerated input type of UpdateProjectColumn.
type UpdateProjectColumnInput struct {
// The ProjectColumn ID to update. (Required.)
ProjectColumnID ID `json:"projectColumnId"`
// The name of project column. (Required.)
Name String `json:"name"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// DeleteProjectColumnInput is an autogenerated input type of DeleteProjectColumn.
type DeleteProjectColumnInput struct {
// The id of the column to delete. (Required.)
ColumnID ID `json:"columnId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// AddProjectCardInput is an autogenerated input type of AddProjectCard.
type AddProjectCardInput struct {
// The Node ID of the ProjectColumn. (Required.)
@ -214,105 +40,12 @@ type AddProjectCardInput struct {
Note *String `json:"note,omitempty"`
}
// UpdateProjectCardInput is an autogenerated input type of UpdateProjectCard.
type UpdateProjectCardInput struct {
// The ProjectCard ID to update. (Required.)
ProjectCardID ID `json:"projectCardId"`
// The note of ProjectCard. (Required.)
Note String `json:"note"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// MoveProjectCardInput is an autogenerated input type of MoveProjectCard.
type MoveProjectCardInput struct {
// The id of the card to move. (Required.)
CardID ID `json:"cardId"`
// The id of the column to move it into. (Required.)
ColumnID ID `json:"columnId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// Place the new card after the card with this id. Pass null to place it at the top. (Optional.)
AfterCardID *ID `json:"afterCardId,omitempty"`
}
// DeleteProjectCardInput is an autogenerated input type of DeleteProjectCard.
type DeleteProjectCardInput struct {
// The id of the card to delete. (Required.)
CardID ID `json:"cardId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// AddPullRequestReviewInput is an autogenerated input type of AddPullRequestReview.
type AddPullRequestReviewInput struct {
// The Node ID of the pull request to modify. (Required.)
PullRequestID ID `json:"pullRequestId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// The commit OID the review pertains to. (Optional.)
CommitOID *GitObjectID `json:"commitOID,omitempty"`
// The contents of the review body comment. (Optional.)
Body *String `json:"body,omitempty"`
// The event to perform on the pull request review. (Optional.)
Event *PullRequestReviewEvent `json:"event,omitempty"`
// The review line comments. (Optional.)
Comments *[]*DraftPullRequestReviewComment `json:"comments,omitempty"`
}
// DraftPullRequestReviewComment specifies a review comment to be left with a Pull Request Review.
type DraftPullRequestReviewComment struct {
// Path to the file being commented on. (Required.)
Path String `json:"path"`
// Position in the file to leave a comment on. (Required.)
Position Int `json:"position"`
// Body of the comment to leave. (Required.)
Body String `json:"body"`
}
// SubmitPullRequestReviewInput is an autogenerated input type of SubmitPullRequestReview.
type SubmitPullRequestReviewInput struct {
// The Pull Request Review ID to submit. (Required.)
PullRequestReviewID ID `json:"pullRequestReviewId"`
// The event to send to the Pull Request Review. (Required.)
Event PullRequestReviewEvent `json:"event"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// The text field to set on the Pull Request Review. (Optional.)
Body *String `json:"body,omitempty"`
}
// UpdatePullRequestReviewInput is an autogenerated input type of UpdatePullRequestReview.
type UpdatePullRequestReviewInput struct {
// The Node ID of the pull request review to modify. (Required.)
PullRequestReviewID ID `json:"pullRequestReviewId"`
// The contents of the pull request review body. (Required.)
Body String `json:"body"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// DismissPullRequestReviewInput is an autogenerated input type of DismissPullRequestReview.
type DismissPullRequestReviewInput struct {
// The Node ID of the pull request review to modify. (Required.)
PullRequestReviewID ID `json:"pullRequestReviewId"`
// The contents of the pull request review dismissal message. (Required.)
Message String `json:"message"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// DeletePullRequestReviewInput is an autogenerated input type of DeletePullRequestReview.
type DeletePullRequestReviewInput struct {
// The Node ID of the pull request review to delete. (Required.)
PullRequestReviewID ID `json:"pullRequestReviewId"`
// AddProjectColumnInput is an autogenerated input type of AddProjectColumn.
type AddProjectColumnInput struct {
// The Node ID of the project. (Required.)
ProjectID ID `json:"projectId"`
// The name of the column. (Required.)
Name String `json:"name"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
@ -337,39 +70,32 @@ type AddPullRequestReviewCommentInput struct {
InReplyTo *ID `json:"inReplyTo,omitempty"`
}
// UpdatePullRequestReviewCommentInput is an autogenerated input type of UpdatePullRequestReviewComment.
type UpdatePullRequestReviewCommentInput struct {
// The Node ID of the comment to modify. (Required.)
PullRequestReviewCommentID ID `json:"pullRequestReviewCommentId"`
// The text of the comment. (Required.)
Body String `json:"body"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// RemoveOutsideCollaboratorInput is an autogenerated input type of RemoveOutsideCollaborator.
type RemoveOutsideCollaboratorInput struct {
// The ID of the outside collaborator to remove. (Required.)
UserID ID `json:"userId"`
// The ID of the organization to remove the outside collaborator from. (Required.)
OrganizationID ID `json:"organizationId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// RequestReviewsInput is an autogenerated input type of RequestReviews.
type RequestReviewsInput struct {
// AddPullRequestReviewInput is an autogenerated input type of AddPullRequestReview.
type AddPullRequestReviewInput struct {
// The Node ID of the pull request to modify. (Required.)
PullRequestID ID `json:"pullRequestId"`
// The Node IDs of the users to request. (Required.)
UserIds []ID `json:"userIds"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// Add users to the set rather than replace. (Optional.)
Union *Boolean `json:"union,omitempty"`
// The commit OID the review pertains to. (Optional.)
CommitOID *GitObjectID `json:"commitOID,omitempty"`
// The contents of the review body comment. (Optional.)
Body *String `json:"body,omitempty"`
// The event to perform on the pull request review. (Optional.)
Event *PullRequestReviewEvent `json:"event,omitempty"`
// The review line comments. (Optional.)
Comments *[]*DraftPullRequestReviewComment `json:"comments,omitempty"`
}
// AddReactionInput is an autogenerated input type of AddReaction.
type AddReactionInput struct {
// The Node ID of the subject to modify. (Required.)
SubjectID ID `json:"subjectId"`
// The name of the emoji to react with. (Required.)
Content ReactionContent `json:"content"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// AddStarInput is an autogenerated input type of AddStar.
@ -381,24 +107,26 @@ type AddStarInput struct {
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// RemoveStarInput is an autogenerated input type of RemoveStar.
type RemoveStarInput struct {
// The Starrable ID to unstar. (Required.)
StarrableID ID `json:"starrableId"`
// CommitAuthor specifies an author for filtering Git commits.
type CommitAuthor struct {
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// ID of a User to filter by. If non-null, only commits authored by this user will be returned. This field takes precedence over emails. (Optional.)
ID *ID `json:"id,omitempty"`
// Email addresses to filter by. Commits authored by any of the specified email addresses will be returned. (Optional.)
Emails *[]String `json:"emails,omitempty"`
}
// AcceptTopicSuggestionInput is an autogenerated input type of AcceptTopicSuggestion.
type AcceptTopicSuggestionInput struct {
// The Node ID of the repository. (Required.)
RepositoryID ID `json:"repositoryId"`
// The name of the suggested topic. (Required.)
// CreateProjectInput is an autogenerated input type of CreateProject.
type CreateProjectInput struct {
// The owner ID to create the project under. (Required.)
OwnerID ID `json:"ownerId"`
// The name of project. (Required.)
Name String `json:"name"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// The description of project. (Optional.)
Body *String `json:"body,omitempty"`
}
// DeclineTopicSuggestionInput is an autogenerated input type of DeclineTopicSuggestion.
@ -414,6 +142,280 @@ type DeclineTopicSuggestionInput struct {
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// DeleteProjectCardInput is an autogenerated input type of DeleteProjectCard.
type DeleteProjectCardInput struct {
// The id of the card to delete. (Required.)
CardID ID `json:"cardId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// DeleteProjectColumnInput is an autogenerated input type of DeleteProjectColumn.
type DeleteProjectColumnInput struct {
// The id of the column to delete. (Required.)
ColumnID ID `json:"columnId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// DeleteProjectInput is an autogenerated input type of DeleteProject.
type DeleteProjectInput struct {
// The Project ID to update. (Required.)
ProjectID ID `json:"projectId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// DeletePullRequestReviewInput is an autogenerated input type of DeletePullRequestReview.
type DeletePullRequestReviewInput struct {
// The Node ID of the pull request review to delete. (Required.)
PullRequestReviewID ID `json:"pullRequestReviewId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// DismissPullRequestReviewInput is an autogenerated input type of DismissPullRequestReview.
type DismissPullRequestReviewInput struct {
// The Node ID of the pull request review to modify. (Required.)
PullRequestReviewID ID `json:"pullRequestReviewId"`
// The contents of the pull request review dismissal message. (Required.)
Message String `json:"message"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// DraftPullRequestReviewComment specifies a review comment to be left with a Pull Request Review.
type DraftPullRequestReviewComment struct {
// Path to the file being commented on. (Required.)
Path String `json:"path"`
// Position in the file to leave a comment on. (Required.)
Position Int `json:"position"`
// Body of the comment to leave. (Required.)
Body String `json:"body"`
}
// IssueOrder represents ways in which lists of issues can be ordered upon return.
type IssueOrder struct {
// The field in which to order issues by. (Required.)
Field IssueOrderField `json:"field"`
// The direction in which to order issues by the specified field. (Required.)
Direction OrderDirection `json:"direction"`
}
// LanguageOrder represents ordering options for language connections.
type LanguageOrder struct {
// The field to order languages by. (Required.)
Field LanguageOrderField `json:"field"`
// The ordering direction. (Required.)
Direction OrderDirection `json:"direction"`
}
// MoveProjectCardInput is an autogenerated input type of MoveProjectCard.
type MoveProjectCardInput struct {
// The id of the card to move. (Required.)
CardID ID `json:"cardId"`
// The id of the column to move it into. (Required.)
ColumnID ID `json:"columnId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// Place the new card after the card with this id. Pass null to place it at the top. (Optional.)
AfterCardID *ID `json:"afterCardId,omitempty"`
}
// MoveProjectColumnInput is an autogenerated input type of MoveProjectColumn.
type MoveProjectColumnInput struct {
// The id of the column to move. (Required.)
ColumnID ID `json:"columnId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// Place the new column after the column with this id. Pass null to place it at the front. (Optional.)
AfterColumnID *ID `json:"afterColumnId,omitempty"`
}
// ProjectOrder represents ways in which lists of projects can be ordered upon return.
type ProjectOrder struct {
// The field in which to order projects by. (Required.)
Field ProjectOrderField `json:"field"`
// The direction in which to order projects by the specified field. (Required.)
Direction OrderDirection `json:"direction"`
}
// ReactionOrder represents ways in which lists of reactions can be ordered upon return.
type ReactionOrder struct {
// The field in which to order reactions by. (Required.)
Field ReactionOrderField `json:"field"`
// The direction in which to order reactions by the specified field. (Required.)
Direction OrderDirection `json:"direction"`
}
// RemoveOutsideCollaboratorInput is an autogenerated input type of RemoveOutsideCollaborator.
type RemoveOutsideCollaboratorInput struct {
// The ID of the outside collaborator to remove. (Required.)
UserID ID `json:"userId"`
// The ID of the organization to remove the outside collaborator from. (Required.)
OrganizationID ID `json:"organizationId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// RemoveReactionInput is an autogenerated input type of RemoveReaction.
type RemoveReactionInput struct {
// The Node ID of the subject to modify. (Required.)
SubjectID ID `json:"subjectId"`
// The name of the emoji to react with. (Required.)
Content ReactionContent `json:"content"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// RemoveStarInput is an autogenerated input type of RemoveStar.
type RemoveStarInput struct {
// The Starrable ID to unstar. (Required.)
StarrableID ID `json:"starrableId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// RepositoryOrder represents ordering options for repository connections.
type RepositoryOrder struct {
// The field to order repositories by. (Required.)
Field RepositoryOrderField `json:"field"`
// The ordering direction. (Required.)
Direction OrderDirection `json:"direction"`
}
// RequestReviewsInput is an autogenerated input type of RequestReviews.
type RequestReviewsInput struct {
// The Node ID of the pull request to modify. (Required.)
PullRequestID ID `json:"pullRequestId"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// The Node IDs of the user to request. (Optional.)
UserIDs *[]ID `json:"userIds,omitempty"`
// The Node IDs of the team to request. (Optional.)
TeamIDs *[]ID `json:"teamIds,omitempty"`
// Add users to the set rather than replace. (Optional.)
Union *Boolean `json:"union,omitempty"`
}
// StarOrder represents ways in which star connections can be ordered.
type StarOrder struct {
// The field in which to order nodes by. (Required.)
Field StarOrderField `json:"field"`
// The direction in which to order nodes. (Required.)
Direction OrderDirection `json:"direction"`
}
// SubmitPullRequestReviewInput is an autogenerated input type of SubmitPullRequestReview.
type SubmitPullRequestReviewInput struct {
// The Pull Request Review ID to submit. (Required.)
PullRequestReviewID ID `json:"pullRequestReviewId"`
// The event to send to the Pull Request Review. (Required.)
Event PullRequestReviewEvent `json:"event"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// The text field to set on the Pull Request Review. (Optional.)
Body *String `json:"body,omitempty"`
}
// TeamOrder represents ways in which team connections can be ordered.
type TeamOrder struct {
// The field in which to order nodes by. (Required.)
Field TeamOrderField `json:"field"`
// The direction in which to order nodes. (Required.)
Direction OrderDirection `json:"direction"`
}
// TeamRepositoryOrder represents ordering options for team repository connections.
type TeamRepositoryOrder struct {
// The field to order repositories by. (Required.)
Field TeamRepositoryOrderField `json:"field"`
// The ordering direction. (Required.)
Direction OrderDirection `json:"direction"`
}
// UpdateProjectCardInput is an autogenerated input type of UpdateProjectCard.
type UpdateProjectCardInput struct {
// The ProjectCard ID to update. (Required.)
ProjectCardID ID `json:"projectCardId"`
// The note of ProjectCard. (Required.)
Note String `json:"note"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// UpdateProjectColumnInput is an autogenerated input type of UpdateProjectColumn.
type UpdateProjectColumnInput struct {
// The ProjectColumn ID to update. (Required.)
ProjectColumnID ID `json:"projectColumnId"`
// The name of project column. (Required.)
Name String `json:"name"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// UpdateProjectInput is an autogenerated input type of UpdateProject.
type UpdateProjectInput struct {
// The Project ID to update. (Required.)
ProjectID ID `json:"projectId"`
// The name of project. (Required.)
Name String `json:"name"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
// The description of project. (Optional.)
Body *String `json:"body,omitempty"`
// Whether the project is open or closed. (Optional.)
State *ProjectState `json:"state,omitempty"`
}
// UpdatePullRequestReviewCommentInput is an autogenerated input type of UpdatePullRequestReviewComment.
type UpdatePullRequestReviewCommentInput struct {
// The Node ID of the comment to modify. (Required.)
PullRequestReviewCommentID ID `json:"pullRequestReviewCommentId"`
// The text of the comment. (Required.)
Body String `json:"body"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// UpdatePullRequestReviewInput is an autogenerated input type of UpdatePullRequestReview.
type UpdatePullRequestReviewInput struct {
// The Node ID of the pull request review to modify. (Required.)
PullRequestReviewID ID `json:"pullRequestReviewId"`
// The contents of the pull request review body. (Required.)
Body String `json:"body"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// UpdateSubscriptionInput is an autogenerated input type of UpdateSubscription.
type UpdateSubscriptionInput struct {
// The Node ID of the subscribable object to modify. (Required.)
SubscribableID ID `json:"subscribableId"`
// The new state of the subscription. (Required.)
State SubscriptionState `json:"state"`
// A unique identifier for the client performing the mutation. (Optional.)
ClientMutationID *String `json:"clientMutationId,omitempty"`
}
// UpdateTopicsInput is an autogenerated input type of UpdateTopics.
type UpdateTopicsInput struct {
// The Node ID of the repository. (Required.)

View File

@ -5,7 +5,10 @@ import (
"encoding/json"
"fmt"
"net/url"
"reflect"
"time"
"github.com/shurcooL/graphql"
)
// Note: These custom types are meant to be used in queries for now.
@ -19,14 +22,14 @@ import (
type (
// Boolean represents true or false values.
Boolean bool
Boolean graphql.Boolean
// DateTime is an ISO-8601 encoded UTC date.
DateTime struct{ time.Time }
// Float represents signed double-precision fractional values as
// specified by IEEE 754.
Float float64
Float graphql.Float
// GitObjectID is a Git object ID. For example,
// "912ec1990bd09f8fc128c3fa6b59105085aabc03".
@ -45,16 +48,16 @@ type (
// intended to be human-readable. When expected as an input type,
// any string (such as "VXNlci0xMA==") or integer (such as 4) input
// value will be accepted as an ID.
ID interface{}
ID graphql.ID
// Int represents non-fractional signed whole numeric values.
// Int can represent values between -(2^31) and 2^31 - 1.
Int int32
Int graphql.Int
// String represents textual data as UTF-8 character sequences.
// This type is most often used by GraphQL to represent free-form
// human-readable text.
String string
String graphql.String
// URI is an RFC 3986, RFC 3987, and RFC 6570 (level 4) compliant URI.
URI struct{ *url.URL }
@ -63,6 +66,13 @@ type (
X509Certificate struct{ *x509.Certificate }
)
var scalars = []reflect.Type{
reflect.TypeOf(DateTime{}),
reflect.TypeOf(GitTimestamp{}),
reflect.TypeOf(URI{}),
reflect.TypeOf(X509Certificate{}),
}
// MarshalJSON implements the json.Marshaler interface.
// The URI is a quoted string.
func (u URI) MarshalJSON() ([]byte, error) {

34079
vendor/github.com/shurcooL/githubql/schema.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

21
vendor/github.com/shurcooL/graphql/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Dmitri Shuralyov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

219
vendor/github.com/shurcooL/graphql/README.md generated vendored Normal file
View File

@ -0,0 +1,219 @@
graphql
=======
[![Build Status](https://travis-ci.org/shurcooL/graphql.svg?branch=master)](https://travis-ci.org/shurcooL/graphql) [![GoDoc](https://godoc.org/github.com/shurcooL/graphql?status.svg)](https://godoc.org/github.com/shurcooL/graphql)
Package `graphql` provides a GraphQL client implementation.
For more information, see package [`github.com/shurcooL/githubql`](https://github.com/shurcooL/githubql), which is a specialized version targeting GitHub GraphQL API v4. That package is driving the feature development.
**Status:** In active early research and development. The API will change when opportunities for improvement are discovered; it is not yet frozen.
Installation
------------
`graphql` requires Go version 1.8 or later.
```bash
go get -u github.com/shurcooL/graphql
```
Usage
-----
Construct a GraphQL client, specifying the GraphQL server URL. Then, you can use it to make GraphQL queries and mutations.
```Go
client := graphql.NewClient("https://example.com/graphql", nil, nil)
// Use client...
```
### Authentication
Some GraphQL servers may require authentication. The `graphql` package does not directly handle authentication. Instead, when creating a new client, you're expected to pass an `http.Client` that performs authentication. The easiest and recommended way to do this is to use the [`golang.org/x/oauth2`](https://golang.org/x/oauth2) package. You'll need an OAuth token with the right scopes. Then:
```Go
import "golang.org/x/oauth2"
func main() {
src := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.Getenv("GRAPHQL_TOKEN")},
)
httpClient := oauth2.NewClient(context.Background(), src)
client := graphql.NewClient("https://example.com/graphql", httpClient, nil)
// Use client...
```
### Simple Query
To make a GraphQL query, you need to define a corresponding Go type.
For example, to make the following GraphQL query:
```GraphQL
query {
me {
name
}
}
```
You can define this variable:
```Go
var query struct {
Me struct {
Name graphql.String
}
}
```
And call `client.Query`, passing a pointer to it:
```Go
err := client.Query(context.Background(), &query, nil)
if err != nil {
// Handle error.
}
fmt.Println(query.Me.Name)
// Output: Luke Skywalker
```
### Arguments and Variables
Often, you'll want to specify arguments on some fields. You can use the `graphql` struct field tag for this.
For example, to make the following GraphQL query:
```GraphQL
{
human(id: "1000") {
name
height(unit: METER)
}
}
```
You can define this variable:
```Go
var q struct {
Human struct {
Name graphql.String
Height graphql.Float `graphql:"height(unit: METER)"`
} `graphql:"human(id: \"1000\")"`
}
```
And call `client.Query`:
```Go
err := client.Query(context.Background(), &q, nil)
if err != nil {
// Handle error.
}
fmt.Println(q.Human.Name)
fmt.Println(q.Human.Height)
// Output:
// Luke Skywalker
// 1.72
```
However, that'll only work if the arguments are constant and known in advance. Otherwise, you will need to make use of variables. Replace the constants in the struct field tag with variable names:
```Go
var q struct {
Human struct {
Name graphql.String
Height graphql.Float `graphql:"height(unit: $unit)"`
} `graphql:"human(id: $id)"`
}
```
Then, define a `variables` map with their values:
```Go
variables := map[string]interface{}{
"id": graphql.ID(id),
"unit": starwars.LengthUnit("METER"),
}
```
Finally, call `client.Query` providing `variables`:
```Go
err := client.Query(context.Background(), &q, variables)
if err != nil {
// Handle error.
}
```
### Mutations
Mutations often require information that you can only find out by performing a query first. Let's suppose you've already done that.
For example, to make the following GraphQL mutation:
```GraphQL
mutation($ep: Episode!, $review: ReviewInput!) {
createReview(episode: $ep, review: $review) {
stars
commentary
}
}
variables {
"ep": "JEDI",
"review": {
"stars": 5,
"commentary": "This is a great movie!"
}
}
```
You can define:
```Go
var m struct {
CreateReview struct {
Stars graphql.Int
Commentary graphql.String
} `graphql:"createReview(episode: $ep, review: $review)"`
}
variables := map[string]interface{}{
"ep": starwars.Episode("JEDI"),
"review": starwars.ReviewInput{
Stars: graphql.Int(5),
Commentary: graphql.String("This is a great movie!"),
},
}
```
And call `client.Mutate`:
```Go
err := client.Mutate(context.Background(), &m, variables)
if err != nil {
// Handle error.
}
fmt.Printf("Created a %v star review: %v\n", m.CreateReview.Stars, m.CreateReview.Commentary)
// Output:
// Created a 5 star review: This is a great movie!
```
Directories
-----------
| Path | Synopsis |
|----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|
| [example/graphqldev](https://godoc.org/github.com/shurcooL/graphql/example/graphqldev) | graphqldev is a test program currently being used for developing graphql package. |
| [ident](https://godoc.org/github.com/shurcooL/graphql/ident) | Package ident provides functions for parsing and converting identifier names between various naming convention. |
| [internal/jsonutil](https://godoc.org/github.com/shurcooL/graphql/internal/jsonutil) | Package jsonutil provides a function for decoding JSON into a GraphQL query data structure. |
License
-------
- [MIT License](LICENSE)

11
vendor/github.com/shurcooL/graphql/doc.go generated vendored Normal file
View File

@ -0,0 +1,11 @@
// Package graphql provides a GraphQL client implementation.
//
// For more information, see package github.com/shurcooL/githubql,
// which is a specialized version targeting GitHub GraphQL API v4.
// That package is driving the feature development.
//
// Status: In active early research and development. The API will change when
// opportunities for improvement are discovered; it is not yet frozen.
//
// For now, see README for more details.
package graphql // import "github.com/shurcooL/graphql"

123
vendor/github.com/shurcooL/graphql/graphql.go generated vendored Normal file
View File

@ -0,0 +1,123 @@
package graphql
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"github.com/shurcooL/go/ctxhttp"
"github.com/shurcooL/graphql/internal/jsonutil"
)
// Client is a GraphQL client.
type Client struct {
url string // GraphQL server URL.
httpClient *http.Client
qctx *queryContext
}
// NewClient creates a GraphQL client targeting the specified GraphQL server URL.
// If httpClient is nil, then http.DefaultClient is used.
// scalars optionally specifies types that are scalars (this matters
// when constructing queries from types, scalars are never expanded).
func NewClient(url string, httpClient *http.Client, scalars []reflect.Type) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
return &Client{
url: url,
httpClient: httpClient,
qctx: &queryContext{
Scalars: scalars,
},
}
}
// Query executes a single GraphQL query request,
// with a query derived from q, populating the response into it.
// q should be a pointer to struct that corresponds to the GraphQL schema.
func (c *Client) Query(ctx context.Context, q interface{}, variables map[string]interface{}) error {
return c.do(ctx, queryOperation, q, variables)
}
// Mutate executes a single GraphQL mutation request,
// with a mutation derived from m, populating the response into it.
// m should be a pointer to struct that corresponds to the GraphQL schema.
func (c *Client) Mutate(ctx context.Context, m interface{}, variables map[string]interface{}) error {
return c.do(ctx, mutationOperation, m, variables)
}
// do executes a single GraphQL operation.
func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}) error {
var query string
switch op {
case queryOperation:
query = constructQuery(c.qctx, v, variables)
case mutationOperation:
query = constructMutation(c.qctx, v, variables)
}
in := struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
}{
Query: query,
Variables: variables,
}
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(in)
if err != nil {
return err
}
resp, err := ctxhttp.Post(ctx, c.httpClient, c.url, "application/json", &buf)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status: %v", resp.Status)
}
var out struct {
Data json.RawMessage
Errors errors
//Extensions interface{} // Unused.
}
err = json.NewDecoder(resp.Body).Decode(&out)
if err != nil {
return err
}
if len(out.Errors) > 0 {
return out.Errors
}
err = jsonutil.UnmarshalGraphQL(out.Data, v)
return err
}
// errors represents the "errors" array in a response from a GraphQL server.
// If returned via error interface, the slice is expected to contain at least 1 element.
//
// Specification: https://facebook.github.io/graphql/#sec-Errors.
type errors []struct {
Message string
Locations []struct {
Line int
Column int
}
}
// Error implements error interface.
func (e errors) Error() string {
return e[0].Message
}
type operationType uint8
const (
queryOperation operationType = iota
mutationOperation
//subscriptionOperation // Unused.
)

215
vendor/github.com/shurcooL/graphql/ident/ident.go generated vendored Normal file
View File

@ -0,0 +1,215 @@
// Package ident provides functions for parsing and converting identifier names
// between various naming convention. It has support for MixedCaps, lowerCamelCase,
// and SCREAMING_SNAKE_CASE naming conventions.
package ident
import (
"strings"
"unicode"
"unicode/utf8"
)
// ParseMixedCaps parses a MixedCaps identifier name.
//
// E.g., "ClientMutationID" -> {"Client", "Mutation", "ID"}.
func ParseMixedCaps(name string) Name {
var words Name
// Split name at any lower -> Upper or Upper -> Upper,lower transitions.
// Check each word for initialisms.
runes := []rune(name)
w, i := 0, 0 // Index of start of word, scan.
for i+1 <= len(runes) {
eow := false // Whether we hit the end of a word.
if i+1 == len(runes) {
eow = true
} else if unicode.IsLower(runes[i]) && unicode.IsUpper(runes[i+1]) {
// lower -> Upper.
eow = true
} else if i+2 < len(runes) && unicode.IsUpper(runes[i]) && unicode.IsUpper(runes[i+1]) && unicode.IsLower(runes[i+2]) {
// Upper -> Upper,lower. End of acronym, followed by a word.
eow = true
if string(runes[i:i+3]) == "IDs" { // Special case, plural form of ID initialism.
eow = false
}
}
i++
if !eow {
continue
}
// [w, i) is a word.
word := string(runes[w:i])
if initialism, ok := isInitialism(word); ok {
words = append(words, initialism)
} else if i1, i2, ok := isTwoInitialisms(word); ok {
words = append(words, i1, i2)
} else {
words = append(words, word)
}
w = i
}
return words
}
// ParseLowerCamelCase parses a lowerCamelCase identifier name.
//
// E.g., "clientMutationId" -> {"client", "Mutation", "Id"}.
func ParseLowerCamelCase(name string) Name {
var words Name
// Split name at any Upper letters.
runes := []rune(name)
w, i := 0, 0 // Index of start of word, scan.
for i+1 <= len(runes) {
eow := false // Whether we hit the end of a word.
if i+1 == len(runes) {
eow = true
} else if unicode.IsUpper(runes[i+1]) {
// Upper letter.
eow = true
}
i++
if !eow {
continue
}
// [w, i) is a word.
words = append(words, string(runes[w:i]))
w = i
}
return words
}
// ParseScreamingSnakeCase parses a SCREAMING_SNAKE_CASE identifier name.
//
// E.g., "CLIENT_MUTATION_ID" -> {"CLIENT", "MUTATION", "ID"}.
func ParseScreamingSnakeCase(name string) Name {
var words Name
// Split name at '_' characters.
runes := []rune(name)
w, i := 0, 0 // Index of start of word, scan.
for i+1 <= len(runes) {
eow := false // Whether we hit the end of a word.
if i+1 == len(runes) {
eow = true
} else if runes[i+1] == '_' {
// Underscore.
eow = true
}
i++
if !eow {
continue
}
// [w, i) is a word.
words = append(words, string(runes[w:i]))
if i < len(runes) && runes[i] == '_' {
// Skip underscore.
i++
}
w = i
}
return words
}
// Name is an identifier name, broken up into individual words.
type Name []string
// ToMixedCaps expresses identifer name in MixedCaps naming convention.
//
// E.g., "ClientMutationID".
func (n Name) ToMixedCaps() string {
for i, word := range n {
if strings.EqualFold(word, "IDs") { // Special case, plural form of ID initialism.
n[i] = "IDs"
continue
}
if initialism, ok := isInitialism(word); ok {
n[i] = initialism
continue
}
r, size := utf8.DecodeRuneInString(word)
n[i] = string(unicode.ToUpper(r)) + strings.ToLower(word[size:])
}
return strings.Join(n, "")
}
// ToLowerCamelCase expresses identifer name in lowerCamelCase naming convention.
//
// E.g., "clientMutationId".
func (n Name) ToLowerCamelCase() string {
for i, word := range n {
if i == 0 {
n[i] = strings.ToLower(word)
continue
}
r, size := utf8.DecodeRuneInString(word)
n[i] = string(unicode.ToUpper(r)) + strings.ToLower(word[size:])
}
return strings.Join(n, "")
}
// isInitialism reports whether word is an initialism.
func isInitialism(word string) (string, bool) {
initialism := strings.ToUpper(word)
_, ok := initialisms[initialism]
return initialism, ok
}
// isTwoInitialisms reports whether word is two initialisms.
func isTwoInitialisms(word string) (string, string, bool) {
word = strings.ToUpper(word)
for i := 2; i <= len(word)-2; i++ { // Shortest initialism is 2 characters long.
_, ok1 := initialisms[word[:i]]
_, ok2 := initialisms[word[i:]]
if ok1 && ok2 {
return word[:i], word[i:], true
}
}
return "", "", false
}
// initialisms is the set of initialisms in the MixedCaps naming convention.
var initialisms = map[string]struct{}{
"ACL": {},
"API": {},
"ASCII": {},
"CPU": {},
"CSS": {},
"DNS": {},
"EOF": {},
"GUID": {},
"HTML": {},
"HTTP": {},
"HTTPS": {},
"ID": {},
"IP": {},
"JSON": {},
"LHS": {},
"QPS": {},
"RAM": {},
"RHS": {},
"RPC": {},
"SLA": {},
"SMTP": {},
"SQL": {},
"SSH": {},
"TCP": {},
"TLS": {},
"TTL": {},
"UDP": {},
"UI": {},
"UID": {},
"UUID": {},
"URI": {},
"URL": {},
"UTF8": {},
"VM": {},
"XML": {},
"XMPP": {},
"XSRF": {},
"XSS": {},
}

View File

@ -0,0 +1,299 @@
// Package jsonutil provides a function for decoding JSON
// into a GraphQL query data structure.
package jsonutil
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"strings"
)
// UnmarshalGraphQL parses the JSON-encoded GraphQL response data and stores
// the result in the GraphQL query data structure pointed to by v.
//
// The implementation is created on top of the JSON tokenizer available
// in "encoding/json".Decoder.
func UnmarshalGraphQL(data []byte, v interface{}) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
err := (&decoder{tokenizer: dec}).Decode(v)
if err != nil {
return err
}
tok, err := dec.Token()
switch err {
case io.EOF:
// Expect to get io.EOF. There shouldn't be any more
// tokens left after we've decoded v successfully.
return nil
case nil:
return fmt.Errorf("invalid token '%v' after top-level value", tok)
default:
return err
}
}
// decoder is a JSON decoder that performs custom unmarshaling behavior
// for GraphQL query data structures. It's implemented on top of a JSON tokenizer.
type decoder struct {
tokenizer interface {
Token() (json.Token, error)
}
// Stack of what part of input JSON we're in the middle of - objects, arrays.
parseState []json.Delim
// Stacks of values where to unmarshal.
// The top of each stack is the reflect.Value where to unmarshal next JSON value.
//
// The reason there's more than one stack is because we might be unmarshaling
// a single JSON value into multiple GraphQL fragments or embedded structs, so
// we keep track of them all.
vs [][]reflect.Value
}
// Decode decodes a single JSON value from d.tokenizer into v.
func (d *decoder) Decode(v interface{}) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr {
return fmt.Errorf("cannot decode into non-pointer %T", v)
}
d.vs = [][]reflect.Value{{rv.Elem()}}
return d.decode()
}
// decode decodes a single JSON value from d.tokenizer into d.vs.
func (d *decoder) decode() error {
// The loop invariant is that the top of each d.vs stack
// is where we try to unmarshal the next JSON value we see.
for len(d.vs) > 0 {
tok, err := d.tokenizer.Token()
if err == io.EOF {
return errors.New("unexpected end of JSON input")
} else if err != nil {
return err
}
switch {
// Are we inside an object and seeing next key (rather than end of object)?
case d.state() == '{' && tok != json.Delim('}'):
key, ok := tok.(string)
if !ok {
return errors.New("unexpected non-key in JSON input")
}
someFieldExist := false
for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
var f reflect.Value
if v.Kind() == reflect.Struct {
f = fieldByGraphQLName(v, key)
if f.IsValid() {
someFieldExist = true
}
}
d.vs[i] = append(d.vs[i], f)
}
if !someFieldExist {
return fmt.Errorf("struct field for %s doesn't exist in any of %v places", key, len(d.vs))
}
// We've just consumed the current token, which was the key.
// Read the next token, which should be the value, and let the rest of code process it.
tok, err = d.tokenizer.Token()
if err == io.EOF {
return errors.New("unexpected end of JSON input")
} else if err != nil {
return err
}
// Are we inside an array and seeing next value (rather than end of array)?
case d.state() == '[' && tok != json.Delim(']'):
for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Slice {
return fmt.Errorf("can't decode into non-slice %v", v.Kind())
}
v.Set(reflect.Append(v, reflect.Zero(v.Type().Elem()))) // v = append(v, T).
d.vs[i] = append(d.vs[i], v.Index(v.Len()-1))
}
}
switch tok := tok.(type) {
// Values.
case string, json.Number, bool, nil:
for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
if !v.IsValid() {
continue
}
err := unmarshalValue(tok, v)
if err != nil {
return err
}
}
d.popAllVs()
// Start/end of object/array.
case json.Delim:
switch tok {
case '{':
d.pushState(tok)
frontier := make([]reflect.Value, len(d.vs)) // Places to look for GraphQL fragments/embedded structs.
for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
frontier[i] = v
// TODO: Do this recursively or not? Add a test case if needed.
if v.Kind() == reflect.Ptr && v.IsNil() {
v.Set(reflect.New(v.Type().Elem())) // v = new(T).
}
}
// Find GraphQL fragments/embedded structs recursively, adding to frontier
// as new ones are discovered and exploring them further.
for len(frontier) > 0 {
v := frontier[0]
frontier = frontier[1:]
// TODO: Needed? Add a test case if so.
//if v.Kind() == reflect.Ptr {
// v = v.Elem()
//}
if v.Kind() != reflect.Struct {
continue
}
for i := 0; i < v.NumField(); i++ {
if isGraphQLFragment(v.Type().Field(i)) || v.Type().Field(i).Anonymous {
// Add GraphQL fragment or embedded struct.
d.vs = append(d.vs, []reflect.Value{v.Field(i)})
frontier = append(frontier, v.Field(i))
}
}
}
case '[':
d.pushState(tok)
for i := range d.vs {
v := d.vs[i][len(d.vs[i])-1]
// TODO: Confirm this is needed, write a test case.
//if v.Kind() == reflect.Ptr && v.IsNil() {
// v.Set(reflect.New(v.Type().Elem())) // v = new(T).
//}
// Reset slice to empty (in case it had non-zero initial value).
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Slice {
continue
}
v.Set(reflect.Zero(v.Type())) // v = zero(v).
}
case '}', ']':
d.popAllVs()
d.popState()
default:
return errors.New("unexpected delimiter in JSON input")
}
default:
return errors.New("unexpected token in JSON input")
}
}
return nil
}
// pushState pushes a new parse state s onto the stack.
func (d *decoder) pushState(s json.Delim) {
d.parseState = append(d.parseState, s)
}
// popState pops a parse state (already obtained) off the stack.
// The stack must be non-empty.
func (d *decoder) popState() {
d.parseState = d.parseState[:len(d.parseState)-1]
}
// state reports the parse state on top of stack, or 0 if empty.
func (d *decoder) state() json.Delim {
if len(d.parseState) == 0 {
return 0
}
return d.parseState[len(d.parseState)-1]
}
// popAllVs pops from all d.vs stacks, keeping only non-empty ones.
func (d *decoder) popAllVs() {
var nonEmpty [][]reflect.Value
for i := range d.vs {
d.vs[i] = d.vs[i][:len(d.vs[i])-1]
if len(d.vs[i]) > 0 {
nonEmpty = append(nonEmpty, d.vs[i])
}
}
d.vs = nonEmpty
}
// fieldByGraphQLName returns a struct field of struct v that matches GraphQL name,
// or invalid reflect.Value if none found.
func fieldByGraphQLName(v reflect.Value, name string) reflect.Value {
for i := 0; i < v.NumField(); i++ {
if hasGraphQLName(v.Type().Field(i), name) {
return v.Field(i)
}
}
return reflect.Value{}
}
// hasGraphQLName reports whether struct field f has GraphQL name.
func hasGraphQLName(f reflect.StructField, name string) bool {
value, ok := f.Tag.Lookup("graphql")
if !ok {
// TODO: caseconv package is relatively slow. Optimize it, then consider using it here.
//return caseconv.MixedCapsToLowerCamelCase(f.Name) == name
return strings.EqualFold(f.Name, name)
}
value = strings.TrimSpace(value) // TODO: Parse better.
if strings.HasPrefix(value, "...") {
// GraphQL fragment. It doesn't have a name.
return false
}
if i := strings.Index(value, "("); i != -1 {
value = value[:i]
}
if i := strings.Index(value, ":"); i != -1 {
value = value[:i]
}
return strings.TrimSpace(value) == name
}
// isGraphQLFragment reports whether struct field f is a GraphQL fragment.
func isGraphQLFragment(f reflect.StructField) bool {
value, ok := f.Tag.Lookup("graphql")
if !ok {
return false
}
value = strings.TrimSpace(value) // TODO: Parse better.
return strings.HasPrefix(value, "...")
}
// unmarshalValue unmarshals JSON value into v.
func unmarshalValue(value json.Token, v reflect.Value) error {
b, err := json.Marshal(value) // TODO: Short-circuit (if profiling says it's worth it).
if err != nil {
return err
}
if !v.CanAddr() {
return fmt.Errorf("value %v is not addressable", v)
}
return json.Unmarshal(b, v.Addr().Interface())
}

View File

@ -1,4 +1,4 @@
package githubql
package graphql
import (
"bytes"
@ -6,25 +6,19 @@ import (
"reflect"
"sort"
"github.com/shurcooL/githubql/internal/hacky/caseconv"
"github.com/shurcooL/graphql/ident"
)
// WARNING: This file contains hacky (but functional) code. It's very ugly.
// The goal is to eventually clean up the code here and move it elsewhere,
// reducing this file to non-existence. But, I'm tackling higher priorities
// first (such as ensuring the API design will scale and work out), and
// saving time by deferring this work.
func constructQuery(v interface{}, variables map[string]interface{}) string {
query := querify(v)
func constructQuery(qctx *queryContext, v interface{}, variables map[string]interface{}) string {
query := qctx.Query(v)
if variables != nil {
return "query(" + queryArguments(variables) + ")" + query
}
return query
}
func constructMutation(v interface{}, variables map[string]interface{}) string {
query := querify(v)
func constructMutation(qctx *queryContext, v interface{}, variables map[string]interface{}) string {
query := qctx.Query(v)
if variables != nil {
return "mutation(" + queryArguments(variables) + ")" + query
}
@ -64,33 +58,39 @@ func queryArguments(variables map[string]interface{}) string {
return s
}
// querify uses querifyType, which recursively constructs
type queryContext struct {
// Scalars are Go types that map to GraphQL scalars, and therefore we don't want to expand them.
Scalars []reflect.Type
}
// Query uses writeQuery to recursively construct
// a minified query string from the provided struct v.
//
// E.g., struct{Foo Int, Bar *Boolean} -> "{foo,bar}".
func querify(v interface{}) string {
// E.g., struct{Foo Int, BarBaz *Boolean} -> "{foo,barBaz}".
func (c *queryContext) Query(v interface{}) string {
var buf bytes.Buffer
querifyType(&buf, reflect.TypeOf(v), false)
c.writeQuery(&buf, reflect.TypeOf(v), false)
return buf.String()
}
func querifyType(w io.Writer, t reflect.Type, inline bool) {
// writeQuery writes a minified query for t to w. If inline is true,
// the struct fields of t are inlined into parent struct.
func (c *queryContext) writeQuery(w io.Writer, t reflect.Type, inline bool) {
switch t.Kind() {
case reflect.Ptr, reflect.Slice:
querifyType(w, t.Elem(), false)
c.writeQuery(w, t.Elem(), false)
case reflect.Struct:
// Special handling of scalar struct types.
if t == dateTimeType || t == gitTimestampType || t == uriType || t == x509CertificateType {
return
// Special handling of scalar struct types. Don't expand them.
for _, scalar := range c.Scalars {
if t == scalar {
return
}
}
if !inline {
io.WriteString(w, "{")
}
sep := false
for i := 0; i < t.NumField(); i++ {
if !sep {
sep = true
} else {
if i != 0 {
io.WriteString(w, ",")
}
f := t.Field(i)
@ -100,20 +100,13 @@ func querifyType(w io.Writer, t reflect.Type, inline bool) {
if ok {
io.WriteString(w, value)
} else {
io.WriteString(w, caseconv.MixedCapsToLowerCamelCase(f.Name))
io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase())
}
}
querifyType(w, f.Type, inlineField)
c.writeQuery(w, f.Type, inlineField)
}
if !inline {
io.WriteString(w, "}")
}
}
}
var (
dateTimeType = reflect.TypeOf(DateTime{})
gitTimestampType = reflect.TypeOf(GitTimestamp{})
uriType = reflect.TypeOf(URI{})
x509CertificateType = reflect.TypeOf(X509Certificate{})
)

51
vendor/github.com/shurcooL/graphql/scalar.go generated vendored Normal file
View File

@ -0,0 +1,51 @@
package graphql
// Note: These custom types are meant to be used in queries for now.
// But the plan is to switch to using native Go types (string, int, bool, time.Time, etc.).
// See https://github.com/shurcooL/githubql/issues/9 for details.
//
// These custom types currently provide documentation, and their use
// is required for sending outbound queries. However, native Go types
// can be used for unmarshaling. Once https://github.com/shurcooL/githubql/issues/9
// is resolved, native Go types can completely replace these.
type (
// Boolean represents true or false values.
Boolean bool
// Float represents signed double-precision fractional values as
// specified by IEEE 754.
Float float64
// ID represents a unique identifier that is Base64 obfuscated. It
// is often used to refetch an object or as key for a cache. The ID
// type appears in a JSON response as a String; however, it is not
// intended to be human-readable. When expected as an input type,
// any string (such as "VXNlci0xMA==") or integer (such as 4) input
// value will be accepted as an ID.
ID interface{}
// Int represents non-fractional signed whole numeric values.
// Int can represent values between -(2^31) and 2^31 - 1.
Int int32
// String represents textual data as UTF-8 character sequences.
// This type is most often used by GraphQL to represent free-form
// human-readable text.
String string
)
// NewBoolean is a helper to make a new *Boolean.
func NewBoolean(v Boolean) *Boolean { return &v }
// NewFloat is a helper to make a new *Float.
func NewFloat(v Float) *Float { return &v }
// NewID is a helper to make a new *ID.
func NewID(v ID) *ID { return &v }
// NewInt is a helper to make a new *Int.
func NewInt(v Int) *Int { return &v }
// NewString is a helper to make a new *String.
func NewString(v String) *String { return &v }

24
vendor/vendor.json vendored
View File

@ -58,10 +58,10 @@
"revisionTime": "2014-02-26T03:06:59Z"
},
{
"checksumSHA1": "pDc4wX6YbjwcmE6h+mKsTJTLZ1Q=",
"checksumSHA1": "d/5DXjf5Y51HztQMibCIMDAIB6o=",
"path": "github.com/shurcooL/githubql",
"revision": "90ae6edce2778dae98524ca8c3622cc76d87a5ba",
"revisionTime": "2017-07-12T02:05:31Z"
"revision": "b3091cd0b2f573f6945eb6f15b0559c06330a1a8",
"revisionTime": "2017-07-25T15:22:08Z"
},
{
"checksumSHA1": "knI7/j/sqbh9tUh5IJ1Alrg0HN8=",
@ -81,6 +81,24 @@
"revision": "5924e6132c2f184e262d4bc779e5745fa297d093",
"revisionTime": "2017-07-17T04:21:40Z"
},
{
"checksumSHA1": "EV7MtBnHXibWMg4clfY118168kM=",
"path": "github.com/shurcooL/graphql",
"revision": "52ce28a2c9fdfbdb3377232422c7915fa04b678a",
"revisionTime": "2017-07-25T16:20:00Z"
},
{
"checksumSHA1": "cBmux8EtRW7A/zcYHn4ABYWjA6U=",
"path": "github.com/shurcooL/graphql/ident",
"revision": "52ce28a2c9fdfbdb3377232422c7915fa04b678a",
"revisionTime": "2017-07-25T16:20:00Z"
},
{
"checksumSHA1": "lRm7JhQAe9p+ie6OIsT16O2HAQw=",
"path": "github.com/shurcooL/graphql/internal/jsonutil",
"revision": "52ce28a2c9fdfbdb3377232422c7915fa04b678a",
"revisionTime": "2017-07-25T16:20:00Z"
},
{
"checksumSHA1": "Y+HGqEkYM15ir+J93MEaHdyFy0c=",
"path": "golang.org/x/net/context",