Граф коммитов

38 Коммитов

Автор SHA1 Сообщение Дата
Jason Vercellone 9ec863b142
Add support for codespaces (#407)
Adds initial support for GitHub Codespaces.

#### References
Endpoints ~~excluded~~ below will be added in subsequent PRs

**[Codespaces/codespaces](https://docs.github.com/en/rest/codespaces/codespaces)**
- [x] [List codespaces in a repository for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#list-codespaces-in-a-repository-for-the-authenticated-user)
- [x] [Create a codespace in a repository](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#create-a-codespace-in-a-repository)
~~[List devcontainer configurations in a repository for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#list-devcontainer-configurations-in-a-repository-for-the-authenticated-user)~~
~~[Get default attributes for a codespace](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#get-default-attributes-for-a-codespace)~~
- [x] [Create a codespace from a pull request](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#create-a-codespace-from-a-pull-request)
- [x] [List codespaces for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#list-codespaces-for-the-authenticated-user)
- [x] [Create a codespace for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#create-a-codespace-for-the-authenticated-user)
- [x] [Get a codespace for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#get-a-codespace-for-the-authenticated-user)
~~[Update a codespace for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#update-a-codespace-for-the-authenticated-user)~~
- [x] [Delete a codespace for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#delete-a-codespace-for-the-authenticated-user)
~~[Export a codespace for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#export-a-codespace-for-the-authenticated-user)~~
~~[Get details about a codespace export](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#get-details-about-a-codespace-export)~~
~~[Create a repository from an unpublished codespace](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#create-a-repository-from-an-unpublished-codespace)~~
- [x] [Start a codespace for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#start-a-codespace-for-the-authenticated-user)
- [x] [Stop a codespace for the authenticated user](https://docs.github.com/en/rest/codespaces/codespaces?apiVersion=2022-11-28#stop-a-codespace-for-the-authenticated-user)

**[Codespaces/organizations](https://docs.github.com/en/rest/codespaces/organizations)**
- [x] [List codespaces for the organization](https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#list-codespaces-for-the-organization)
~~[Manage access control for organization codespaces](https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#manage-access-control-for-organization-codespaces)~~
~~[Add users to Codespaces billing for an organization](https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#add-users-to-codespaces-billing-for-an-organization)~~
~~[Removes users from Codespaces billing for an organization](https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#removes-users-from-codespaces-billing-for-an-organization)~~
- [x] [List codespaces for a user in organization](https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#list-codespaces-for-a-user-in-organization)
- [x] [Delete a codespace from the organization](https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#delete-a-codespace-from-the-organization)
~~[Stop a codespace for an organization user](https://docs.github.com/en/rest/codespaces/organizations?apiVersion=2022-11-28#stop-a-codespace-for-an-organization-user)~~
2023-08-29 10:21:13 -07:00
Neil White 938896738c
Added API versioning support (#379)
GitHub is introducing versioned API's.  In order to get the expected behavior of an API, you need to invoke the API with its version in the request header.  This change updates the core functions (`Invoke-GHRestMethod` and `Invoke-GHRestMethodMultipleResult`) to accept an ApiVersion as part of their param sets so that as the module continues to add new functionality, methods can request the appropriate API Version for their individual calls.

Fixes #377 

Reference: [To infinity and beyond: enabling the future of GitHub’s REST API with API versioning](https://github.blog/2022-11-28-to-infinity-and-beyond-enabling-the-future-of-githubs-rest-api-with-api-versioning/)
[API Versions](https://docs.github.com/en/rest/overview/api-versions?apiVersion=2022-11-28)
2022-12-16 08:29:19 -08:00
Howard Wolosky 1466f1656b
Improve the 404 friendly message (#363)
Doing some clarifying wording in the friendly error message that we add to a 404 to indicate that they could be getting the error because the item truly doesn't exist, not simply due to authentication issues.
2022-12-14 17:21:06 -08:00
Howard Wolosky a2329d6730
Allow callers of Invoke-GHRestMethod[MultipleResult] to specify additional headers (#319)
When experimenting with the the notifications API, it was necessary to be able to specify an additional header (If-Modified-Since).

Making this support generic by allowing callers to specify any number of additional headers to be included with the REST request.
2021-03-20 15:52:37 -07:00
Simon Heather 22e3d7bdf6
GitHubRepositories: Add Get/Set/Remove GitHub Repository Team Permissions (#300)
Adds the following functions:

* `Get-GitHubRepositoryTeamPermission`
* `Set-GitHubRepositoryTeamPermission`
* `Remove-GitHubRepositoryTeamPermission`

References
* [Check team permissions for a repository](https://docs.github.com/en/free-pro-team@latest/rest/reference/teams#check-team-permissions-for-a-repository)
* [Add or update team repository permissions](https://docs.github.com/en/free-pro-team@latest/rest/reference/teams#add-or-update-team-repository-permissions)
* [Remove a repository from a team](https://docs.github.com/en/free-pro-team@latest/rest/reference/teams#remove-a-repository-from-a-team)

Resolves #307
2020-12-24 12:54:03 -08:00
Howard Wolosky c92d8a64eb
Fix potential call depth overflow error when retrying a 202 response (#294)
GitHub will return back a `202` response when the result for the query is not yet ready.  GitHub requests that we "give the job a few moments to complete, and then submit the request again."

We already had the configuration value `RetryDelaySeconds` which covered how many seconds we would sleep before trying the request again. We tried the request again via a recursive call to `Invoke-GHRestMethod`.

It turns out that there's something going on with GitHub right now, and trying to get contributor statistics for a completely new repository never returns back a 200, even after 145 retry attempts over 72 minutes.

That many recursive calls ends up causing a call depth overflow exception with PowerShell.  While this scenario should be an edge-case, nonetheless it seems better to remove the possibility of this error from occurring by modifying the retry logic to be a loop rather than a recursive call.

I've also added a new configuration value: `MaximumRetriesWhenResultNotReady` to help control and limit the number of retries that we'll attempt in this situation, ultimately throwing an exception if the retry limit is exceeded without a 200 response.

Finally, I've disabled the `When getting Github Repository Contributors with Statistics` test until the problem is fixed on the GitHub end.  I've disabled the test by commenting the test out vs using the disable keyword to avoid the Pester failure for disabled tests, and I've opened a [support issue](https://github.community/t/unable-to-retrieve-contributor-statistics-for-a-brand-new-repo/136658) on this problem.
2020-10-08 12:56:37 -07:00
Howard Wolosky ab536c772a
Add missing .SYNOPSIS to functions (#293)
Now that we are generating help documentation for the module, we want to ensure that we have a .SYNOPSIS for every function CBH.
2020-10-05 00:25:32 -07:00
Howard Wolosky db111559f9
Removing NoStatus from the module (#274)
The `NoStatus` parameter (and `DefaultNoStatus` config value) were deprecated as part of #253 when we stopped showing status except for multi-page requests that exceeded some minimum number of pages.

At that time, `NoStatus` (and `DefaultNoStatus`) were not removed in order to minimize the churn to the module.  However, keeping it in is adding unnecessary complexity to the module as we continue to expand what the module can do.

This change removes `NoStatus` (and `DefaultNoStatus`) from the module entirely.  The only impact that this may cause is with users who are currently using one (or both) of them.  This breaking change impact should be minimal, but its best for the breaking change to be part of the coming release which already has a number of other breaking changes as well, as opposed to having more breaking changes in a successive release.
2020-08-11 20:03:33 -07:00
Simon Heather 2f16de1f46
PowerShellForGitHub: Improve and Standardise WhatIf/Confirm Processing (#254)
Improves and standardizes the WhatIf/Confirm ('ShouldProcess') processing across all the functions.

* Moved the `$PSCmdlet.ShouldProcess` check out of `Invoke-GHRestMethod` and added it to the calling functions with the correct operation and target.
* Added `WhatIf:$false` and `Confirm:$false` to the `Out-File` Cmdlet call in the `Write-Log` function in the Helpers module. This will prevent the `Write-Log` function displaying `WhatIf` and `Confirm` prompts.
* Removed `ShouldProcess` from non-state changing functions.
* Modified the current `ShouldProcess` conditions to use an early return.
* Modified the `Set-GitHubIssueLabel` function to remove `ConfirmImpact='High'` and set `ConfirmPreference` to 'Low' if no labels have been specified instead.
* Modified the `Update-GitHubRepository` function to remove `ConfirmImpact='High'` and set `ConfirmPreference` to 'Low' if the repo is being renamed instead.
2020-08-03 14:26:23 -07:00
Simon Heather 981b85c2d4
New GitHubRepositoryBranchProtectionRule Functions (#255)
Adds the following GitHub Branch Protection Rule functions:

- `Get-GitHubRepositoryBranchProtectionRule`
- `New-GitHubRepositoryBranchProtectionRule`
- `Remove-GitHubRepositoryBranchProtectionRule`

References:
- [Get Branch Protection](https://developer.github.com/v3/repos/branches/#get-branch-protection)
- [Update Branch Protection](https://developer.github.com/v3/repos/branches/#update-branch-protection)
- [Delete Branch Protection](https://developer.github.com/v3/repos/branches/#delete-branch-protection)
2020-07-31 15:42:25 -07:00
Howard Wolosky 92c4aa8b3a
Add support for gists (#172)
This completes the required work to support the full set of API's around gists.

It adds the following functions:
* `Get-GitHubGist`
* `Remove-GitHubGist`
* `Copy-GitHubGist` (aka. `Fork-GitHubGist`)
* `Add-GitHubGistStar`
* `Remove-GitHubGistStar`
* `Set-GitHubGistStar` (just a wrapper around `Add/Remove-GitHubGistStar`
* `Test-GitHubGistStar`
* `New-GitHubGist`
* `Set-GitHubGist`
   * `Rename-GitHubGistFile` (exposed helper function)
   * `Remove-GitHubGistFile` (exposed helper function)
   * `Set-GitHubGistFile` (exposed helper function, also known as `Add-GitHubGistFile`)
* `Get-GitHubGistComment`
* `Set-GitHubGistComment`
* `New-GitHubGistComment`
* `Remove-GitHubGistComment`

This also adds formatters for all newly introduced types: `GitHub.Gist`, `GitHub.GistCommit`, `GitHub.GistDetail`, and `GitHub.GistFork`.

Positional Binding has been set as `false`, and `Position` attributes added to the functions' mandatory parameters.

References:
[GitHub Gist](https://developer.github.com/v3/gists/)
[GitHub Gist Comments](https://developer.github.com/v3/gists/comments/)

Fixes #32
2020-07-20 15:07:58 -07:00
Howard Wolosky 356af2f5b6
Complete support for Releases API (#177)
This completes the required work to support the set of Releases API's.

It adds the following functions:

* `New-GitHubRelease`
* `Set-GitHubRelease`
* `Remove-GitHubRelease`
* `Get-GitHubReleaseAsset`
* `New-GitHubReleaseAsset`
* `Set-GitHubReleaseAsset`
* `Remove-GitHubReleaseAsset`

`Invoke-GHRestMethod` has been updated to be able to upload a file (via the new `InFile` parameter) and download a file (via the `Save` switch which will cause it to return back a `FileInfo` object of a temporary file which can then be renamed as seen fit by the caller).

This also adds formatters for `GitHub.Release` and `GitHub.ReleaseAsset`.

Positional Binding has been set as `false` for the three functions, and `Position` attributes added to the function's mandatory parameters.

Reference: [GitHub Releases](https://developer.github.com/v3/repos/releases/)


Fixes #47 
Fixes #110
2020-07-20 08:48:48 -07:00
Howard Wolosky 402529aa8d
Attempting to increase reliability of some Pester tests - take 2 (#268)
This is re-implementing #265 in a more robust way, thanks to a suggestion from @X-Guardian in #267.

Instead of adding in one-off sleeps throughout the test codebase, there is now a new configuration value `StateChangeDelaySeconds`) that will allow us to insert a delay before returning the result of _any_ state change request.

This should ideally consistently add reliability throughout the entire test codebase.
2020-07-19 11:35:40 -07:00
Howard Wolosky 2740026e64
Reimagining status for the module (#253)
* Reimagining status for the module

Status for commands was originally added to this module based on my experience with other REST API's where individual commands could easily take 10-20 seconds.

Practical usage has shown that most GitHub requests in reality take under one second.  The additional work that PowerShell has to do in order to display progress to the user can easily make the overall command take 4-6 times longer than its actual execution time.

Therefore, status is being ripped out of this module (for the most part).  `Invoke-GHRestMethod` and `Invoke-SendTelemetryEvent` no longer have bifurcating execution paths based on the value of `$NoStatus`.  Everything runs synchronously now on the command prompt.

* `DefaultNoStatus` has been deprecated.  Its value will be ignored.
* The `NoStatus` switch has not been removed from the module commands in order to avoid a breaking change.  It may be removed in a future update.
* `Invoke-GHRestMethod -ExtendedResult` has been updated to include the next page's number and the total number of pages for the REST request.
* A new configuration value has been added: `MultiRequestProgressThreshold
  `Invoke-GHRestMethodMultipleResult` will display a ProgressBar to the user tracking the number of remaining requests for the overall execution of the requested command based on this threshold value.  It will only display the progress bar if the number of requets needed meets or exceeds this threshold value.  This defaults to 10, and can be disabled with a value of 0.  
  Practical usage has shown that this adds less than a second of additional time to the overall execution of a multi-request command (quite different than the previous status).
* `Wait-JobWithAnimation` has been removed since it's no longer used.

Fixes #247
2020-06-30 15:05:08 -07:00
Giuseppe Campanelli 618398eedd
Save & restore the state of [Net.ServicePointManager]::SecurityProtocol (#240)
[Net.ServicePointManager]::SecurityProtocol is a global configuration that was being modified during the execution of `Invoke-GHRestMethod`.  With this change, the global state will be cached before the change and restored immediately afterwards.

Fixes #230
2020-06-18 12:44:16 -07:00
Howard Wolosky 17f6122d78
Adding complete Pipeline support to the entire module (#242)
# Description

Comprehensively adds pipeline support throughout the entire module

This change required examining every method, and in some cases a few breaking changes (noted below) had to be introduced in order to make support work consistently end-to-end.  UT's were added for every function, which resuled in a few bugs that were identified and fixed (also noted below).

## Breaking changes
### Unavoidable Breaks
 * `Get-GitHubRepositoryBranch`: `Name` parameter is now `BranchName`.
  > A `GitHub.Repository` object has a `name` property which is the name of the repo.  Piping in the repo object to this method would confuse it, making it search for a branch with the name of the repo, as opposed to the desired effect of just listing out all branches in the repo.

 * `*-GitHub*Label`: `Name` parameter is now `Label`.
  > Similar to above.
  > `Name` was too generic and was causing unintended conflicts when passing in certain objects over the pipeline (like a `GitHub.Repository`) which also has a `name` property, making it impossible to pipe in a repository to list all labels (since it was trying to query for a label in that repository named the same as the repo.

 * `*-GitHubLabel`: `Milestone` parameter is now `MilestoneNumber`.
  > A `GitHub.Issue` contains a `milestone` object property, and PowerShell was complaining that there was no way to convert that to an `[int64]` when an Issue was passed in via the pipeline.  The only way to avoid this was to use `MilestoneNumber` which is the name of the property we add to `GitHub.Milestone` objects, and it's what we alias to in all other methods that interact with milestones.

 * `*-GitHubIssue`: `Milestone` parameter is now `MilestoneNumber`.
  > A `GitHub.Issue` contains a `milestone` object property, and PowerShell was complaining that there was no way to convert that to an `[int64]` when an Issue was passed in via the pipeline.  The only way to avoid this was to use `MilestoneNumber` which is the name of the property we add to `GitHub.Milestone` objects, and it's what we alias to in all other methods that interact with milestones.

 * `Get-GitHubLicense`: `Name` parameter is now `Key`.
  > The `key` is what you can query against, but a License object has _both_ a `name` and a `key` property, which caused piped object queries to fail with the existing parameter name.
 
 * `Get-GitHubCodeOfConduct`: `Name` parameter is now `Key`.
  > Similar to above.
  > The `key` is what you can query against, but a Code of Conduct object has _both_ a `name` and a `key` property, which caused piped object queries to fail with the existing parameter name.
 
 * `New-ProjectCard`: Signature has changed.  Instead of specifying `ContentId` and `ContentType`, you now just directly specify either `IssueId` or `PullRequestId`.
  > Pipeline input would not have worked without this change. Additionally, this simply provides a cleaner interface for users in general, requiring one less input.
 
 * `Get-GitHubUserContextualInformation`: Signature has changed.  Instead of specifying `SubjectId` and `SubjectType`, you now just directly specify either `OrganizationId`, `RepositoryId`, `IssueId` or `PullRequestId`.
  > Similar to above.
  > Pipeline input would not have worked without this change. Additionally, this simply provides a cleaner interface for users in general, requiring one less input.
 

### Breaks With Workarounds
 * A number of changes to the Comments functions
    * `GitHubComments.ps1` was renamed to `GitHubIssueComments.ps1` given that there are 5 different types of comments, these functions focus on `Issue` comments, and there doesn't currently appear to be a path forward for creating a single unified API set for all comment types.

    * All of these methods were renamed from `*-GitHubComment` to `*-GitHubIssueComment`, however they were also aliased back to their previous names (for now).  You should really migrate to these new names however.

    * The main parameter was renamed from `CommentId` to `Comment`, however it was aliased back to `CommentId`.

 * `*-GitHubProject`: `ArchivedState` parameter is now `State` (but aliased back to `ArchivedState` to help with migration).

 * `*-GitHubProject`: `Name` parameter is now `ColumnName` (but aliased back to `Name`)

 * `*-GitHubProjectColumn`: `Name` parameter is now `ColumnName` (but aliased back to `Name`)

 * `Move-GitHubProjectCard`: `ColumnId` parameter is now `Column` (but aliased back to `ColumnId` to support pipeline input).

 * `Get-GitHubRelease`: `ReleaseId` parameter is now `Release` (but aliased back to `ReleaseId` to support pipeline input).
 
 * `Rename-GitHubRepository` has been effectively deprectaed.  It was built on top of the same endpoint that `Set-GitHubRepository` uses, but was only modifying a single property (the name).  For now, the function remains, but it now just internally calls into `Set-GitHubRepository` to perform the same action.
 
 * `Set-GitHubRepositoryTopic`: `Name` parameter is now `Topic` (but aliased back to `Name`).
 
 * `Get-GitHubUser`: `User` parameter is now `UserName` (but aliased back to `User` and `Name`).

 * `Get-GitHubUserContextualInformation`: `User` parameter is now `UserName` (but aliased back to `User` and `Name`).

## Bug Fixes:
 * Events had been using a typo'd version of the `sailor-v` AcceptHeader.  This was fixed as part of the migration to using the AcceptHeader constants.
 * `Lock-GitHubIssue` was not correctly providing the `lock_reason` value to the API, so that metadata was getting lost.  This was caught by new UT's and then fixed.
 * `Update-GitHubLabel` was modified to accept colors both with and without a leading # sign, just like `New-GitHubLabel` already supported.
 
## New Features:
 * `Get-GitHubGitIgnore` has a new `RawContent` switch which allows you to directly get back the content of the actual .gitignore file.
 * `Set-GitHubRepository` has been updated to allow users to change the name (rename) the repository at the same time as making any of their other changes.  If a new name has been specified, users will be required to confirm the change, or to specify `-Confirm:$false` and/or `-Force` to avoid the confirmation.
 * `Get-GitHubRepositoryCollaborator` has gained a new parameter `Affiliation` allowing you to filter which collaborators you're interested in querying for.

## Minor updates:
 * Fixed the casing of the "microsoft" OwnerName in any examples
 * Fixed the casing of `GitHub` in the `Assignee` method names (was `Github` intead of `GitHub`
 * Added new configuration property (`DisablePipelineSupport`) to assist with pipeline development
 * All `AcceptHeader` usage has migrated to using script-wide constants
 * `Split-GitHubUri` can now return both components in a single function call if no switch is specified.
 * Added `Join-GitHubUri` which can reverse what `Split-GitHubUri` does, based on the configured `ApiHostName`.
 * Adds type information (via `.OUTPUTS` and `[OutputType()]` for every function.
 * Documentation updates reflecting the new pipeline support.

## Test changes:
 * `Set-StrictMode -Version 1.0` has been specified for all tests to catch access to undeclared variables (which should help catch common typo errors)
 * The workarounds for PSScriptAnalyzer's false complaint for rule `PSUseDeclaredVarsMoreThanAssignments` have been removed, and all test files now suppress that rule.
 * A test file now exists for every module file, and some tests were moved around to the appropriate file (away from GitHubAnalytics.tests.ps1 which had previously been a dumping ground for tests).
 * A _substantial_ number of new tests have been added.  Every function should now be tested with limited exceptions (like for Organizations and Teams where we don't yet have the support in the module to get the account in the appropriate state to be able to query with those existing functions).
  
> Note: These tests fully pass with Pester 4.10.1.  Some additional work may be done prior to merging to get them passing with Pester 5.0, but the priority is to get this merged into master soon in order to unblock the pipeline of existing pull requests that have been waiting on this change.

#### Issues Fixed
- Fixes #63

#### References
[The whole API set](https://developer.github.com/v3/)
2020-06-17 22:26:59 -07:00
Howard Wolosky 78187766f0
Improve performance of Get-GitHubContent (#232)
The call to `ConvertTo-SmarterObject` was adding a significant amount of time to the execution of Get-GitHubContent.

```powershell
    Set-GitHubConfiguration -DisableSmarterObjects:$false
    Measure-Command { $c = Get-GitHubContent -OwnerName microsoft -RepositoryName PowerShellForGitHub -Path README.md }
    # This averages to be around 1.2 seconds

    Set-GitHubConfiguration -DisableSmarterObjects:$true
    Measure-Command { $c = Get-GitHubContent -OwnerName microsoft -RepositoryName PowerShellForGitHub -Path README.md }
    # This averages to be around 14 seconds
```

The reasoning behind this was that the return of `Invoke-WebRequest` for this repo's `README.md` was an array of [int32] that contained 22,000+ entries (one byte per entry).  Because the array was created by `ConverFrom-Json`, each `[int32]` was also an `[object]`, which meant that it was considered a `[PSCustomObject]` inside of `ConverTo-SmarterObject`, which caused it to do a lot of unnecessary work. Piping in 22,000 objects and doing all of that unnecessary work to end up just calling `Write-Output` on the original value took a _lot_ of time.

The fix here was to skip trying to convert the result to a smarter object if it wasn't going to be a convertible object in the first place.

I also added in protection directly to `ConverTo-SmarterObject` as well.  It made things better than the current runtime, but still twice as slow as not calling it in the first place (average runtime of above command was 3.5 seconds when we allowed it to go into the command and then do nothing).

This doesn't end up saving much time with the execution of `Tests/GitHubContents.tests.ps1` because the file being returned is so small, but this should have some nice user experience improvements in practical usage.
2020-06-10 14:32:05 -07:00
Simon Heather 6e794cbcaf
PowerShellForGitHub: Disable Progress Bar for Invoke-WebRequest (#229)
Disables the PowerShell progress bar for the `Invoke-WebRequest` cmdlet calls in the `Invoke-GHRestMethod` and `Invoke-SendTelemetryEvent` functions due to known performance issues in PowerShell 5.1.

Reference: 
[Progress bar can significantly impact cmdlet performance.](https://github.com/PowerShell/PowerShell/issues/2138)

Fixes #227
2020-06-10 11:00:18 -07:00
Howard Wolosky ae8467f74a
Removing binary dependencies for telemetry (#186)
This reverse engineers the REST API for Application Insights so that
we no longer need to download / depend on the 3 .dll files that were
necessary to use the Application Insights .NET SDK.

As a result, this also removes the `AssemblyPath` configuration property
since there are no longer any assemblies that this module needs.
2020-06-01 13:56:03 -07:00
Howard Wolosky ad15657551
Fix handling of -WhatIf in core functions (#213)
WhatIf support has now been simiplified in all API's that eventually
call into `Invoke-GHRestMethod`.  There's now a single check at the
top of that function which checks if it should continue or not.  If it
shouldn't, it early returns in order to avoid any code that might access
uninitialized content from outside of the ShouldProcess blocks later on.

Resolves #197
2020-06-01 12:48:01 -07:00
Howard Wolosky a9f48a8aec
Add automatic daily update checking (#185)
The module will now check daily with PowerShellGallery to see if there
is a newer version of the module available.  This check can be disabled
with the new `DisableUpdateCheck` config property.

The check happens asynchronously.  The web request is kicked off when
the module is loaded, but the result is only checked when the user
runs a command.

The result is logged at the Verbose level in any failure case as well
as when the module is up-to-date.  When there is a newer version
available, it will write the message out as a Warning.  The web request
will only run once per day, and the user message will only be written
once per day as well.
2020-05-30 16:30:38 -07:00
Howard Wolosky bcd0a5616e
Fix multi-result behavior across all versions of PowerShell (fixes CI UT's on all platforms) (#199)
Tests were failing on Mac and Linux, but not Windows ([recent test run](https://dev.azure.com/ms/PowerShellForGitHub/_build/results?buildId=83887&view=logs&j=0da5d1d9-276d-5173-c4c4-9d4d4ed14fdb)).  That's because Windows CI was running against PoSh 5.x while Linux and Mac were running on PoSh 7.x.

There's a slight difference in behavior for how those two treat arrays.

The real root cause for this was the behavior of `Invoke-GHRestMethodMultipleResult`.  When creating `$finalResult`, it was always blindly adding the result to the existing array:

587e204262/GitHubCore.ps1 (L648)
`...`
587e204262/GitHubCore.ps1 (L670)

Oddly enough, this created a difference in behavior between PowerShell versions when making the result an array on the caller side.  Now I ensure that I don't add anything to `$finalResult` unless there's actually a value.  With that change, we can now be sure that when we grab the result as an array, it'll be appropriately empty or populated (and not populated with a single `$null` entry, thus making `Count` 1, erroneously).

I removed the attempt to force the results to be an array, because this is pointless.  PowerShell will always unwrap an array of 0 or 1 in a return result. If you want to ensure that a result is always an array, you have to [wrap the result in an object](https://stackoverflow.com/a/60330501) or you have to do wrap the result in an array on the caller side.

587e204262/GitHubCore.ps1 (L684-L685)

I also normalized some naming in all of the tests, so that when we're getting back a singular result (by querying for a specific item) that we use a singular variable name, and a plural variable name otherwise.

With this change, we should now be passing CI on all OS platforms and across PowerShell 4+.

Resolves #198
2020-05-30 15:42:04 -07:00
Howard Wolosky b7e1ea1cb9
Get PSScriptAnalyzer clean again (#180)
Somehow a number of PSScriptAnalyzer issues snuck in.  This fixes them.

The main PSScriptAnalyzer issues needing to be fixed were:
 * `PSReviewUnusedParameter` - This one came up a lot due to our heavy
    usage of `Resolve-RepositoryElements` and `Resolve-ParameterWithDefaultConfigurationValue`
    which both end up referencing their parameters by grabbing them off
    the stack.  That means that `NoStatus` and `Uri` are frequently
    never directly referenced.  So, exceptions were added.  There were
    two cases (in GitHubAnalytics) where there was a false positive due
    to PowerShell/PSScriptAnalyzer#1472

 * `PSUseProcessBlockForPipelineCommand` - We had a number of functions
   that took pipeline input, but didn't actuall use the `process` block.
   This actually caught a bug with `Group-GitHubIssue` and
   `Group-GitHubPullRequest`.  Added correct `process` block usage for
   most of the functions, but removed pipeline support for those where
   it didn't actually make sense anymore.

 * `PSUseDeclaredVarsMoreThanAssignments` - These are false positives
   in the Pester tests due to the usage of `BeforeAll`.  There wasn't
   an obvious way to use `SuppressMessageAttribute` in the Pester test,
   so I used a hacky workaround to "use" the variable in the `BeforeAll`
   block.  I could have added the suppression to the top of the file,
   but I still want to catch real issues in those files later.

 * `PSAvoidOverwritingBuiltInCmdlets` - It turns out that there's a bug
   with PSDesiredStateConfiguration in PS Core 6.1.0 where it was exporting
   internal functions.  This was thus a false-postive flag for Write-Log.
   See PowerShell/PowerShell#7209 for more info.

Also, it turns out that `Group-GitHubPullRequest` hadn't actually been
exported, so I fixed that too.
2020-05-26 08:01:17 -07:00
Howard Wolosky c4c1ec344a
Fix the behavior of Get-GitHubRepository (#179)
There were a few problems with this function:
* -GetAllPublicRepositories didn't actually work.  That's now been fixed,
  and support for the optional Since paramater has been added as well.
* Fixed the ParameterSet handling for all of the parameters to make sure
  that users can only specify parameters relevant with the appropriate
  parameter set given that there are five different use cases for this
  method:
     * Getting repos for the current authenticated user
     * Getting repos for any GitHub user
     * Getting repos for an organization
     * Getting all public repos)
     * Getting a specific GitHub repo

Resolves #178
2020-05-25 15:34:32 -07:00
Jess Pomfret 6735ba57a5
spelling fixes (#165) 2020-05-07 15:04:51 -07:00
Shannon Deminick 9a45908dc6
Adding Get Repository.Contents functionality (#146)
Adds `Get-GitHubContent` and corresponding tests.

Also adds formatting files for VS Code and EditorConfig.
2020-04-03 11:13:53 -07:00
Kiran Reddy f7b956da4a Fix hostname support for Enterprise installations of GitHub (#118)
Per the [documentation](https://developer.github.com/enterprise/2.16/v3/#current-version), enterprise installations support a base URL of  `http(s)://[hostname]/api/v3` in addition to the existing support of `http(s)://api.[hostname]/`.  This PR updates the module to _always_ use the `http(s)://[hostname]/api/v3` syntax when `[hostname]` is _not_ `github.com`.

Fixes #117
2019-07-16 15:02:45 -05:00
Cliff Chapman d5acd0f73d Add URL config for GitHub Enterprise (#101)
Adds the ability to supply a new configuration parameter (ApiHostName) in order to support GitHub Enterprise users.

ApiHostName will default to github.com. GitHub Enterprise installs to a different URL and the API remains as api.somegithub.com, thus it's simple to hit that API on a different base URL.

Fixed a related typo in the documentation as well.

Resolves #98
2019-04-11 12:12:01 -07:00
Howard Wolosky 592167de9b Update Split-GitHubUri to work with the `api.github.com` URI's as well
These can be seen when running `Get-GitHubIssue` and looking at:

* `url`
* `repository_url`
* `labels_url`
* `comments_url`
* `events_url`
2019-02-07 10:50:10 -08:00
Pepe Rivera e3b6c53017 Add ability to specify a MediaType for issues (#83)
Updates Issues API's to have a configurable MediaType.
2019-01-16 11:18:24 -08:00
Howard Wolosky 185441078e Fix all string parameters to be CamelCased and avoid abbreviation
Updated all parameter sets to use `CamelCased` inputs, and adjusted their usage
internally to still conform to the API requirements.

Made minor documentation changes related to these udpates.

Resolves #65: Fix all string parameters to be CamelCased and avoid abbreviation
2019-01-03 15:27:54 -08:00
Howard Wolosky 98aec29d61
Add `LogRequestBody` configuration option to make development debugging easier (#60)
* Add `LogRequestBody` configuration option to make development debugging easier

If enabled, the JSON-serialized version of the body of any REST request will
be written to verbose output, so that you can see exactly what is being sent
to GitHub.
2018-12-04 20:06:34 -08:00
Pepe Rivera 28b314bd7c Add support for comment APIs (#53)
Add support for the [Issue Comments](https://developer.github.com/v3/issues/comments/) API's.
2018-11-30 15:00:22 -08:00
Pepe Rivera 680696a833 Add support for assignee APIs (#54)
Adds support for the [Issues Assignees](https://developer.github.com/v3/issues/assignees/) API's
2018-11-30 14:47:14 -08:00
Howard Wolosky 6cf344fb38
Prevent `ConvertTo-SmarterObject` from flattening arrays (#56)
* Ensure that `ConvertTo-SmarterObject` does not cause any side-effects on `InputObject`
* Ensure that `ConvertTo-SmarterObject` does not flatten any arrays
* Switched all calls of `ConvertTo-Json` to not use pipelining in order to avoid PowerShell's
  array-flattening logic when piping the InputObject in, as opposed to when passing it as a parameter.
* Ensured that we do best-effort Date conversion in `ConvertTo-SmarterObject` (a failed date conversion
  should never cause an exception/failure).
* Used a workaround described in [Pester's Wiki](# https://github.com/pester/Pester/wiki/Testing-different-module-types)
  to force the module to be a `Script Module` instead of a `Manifest Module` so that `Mock` and
  `InModuleScope` (which lets you test private methods) work.
* Added UT's for `ConvertTo-SmarterObject` core scenarios.

Resolves PowerShell#55: ConvertTo-SmarterObject is flattening arrays

Thanks to @DanBelcher-MSFT for the assist on this one.
2018-11-30 11:26:13 -08:00
Howard Wolosky 695845101f
Update helper methods to grab appropriate default values from previous scope (#52)
* Updated `Resolve-ParameterWithDefaultConfigurationValue` and `Resolve-RepositoryElements`
  to grab `$PSBoundParameters` from the previous (calling) scope if not provided.

* Updated `Write-InvocationLog` to grab `$MyInvocation` from the previous (calling) scope
  if not explicitly provided.

In all cases, this will simpliy the standard calling pattern for these functions.
2018-11-19 13:07:05 -08:00
Howard Wolosky 1076239d76 Add support for querying and creating forks
Pull Request #31 was adding support for getting forks using
the old module structure.

I've gone ahead and added the requested functionality using
the new module layout, and additionally added support for
creating new forks, along with tests for both.
2018-11-13 02:51:00 -08:00
Howard Wolosky eb33688e5b Module restructure to v0.2.0
+ Significant restructing and refactoring of entire module to make future expansion easier.
+ Significant documentation updates ([CHANGELOG](./CHANGELOG.md), [CONTRIBUTING.md](./CONTRIBUTING.md),
  [GOVERNANCE.md](./GOVERNANCE.md), [README.md](./README.md), [USAGE.md](./USAGE.md))
+ Added `Set-GitHubAuthentication` (and related methods) for securely caching the Access Token
+ Added `Set-GitHubConfiguration` (and related methods) to enable short and long-term configuration
  of the module.
+ Added ability to asynchronously see status update of REST requests.
+ Added logging and telemetry to the module (each can be disabled if desired).
+ Tests now auto-configure themselves across whatever account information is supplied in
  [Tests/Config/Settings.ps1](./Tests/Config/Settings.ps1)
+ Added support for a number of additional GitHub API's:
  + All [Miscellaneous API's](https://developer.github.com/v3/misc/)
  + Ability to fully query, update, remove, lock, and unlock Issues.
  + Enhanced pull request querying support
  + Ability tofully query, create, and remove Repositories, as well as transfer ownership,
    get tags, get/set topic and current used programming languages.
  + Enhanced user query support as well as being able update information for the current user.

* Made parameter ordering consistent across all functions (OwnerName is now first, then RepositoryName)
* Normalized all parameters to use SentenceCase
* All functions that can take a Uri or OwnerName/RepositoryName now support both options.
* Made all parameter names consistent across functions:
  * `GitHubAccessToken` -> `AccessToken`
  * `RepositoryUrl` -> `Uri`
  * `Organization` -> `OrganizationName`
  * `Repository` -> `RepositoryName`
  * `Owner` -> `OwnerName`
* Normalized usage of Verbose, Info and Error streams

- `New-GitHubLabels` was renamed to `Set-GitHubLabel` and can now optionally take in the labels
  to apply to the Repository.
- `Get-GitHubIssueForRepository` has been removed and replaced with `Get-GitHubIssue`.
  The key difference between these two is that it no longer accepts multiple repositories as single
  input, and filtering on creation/closed date can be done after the fact piping the results into
  `Where-Object` now that the returned objects from `Get-GitHubIssue` have actual `[DateTime]` values
  for the date properties.  For an updated example of doing this, refer to [example usage](USAGE.md#querying-issues).
- `Get-GitHubWeeklyIssueForRepository` has been removed and functionally replaced by `Group-GitHubIssue`.
  For an updated example of using it, refer to [example usage](USAGE.md#querying-issues)
- `Get-GitHubTopIssueRepository` has been removed.  We have [updated examples](USAGE.md#querying-issues)
  for how to accomplish the same scenario.
- `Get-GitHubPullRequestForRepository` has been removed and replaced with `Get-GitHubPullRequest`.
  The key difference between these two is that it no longer accepts multiple repositories as single
  input, and filtering on creation/merged date can be done after the fact piping the results into
  `Where-Object` now that the returned objects from `Get-GitHubPullRequest` have actual `[DateTime]` values
  for the date properties.  For an updated example of doing this, refer to [example usage](USAGE.md#querying-pull-requests).
- `Get-GitHubWeeklyPullRequestForRepository` has been removed and functionally replaced by `Group-GitHubPullRequest`.
  For an updated example of using it, refer to [example usage](USAGE.md#querying-pull-requests)
- `Get-GitHubTopPullRequestRepository` has been removed.  We have [updated examples](USAGE.md#querying-pull-requests)
  for how to accomplish the same scenario.
- `Get-GitHubRepositoryNameFromUrl` and `GitHubRepositoryOwnerFromUrl` have been removed and
  functionally replaced by `Split-GitHubUri`
- `Get-GitHubRepositoryUniqueContributor` has been removed.  We have an
  [updated example](USAGE.md#querying-contributors) for how to accomplish the same scenario.
- `GitHubOrganizationRepository` has been removed.  You can now retrieve repositories for an
  organization via `Get-GitHubRepository -OrganizationName <name>`.
- `Get-GitHubAuthenticatedUser` has been replaced with `Get-GitHubUser -Current`.

Fixes Issue #34: Warning output on import is being written out twice
Fixes Issue #33: TLS error in Get-GitHubIssueForRepository : Failed to execute query with exception
Fixes Issue #26: Token in template file
Fixes Issue #24: Add a command for configuration
2018-11-13 01:49:21 -08:00