Giter Site home page Giter Site logo

powershellforgithub's Introduction

PowerShellForGitHub PowerShell Module

[GitHub version] powershellgallery downloads GitHub code size in bytes downloads CII Best Practices tweet
Build status Azure DevOps tests Azure DevOps coverage
Help Wanted Issues GitHub last commit

Table of Contents


Overview

This is a PowerShell module that provides stateless command-line interaction and automation for the GitHub v3 API.

Embracing the benefits of PowerShell, it has full support for pipelining, allowing you pipe the output of virtually any command into any other command within the module.


What's New

Check out CHANGELOG.md to review the details of the current release as well as all past releases.


Current API Support

At present, this module can:

Development is ongoing, with the goal to add broad support for the entire API set.

For a comprehensive look at what work is remaining to be API Complete, refer to Issue #70.

Review examples to see how the module can be used to accomplish some of these tasks.


Installation

You can get latest release of the PowerShellForGitHub on the PowerShell Gallery

Install-Module -Name PowerShellForGitHub

Configuration

To avoid severe API rate limiting by GitHub, you should configure the module with your own personal access token.

  1. Create a new API token by going to https://github.com/settings/tokens/new (provide a description and check any appropriate scopes)
  2. Call Set-GitHubAuthentication, enter anything as the username (the username is ignored but required by the dialog that pops up), and paste in the API token as the password. That will be securely cached to disk and will persist across all future PowerShell sessions. If you ever wish to clear it in the future, just call Clear-GitHubAuthentication).

For automated scenarios (like GithHub Actions) where you are dynamically getting the access token needed for authentication, refer to Example 2 in Get-Help Set-GitHubAuthentication -Examples for how to configure in a promptless fashion.

Alternatively, you could configure PowerShell itself to always pass in a plain-text access token to any command (by setting $PSDefaultParameterValues["*-GitHub*:AccessToken"] = "<access token>"), although keep in mind that this is insecure (any other process could access this plain-text value).

A number of additional configuration options exist with this module, and they can be configured for just the current session or to persist across all future sessions with Set-GitHubConfiguration. For a full explanation of all possible configurations, run the following:

Get-Help Set-GitHubConfiguration -ShowWindow

For example, if you tend to work on the same repository, you can save yourself a lot of typing by configuring the default OwnerName and/or RepositoryName that you work with. You can always override these values by explicitly providing a value for the parameter in an individual command, but for the common scenario, you'd have less typing to do.

Set-GitHubConfiguration -DefaultOwnerName PowerShell
Set-GitHubConfiguration -DefaultRepositoryName PowerShellForGitHub

Be warned that there are some commands where you may want to only ever supply the OwnerName (like if you're calling Get-GitHubRepository and want to see all the repositories owned by a particular user, as opposed to getting a single, specific repository). In cases like that, you'll need to explicitly pass in $null as the relevant parameter value as a temporary override for your default if you've set a default for one (or both) of these values.

There are more great configuration options available. Just review the help for that command for the most up-to-date list!

GitHub Enterprise

To set the configuration to use a GitHub Enterprise server instead of GitHub.com, simply supply the ApiHostName parameter with the hostname of your GitHub Enterprise server.

Set-GitHubConfiguration -ApiHostName "github.contoso.com"

Usage

Example command:

$issues = Get-GitHubIssue -Uri 'https://github.com/microsoft/PowerShellForGitHub'

For more example commands, please refer to USAGE.


Developing and Contributing

Please see the Contribution Guide for information on how to develop and contribute.

If you have any problems, please consult GitHub Issues to see if has already been discussed.

If you do not see your problem captured, please file feedback.


Legal and Licensing

PowerShellForGitHub is licensed under the MIT license.


Governance

Governance policy for this project is described here.


Code of Conduct

For more info, see CODE_OF_CONDUCT


Reporting Security Issues

Please refer to SECURITY.md.


Privacy Policy

For more information, refer to Microsoft's Privacy Policy.

powershellforgithub's People

Contributors

bergmeister avatar etgottli avatar giuseppecampanelli avatar howardwolosky avatar jaxxstar avatar jing8956 avatar johnlokerse avatar joseartrivera avatar jpomfret avatar jrolstad avatar jwmoss avatar karolkaczmarek avatar laustta avatar lazywinadmin avatar matt9ucci avatar microsoft-github-policy-service[bot] avatar mtboren avatar przemyslawklys avatar rjmholt avatar shazwazza avatar smaglio81 avatar tedhudek avatar tigerfansga avatar tylerleonhardt avatar v2kiran avatar variableresistor avatar vercellone avatar wikijm avatar x-guardian avatar zjalexander avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

powershellforgithub's Issues

Token in template file

I find it weird having to rename a file in the module and setting the token there. Wouldn't this get overridden on updates? Why can't I just set the token in profile.ps1, with a global variable or better $PSDefaultParameterValues?

And, shouldn't this be a secure string or credential object of some sort instead of a plain string?

Support seamless pipelining of related cmdlets

Many related PowerShell cmdlets are designed to operate off of a common datatype in order to support pipelining, e.g.

Get-ChildItem .. | Remove-Item

So Get-ChildItem outputs a [System.IO.FileInfo] object and Remove-Item is designed to populate it's input either from a [System.IO.FileInfo] object or by explicit named parameter.

The cmdlets in this module should support a similar paradigm, so that related cmdlets can be seamlessly piped to each other, as PowerShell users would expect, e.g.

New-GitHubMilestone ... |
    Update-GitHubIssue -Issue 4 -PassThru |
    Update-GitHubIssue -Issue 10

In this example, the OwnerName, RepositoryName, and Milestone can be inferred based on the presence of the Milestone object in the pipeline.

GitHub Release support

I wrote some PowerShell to publish a GitHub release recently (here) and was wondering if you would like it? It needs changing to work with the conventions of this module, of course, but with some guidance I can do that.

Let me know if you're interested. I haven't exposed any other GitHub Release API support, but could relatively easily.

ConvertTo-SmarterObject is flattening arrays

Hi! When querying the issues using the Get-GitHubIssue command, sub-arrays seem to get flattened. I'm focusing on the labels array that's returned with each issue: sometimes it returns null, sometimes an array (โœ”๏ธ good), and sometimes the array is flattened and a PSCustomObject is returned (โŒ bad).

Test case setup

Two issues, one with multiple labels, one with a single label. I'm using issues in one of my repositories (assigned to the milestone test to make a subset easily filterable) but I believe any other repo will do.

Current behaviour

> (Get-GitHubIssue -OwnerName "QutEcoacoustics" -RepositoryName "audio-analysis" -Milestone 6 -State all) | ConvertTo-Json -Depth 100 | grep -C 3 'labels\": '
DONE - Operation took 4 second(s) [Getting issues for audio-analysis]
      "type": "User",
      "site_admin": false
    },
    "labels": [
      {
        "id": 151803416,
        "node_id": "MDU6TGFiZWwxNTE4MDM0MTY=",
--
      "type": "User",
      "site_admin": false
    },
    "labels": {
      "id": 91215873,
      "node_id": "MDU6TGFiZWw5MTIxNTg3Mw==",
      "url": "https://api.github.com/repos/QutEcoacoustics/audio-analysis/labels/enhancement",

Note that the issue with one label (the second grep result) has an object directly assigned to the labels field instead of an array.

Expected Behaviour

> ((Invoke-WebRequest "https://api.github.com/repos/QutEcoacoustics/audio-analysis/issues?milestone=6&state=all").Content | ConvertFrom-Json | ConvertTo-Json -Depth 100) | grep -C 3 'labels\": '
      "type": "User",
      "site_admin": false
    },
    "labels": [
      {
        "id": 151803416,
        "node_id": "MDU6TGFiZWwxNTE4MDM0MTY=",
--
      "type": "User",
      "site_admin": false
    },
    "labels": [
      {
        "id": 91215873,
        "node_id": "MDU6TGFiZWw5MTIxNTg3Mw==",

Note both labels fields contain an array.

Why is this a problem

If you're only using these values from within PowerShell then it isn't so important because PowerShell supports scalars or arrays pretty transparently.

However, if you have to use any of this data in another language/tool the inconsistent structure (that also deviates from GitHub's API) makes dealing with these values quite difficult.

Why I think the problem is in PowerShellForGitHub

Because essentially, right down in the guts of this module a Invoke-WebRequest and a ConvertFrom-Json are done, just like in my expected behaviour section above. That rules out those cmdlets as being out-right at fault... and I haven't had the time to properly trace the root cause.


Technical details:

  • The version of the module (located in PowerShellForGitHub.psd1)
    • 0.4.0
  • Your OS version
    • Windows 10.0.17134
  • Your version of PowerShell ($PSVersionTable.PSVersion)
    • 6.1.0
    • Also reproduced in 5.1.17134.407

Get-GitHubEvent shouldn't use [int] for EventId

While running UT's, we're seeing the following failure:

Describing Getting an event directly
    Context For getting an event directly

[-] Error occurred in Context block 0ms
        OverflowException: Value was either too large or too small for an Int32.
        PSInvalidCastException: Cannot convert value "2202340851" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
        ArgumentTransformationMetadataException: Cannot convert value "2202340851" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
        ParameterBindingArgumentTransformationException: Cannot process argument transformation on parameter 'EventID'. Cannot convert value "2202340851" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
        at <ScriptBlock>, C:\projects\powershellforgithub\Tests\GitHubEvents.tests.ps1: line 144
        at DescribeImpl, C:\Program Files\WindowsPowerShell\Modules\Pester\4.7.2\Functions\Describe.ps1: line 199

PascalCase parameter names

The current casing is inconsistent:

Get-GitHubIssueForRepository -
repositoryUrl        closedOnOrAfter      Debug                ErrorVariable        OutBuffer            
state                closedOnOrBefore     ErrorAction          WarningVariable      PipelineVariable     
createdOnOrAfter     gitHubAccessToken    WarningAction        InformationVariable  
createdOnOrBefore    Verbose              InformationAction    OutVariable 

Add test automation

Add pester tests for each function.
To tests API in production, create a new sample repository which we will be querying against.

Migrate to Azure DevOps for Pester CI

We have existing issues with the current implementation of Pester CI via AppVeyor. Azure DevOps has come a long way since when this project was first created, and it's time to migrate over to Azure DevOps for execution of the Pester tests. It'll ensure that the tests are always running against this repo and not my fork, as well as ensure that the test output is visible publicly.

Some articles that I've seen which discuss how to do this:

Enhance Get-GitHubRepositoryTag cmdlet by providing ability to filter results by TagName

This module fits very close to what I needed when querying available tags before finally downloading a release asset using the releases api. It would be even better if there was a way to filter out the tag results by providing an optional parameter to Get-GitHubRepositoryTag:

1). [string[]] TagName
When provided, filter the results by tags that have an exact match with values in the array.

I'm intending to use this cmdlet to find the existence of matching tags. When they do exist, then I can call the releases api and filter by assets names to download.

Thanks in advance.

Enhance module by providing ability to query Release assets

Expose the repos/$user/$repo/releases api by returning matching releases by optional tag and optionally filtering out the assets results by name. Signature of the method could look very similar to Get-GithubRepositoryTag but with an optional [string[]] TagName, [string] AssetName, [switch] PreRelease parameters.

  • When TagName parameter is provided, results from the releases api will be filtered by matching tag_name entries in the TagName array.

  • When AssetName is provided, filter the releases/tags assets array for names that match using the -like operator.

  • When PreRelease is provided, do not filter the results from releases api. By default, only show releases where prerelease = false.

I currently have a script using the repos/$user/$repo/releases/tags/$tagname api but for some repositories that have changed their tagname pattern over time (such as rabbitmq/rabbitmq-server), this requires me to resort to a multi-level try catch mechanism in trying one tag value first and retrying with the alternate pattern after detecting a 404 response. Filtering the results from /releases/tags client side is less than ideal from a performance perspective compared to using /releases/tags/$tagname but provide a much better end-user experience.

There are also repositories such as microsoft/vsts-agent (now renamed to microsoft/azure-pipelines-agent) which changed its use of release assets over time. Up thru version 2.126.0, each release entry returned multiple assets and each asset provided a direct link to the binary via browser_download_url. After 2.126.0, there is only one asset result which does not directly link to the binary assets. Instead, the browser_download_url links to an assets.json file whose structure I have to parse before I could download the binary assets.

Suggestion: Add ability to rename a repository; Rename-GitHubRepository?

Firstly, great module.

One minor capability that we can add: the ability to rename a repository. While this may not be an everyday activity, there are times when it is a need.

Some answers to the Contributing Suggestions items:

  • What you want to achieve / what is the problem that you want to address:
    Add the ability to rename a GitHub repository. This may be through a new cmdlet like Rename-GitHubRepository, or via a new parameter to the existing Update-GitHubRepository cmdlet

  • What is your approach for solving the problem:
    Until such a time that this module directly supports repo renames, we can use the Invoke-GHRestMethod cmdlet from the module to rename a repository. See the Gist at mtboren/snippets_RenameGitHubRepository.ps1

  • A user scenario of the feature / enhancement in action:
    Let's say that Billy forked repoX, and Billy likes to improve clarity about repos -- he adds the prefix fork_ to the repos that he forks, using the name as an additional indicator/clarifier. So, much like Rename-Item for a filesystem object, he would expect to solve this need by doing something like:

    New-GitHubRepositoryFork -Uri https://github.com/aws-quickstart/quickstart-dotnet-serverless-cicd | Rename-GitHubRepository -NewName billyfork_quickstart-dotnet-serverless-cicd

Looking forward to using this module more

Enhance UT's for GitHubRepositories.ps1

We use a number of the functions within this file throughout the other UT's, but not all of them. There is a lack of comprehensive testing available for all the methods within this file as was recently demonstrated with #134 and #136 (around Update-GitHubRepository).

We should close the gaps on the testing of the functions within this file to increase code coverage and reduce regression possibilities.

GitLab Token issue on ConvertTo-SecureString

Is this module compatible with GitLab?
I have a token that was working with PSGitLab, but I haven't found a clone feature on that module.

I have modified the token, but it looks roughly like the one below:

$secureString = ('abCdEf1gHIJKL2m_123A' | ConvertTo-SecureString)

Results in this error:

ConvertTo-SecureString : Input string was not in a correct format.
At line:1 char:43

  • $secureString = ('abCdEf1gHIJKL2m_123A' | ConvertTo-SecureString)
  •                                       ~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [ConvertTo-SecureString], FormatException
    • FullyQualifiedErrorId : System.FormatException,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

Thanks,
Neal Walters

Fix api url for Github Enterprise

The api url has been coded in the following format:

$url = "https://api.$hostName/$UriFragment"

While this works for github it fails with the enterprise version because the api url is different:

http(s)://[hostname]/api/v3

As a result when you call any of the function referencing Github enterprise you may get the following error:

The remote name could not be resolved: 'api.myghhost.com'
At C:\Program 
Files\WindowsPowerShell\Modules\PowerShellForGitHub\0.8.0\GitHubCore.ps1:520 
char:9
+         throw $newLineOutput
+         ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (The remote name.... 
   com':String) [], RuntimeException
    + FullyQualifiedErrorId : The remote name could not be resolved: 'api.myghhost.com'

Will raise a PR to fix this.

Progress is Incorrectly Displayed

The helper function Wait-JobWithAnimation incorrectly handles progress, and this makes it look quite ugly indeed in the ISE (a spew of non-wrapped yellow lines).

The root of the problem is that you are creating your own Write-Progress. Please use Write-Progress instead, as this is more standard and will be honored across more PowerShell hosts.

The issue reproduces everywhere, but is worst in the PowerShell ISE.
PowerShellForGitHub version: 0.8.0
$psVersionTable
Name Value


PSVersion 5.1.17763.503
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17763.503
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1


To detail the fix:
Create an ID before the while loop (Line 57)

Change your Write-InteractiveHost to Write-Progress (line 94)
Write-Progress "$($animationFrames[$($iteration % $($animationFrames.Length))])" "Elapsed: $([int]($iteration / $framesPerSecond)) second(s)" -PercentComplete $((($iteration % $($animationFrames.Length)) / $animationFrames.Length) * 100) -id $id

Complete the Progress message at the end (lines 101 & 108)

Get rid of your Write-InteractiveHost at the very end

Re-enable disabled tests once automated setup is possible

The following tests have been disabled (in GitHubAnalytics.tests.ps1):

  • Obtaining pull requests for repository
  • Obtaining repository with biggest number of pull requests
  • Obtaining organization members
  • Obtaining organization team
  • Obtaining organization team members

They've been disabled because the module does not yet have the functionality to get the test repository into the necessary state for testing (e.g. it needs to be able to create and delete pull requests, create teams and members, etc...).

Once the necessary functionality has been added to the module, those tests should be re-enabled and this issue can be closed out.

New-GitHubPullRequest

The absolute most important cmdlet for me.
Inspiration in hub pull-request create - will default to the current branch, figure out the repo from the current remote, prefill the message with the last commit message...

Get-GitHubOrganizationRepository goes into infinite loop when org doesn't exist or doesn't have any repositories

If we query against organization which doesn't have any repositories (or doesn't exist), we go into infinite loop

PS C:\git\githubkit> Get-GitHubOrganizationRepository -organization 'GitHubOrgTest123'
You cannot call a method on a null-valued expression.
At C:\git\githubkit\GitHubAnalytics.psm1:941 char:5
+     $nextLinkString = $jsonResult.Headers.Link.Split(',')[0]
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\git\githubkit\GitHubAnalytics.psm1:942 char:5
+     $query = $nextLinkString.Split(';')[0].replace('<','').replace('> ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\git\githubkit\GitHubAnalytics.psm1:950 char:7
+       $nextLinkString = $jsonResult.Headers.Link.Split(',')[0]
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Cannot bind parameter 'Uri'. Cannot convert value "https://DisableLogging:False/api/v3/user" to type "System.Uri". Error: "Invalid URI: Invalid port specified."

Hello,

I was testing the module without any issue.

I played with the set-githubconfiguration disablelogging and disabletelemetry.

Now when I try to use the module I have the below error:
Cannot bind parameter 'Uri'. Cannot convert value "https://DisableLogging:False/api/v3/user" to type "System.Uri". Error: "Invalid URI: Invalid port specified."

I was using the below command:
(Get-GitHubUser -Current).login

I tried to uninstall the module then install it again and still same issue.
I can't use the module anymore.

I tested on another computer with the same token and that worked.

image

Warning output on import is being written out twice

Anytime you import this module it is outputting the text multiple times:

> ipmo PowerShellForGitHub
C:\Program Files\WindowsPowerShell\Modules\PowerShellForGitHub\0.1.0\ApiTokens.psm1 does not exist, skipping import
This module should define $global:gitHubApiToken with your GitHub API access token in ApiTokens.psm1. Create this file if it doesn't exist.
You can simply rename ApiTokensTemplate.psm1 to ApiTokens.psm1 and update value of $global:gitHubApiToken.
You can get GitHub token from https://github.com/settings/tokens
If you don't provide it, you can still use this module, but you will be limited to 60 queries per hour.
C:\Program Files\WindowsPowerShell\Modules\PowerShellForGitHub\0.1.0\ApiTokens.psm1 does not exist, skipping import
This module should define $global:gitHubApiToken with your GitHub API access token in ApiTokens.psm1. Create this file if it doesn't exist.
You can simply rename ApiTokensTemplate.psm1 to ApiTokens.psm1 and update value of $global:gitHubApiToken.
You can get GitHub token from https://github.com/settings/tokens
If you don't provide it, you can still use this module, but you will be limited to 60 queries per hour.

As well can you please remove this as information output and change to warning so we have the ability to ignore the output. Right now there is now way to hide this output from being sent to the console or command line.

Bug in Update-GitHubRepository Archived parameter usage

So I'm pretty sure there's a bug in Update-GitHubRepository cmdlet - found it by just browsing source code:

if ($PSBoundParameters.ContainsKey('Archived')) { $hashBody['archived'] = (-not $Archived.ToBool()) }

Passing the Archived switch will result in archived=false parameter passed to API.

Is:
$hashBody['archived'] = (-not $Archived.ToBool())
Should be:
$hashBody['archived'] = $Archived.ToBool()

This is probably a copy-paste error since all other properties use inverted style:

if ($PSBoundParameters.ContainsKey('DisallowSquashMerge')) { $hashBody['allow_squash_merge'] = (-not $DisallowSquashMerge.ToBool()) }
if ($PSBoundParameters.ContainsKey('DisallowMergeCommit')) { $hashBody['allow_merge_commit'] = (-not $DisallowMergeCommit.ToBool()) }
if ($PSBoundParameters.ContainsKey('DisallowRebaseMerge')) { $hashBody['allow_rebase_merge'] = (-not $DisallowRebaseMerge.ToBool()) }
if ($PSBoundParameters.ContainsKey('Archived')) { $hashBody['archived'] = (-not $Archived.ToBool()) }

Make telemetry reporting not require NuGet downloads

Right now, in order for telemetry to work, 3 NuGet packages need to be downloaded (or cached):

  • Microsoft.ApplicationInsights (for Microsoft.ApplicationInsights.dll)
  • Microsoft.Diagnostics.Tracing.EventSource.Redist (for Microsoft.Diagnostics.Tracing.EventSource.dll)
  • Microsoft.Bcl.Async (for Microsoft.Threading.Tasks.dll)

In the end, the telemetry events are just being sent as web requests. While the web request format isn't documented, it should be possible to reverse-engineer via a tool like Fiddler.

If we can figure out how to make those web requests directly, then we can improve the first-run experience for users to not need to have that initial binary download.

Could not create SSL/TLS secure channel

I was trying to create a small gui script to create a repo with a few default settings.

  1. Steps to reproduce: Get-GitHubRepository
  2. Expected to see a list of repositories
  3. What I saw instead:
    Get-GitHubRepository : The term 'Write-InvocationLog' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
    included, verify that the path is correct and try again.
    At line:1 char:1
  • Get-GitHubRepository
  •   + CategoryInfo          : ObjectNotFound: (Write-InvocationLog:String) [Get-GitHubRepository], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException,Get-GitHubRepository
    

Position PowerShellForGitHub to be used in GitHub Actions?

This module is by far the best PowerShell module out there for working with GitHub's API.

PowerShell is a fantastic language for CI/CD pipelines, automation pipelines, etc.

This makes PowerShell a great language to use in GitHub Actions.

My thinking is that PowerShellForGitHub could be leveraged as a GitHub Actions helper module that gives you PowerShell-y ways to interact with GitHub's APIs that are most likely touched in GitHub Actions:

  • Issues
  • Issue comments
  • PRs
  • PR comments
  • Releases

etc.

And most important is to have a seamless way to authenticate the module from a running Action.

With this, we can say that PowerShell can be used for creating Actions - which is the ultimate goal.

This issue is more of a meta-discussion issue than anything else as I think some issues in this repo already call out the parts that are GH API gaps.

Gists

Just thought id throw this out there, but i have a pretty stable module out there that could be included in this for working with Gists: https://github.com/dotps1/PSGist

i haven't updated it in a while, but defiantly could put some work into it if it where included in this repo.

thanks!

Loop between Reset-GitHubConfiguration and Clear-GitHubAuthentication

Description

The commands Reset-GitHubConfiguration and Clear-GitHubAuthentication can get into an infinite suggestion loop.

image

What I was doing / Steps to Reproduce

I downloaded the code for the first time and I was attempting to create a new unit test. Running the new unit test in VSCode presented a series of informative messages and I went about trying to accomplish the correct setup.

I had set the Tests/Config/Settings.ps1 file with my information, and as you can see from the screen shot, I had just entered my GitHub username/password into a PSCredential.

I then used Set-GitHubAuthentication to set the credential and attempted to rerun the unit test. I was running the new unit tests file individually, by opening it in VSCode and hitting F5. It resulted in the error from the screenshot. Please ignore that error, as my custom made / new code is not yet working.

However, it did result in an informative warning message.

I read (or misread) the warning message to indicate that I should run Clear-GitHubAuthentication to prevent the warning message from appearing in the future. (Even though I feel like that name means I'm clearing my authentication tokens).

After the Clear command ran, it left another warning message that I should run Reset-GitHubConfiguration.

Unfortunately, running the Reset command left a warning that I should run Clear-GitHubAuthentication.

Soo .... I figure that's not supposed create a warning message loop like that.

How to upload file on GitHub using the module ?

The module is pretty awesome.
Just starting some tests with it but don't find how to upload file on github ?
I can create a readme using the autoinit parameter.
For now I'm searching how to add my own content into this readme then upload for instance an exe or script in the repository

Remaining work for API Completeness

Using a single issue to track the remaining work, so as not to litter the Issues and give the wrong impression on the current state of the project, bug wise.

If a contributor is interested in making progress towards any of these items, they should just create a new Issue to track that specific work, mention this Issue, and then resolve their PR against the Issue that they created. At that point, I'll go ahead and update this list and check off that item.

Using a single issue to track the remaining work, so as not to litter the Issues and give the wrong impression on the current state of the project, bug wise.

If a contributor is interested in making progress towards any of these items, they should just create a new Issue to track that specific work, mention this Issue, and then resolve their PR against the Issue that they created. At that point, I'll go ahead and update this list and check off that item.

TLS error in Get-GitHubIssueForRepository : Failed to execute query with exception

It looks like there is a issue with TLS with the latest version published to the PSGallery.

When running

$issues=Get-GitHubIssueForRepository -repositor
yUrl @('https://github.com/QuarterSpot/../')
Getting issues for repository https://github.com/QuarterSpot/.../

I get the following error:

Get-GitHubIssueForRepository : Failed to execute query with exception: System.Net.WebException: The request was
aborted: Could not create SSL/TLS secure channel.
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
HTTP status code:
At line:1 char:9
+ $issues=Get-GitHubIssueForRepository -repositoryUrl @('https://github ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-GitHubIssueForRepository

I found a workaround which is to set the default security protocol. I just executed this in the same session that the module was imported.

[System.Net.ServicePointManager]::SecurityProtocol=[System.Net.SecurityProtocolType]::Tls12

Watchers_Count, Watchers returning wrong value

Here's an output of my query:

$T = Get-GitHubRepository -OwnerName EvotecIT
$T | Sort-Object Stargazers_Count -Descending | Format-Table full_name, Name, Stargazers_Count, Watchers_Count, Watchers,forks_count, Open_issues,license, Language, HTML_URL, Fork, Created_At, Updated_At, Pushed_At, Archived -AutoSize

image

It seems watchers_count, watchers are the same as stargazers_count which isn't really true.

Support GitHub Enterprise

GitHub Enterprise supports nearly the same API for interacting, and it appears relatively straightforward to provide a way to override the otherwise hardcoded API URLs in GitHubCore.ps1 to local GHE server environments.

Adding GHE support appears to be low hanging fruit. Is there any prior work done on this? Any pitfalls?

Milestone "Should have the expected due_on date" UT failing

The following UT is failing:

Context For creating a new milestone
      [-] Should have the expected due_on date 85ms
        Expected 2020-03-14T00:00:00.0000000Z, but got 2020-03-13T00:00:00.0000000+00:00.
        112:                 (Get-Date -Date $existingMilestone.due_on).Date | Should be $defaultMilestoneDueOn.Date
        at Invoke-LegacyAssertion, C:\Program Files\WindowsPowerShell\Modules\Pester\4.7.2\Functions\Assertions\Should.ps1: line 169
        at <ScriptBlock>, C:\projects\powershellforgithub\Tests\GitHubMilestones.tests.ps1: line 112
DONE - Operation took 2 second(s) [Updating Issue #1 on 6c28961d-202f-45a8-8f48-bed2616cbf10]

Merge in functionality from other PS & Github Modules

Ideally we only need 1 module for PowerShell & to work with Github and we already have 2 in the Gallery by @pcgeek86 @davidobrien1985 as well as a more featured module Posh-Github written by @Iristyle which could really do with being updated to allow use of Personal Access Token's which there is already support for in the other modules.

Now I'm looking at whether it makes sense trying to port a number of the functions in @Iristyle module as well as @davidobrien1985 module this weekend (if people are agreeable to this of course) into this module and have 1 fully functioned module

Now that PS its self is OS'd I think its time to start bringing together modules that have some similarities to the PowerShell DSC Resources that fall under a similar High Quality suggestive

I say this especially around the Posh-Github modile as there are some as there are some really good functions in that module like the New-GithubFork however I would really like this to be a module that combined all the functions together without lots of global variables dotted everywhere (yak) and has no reliance on stored credentials of any kind (again yak) whilst it passes PSScriptAnalyzer whilst having a structured & standardised build process.

Also would be a challenge to get this working on a .NET Core PS environment and would be a great showcase to the community too!

Default format

The current default format is pretty unreadable for use in the PowerShell REPL:

โœ” ~
๐Ÿบ  Get-GitHubIssueForRepository PowerShell/PowerShellForGitHub | Select-Object -First 1
Getting issues for repository PowerShell/PowerShellForGitHub
                                                                                                                                                                                                                                                                                                                                                                                  url                : https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/26                                                                                               repository_url     : https://api.github.com/repos/PowerShell/PowerShellForGitHub                                                                                                         
labels_url         : https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/26/labels{/name}
comments_url       : https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/26/comments
events_url         : https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/26/events
html_url           : https://github.com/PowerShell/PowerShellForGitHub/issues/26
id                 : 301194116
number             : 26
title              : Token in template file
user               : @{login=felixfbecker; id=10532611; avatar_url=https://avatars0.githubusercontent.com/u/10532611?v=4; gravatar_id=; url=https://api.github.com/users/felixfbecker; h
                     tml_url=https://github.com/felixfbecker; followers_url=https://api.github.com/users/felixfbecker/followers; following_url=https://api.github.com/users/felixfbecker
                     /following{/other_user}; gists_url=https://api.github.com/users/felixfbecker/gists{/gist_id}; starred_url=https://api.github.com/users/felixfbecker/starred{/owner}
                     {/repo}; subscriptions_url=https://api.github.com/users/felixfbecker/subscriptions; organizations_url=https://api.github.com/users/felixfbecker/orgs; repos_url=htt
                     ps://api.github.com/users/felixfbecker/repos; events_url=https://api.github.com/users/felixfbecker/events{/privacy}; received_events_url=https://api.github.com/use
                     rs/felixfbecker/received_events; type=User; site_admin=False}
labels             : {}
state              : open
locked             : False
assignee           : 
assignees          : {}
milestone          : 
comments           : 0
created_at         : 02/28/2018 21:41:52
updated_at         : 02/28/2018 21:41:52
closed_at          : 
author_association : NONE
body               : I find it weird having to rename a file in the module and setting the token there. Wouldn't this get overridden on updates? Why can't I just set the token in profi
                     le.ps1?
                     
                     And, shouldn't this be a secure string or credential object of some sort instead of a plain string?

Table format shows mostly unimportant data:

โœ” ~
๐Ÿบ  Get-GitHubIssueForRepository PowerShell/PowerShellForGitHub  | Format-Table
Getting issues for repository PowerShell/PowerShellForGitHub
                                                                                                                                                                                                                                                                                                      url                                                                   repository_url                                              labels_url                                                                          comments_url                                                                    ---                                                                   --------------                                              ----------                                                                          ------------                                                                    https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/26 https://api.github.com/repos/PowerShell/PowerShellForGitHub https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/26/labels{/name} https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/26/comments  
https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/24 https://api.github.com/repos/PowerShell/PowerShellForGitHub https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/24/labels{/name} https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/24/comments
https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/23 https://api.github.com/repos/PowerShell/PowerShellForGitHub https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/23/labels{/name} https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/23/comments
https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/21 https://api.github.com/repos/PowerShell/PowerShellForGitHub https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/21/labels{/name} https://api.github.com/repos/PowerShell/PowerShellForGitHub/issues/21/comments

I would propose to add ps1xml format files so that the default output format is a table that somewhat resembles the information GitHub shows on the issues page (title, author, closed/open, labels, ...).

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_format.ps1xml?view=powershell-6

Optimizations for array creation

Not really an issue, but with larger arrays things start to be less than optimal for performance when using an approach as seen here:

$getParams = @()
if ($PSBoundParameters.ContainsKey('Visibility')) { $getParams += "visibility=$($Visibility.ToLower())" }
if ($PSBoundParameters.ContainsKey('Sort')) { $getParams += "sort=$($sortConverter[$Sort])" }
if ($PSBoundParameters.ContainsKey('Type')) { $getParams += "type=$($Type.ToLower())" }
if ($PSBoundParameters.ContainsKey('Direction')) { $getParams += "direction=$($directionConverter[$Direction])" }
if ($PSBoundParameters.ContainsKey('Affiliation') -and $Affiliation.Count -gt 0)
{
$getParams += "affiliation=$($Affiliation -join ',')"
}

It can be optimized like that;

    $getParams = @(
        if ($PSBoundParameters.ContainsKey('Visibility')) { "visibility=$($Visibility.ToLower())" }
        if ($PSBoundParameters.ContainsKey('Sort')) { "sort=$($sortConverter[$Sort])" }
        if ($PSBoundParameters.ContainsKey('Type')) { "type=$($Type.ToLower())" }
        if ($PSBoundParameters.ContainsKey('Direction')) { "direction=$($directionConverter[$Direction])" }
        if ($PSBoundParameters.ContainsKey('Affiliation') -and $Affiliation.Count -gt 0) {
            "affiliation=$($Affiliation -join ',')"
        }
    )

Not sure if there's a need for that. I can see it being built the same way all over the code, but the amount of elements probably is too small to notice a performance difference.

Add a command for configuration

It's a bit silly to have to edit a file (in Program Files?) by hand, for a PowerShell module.

Additionally, the setting really should go in AppData, so multiple users can share a single install of the module.

Rename ConvertFrom-Markdown

ConvertFrom-Markdown was added as a standard command in PowerShellCore 6.

Given that, this module's command should be renamed in order to avoid any conflicts when used in that environment.

Current proposal is to rename it to ConvertFrom-GitHubMarkdown -- adding GitHub in there is more consistent with the rest of the module commands. The only downside to this name is that it might imply that it's specifically about converting GitHub Flavored Markdown whereas it converts both "standard" and "GitHub flavored"

Invoke-RestMethod : The remote server returned an error: (500) Internal Server Error

function ResolveJIRA()
{
[cmdletbinding()]
param([String] $ticketID)
$projectname="CAS-CPR-TESt"
$releasenum="1.0.0"
$deployid="1.0.0-dep-id"
#DMl execution logs
$logs="https://xxxxxx.octopus.com/app#/projects/"+$projectname+"/releases/"+$releasenum+"/deployments/"+$deployid
#scriptlogs
$url="https://xxxxxx.octopus.com.com/app#/projects/"+$projectname+"/releases/"+$releasenum
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $usernam,$passwor)))
$resturi ="https://jira.xxxx.com/rest/api/2/issue/"+$ticketID+"/transitions?expand=transitions.fields"
$b1='{
"update": {
"comment": [
{
"add": {
'
$b2=' "body": "JIRA resolved by octopus during datapatch fix. Click to view script logs '+$url+" Click here to view octopus logs "+$logs+'"'
$b3='
}
}
]
},
"transition": {
"id": "121"
},
"fields": {
"resolution": {
"name": "Done"
}
}
}'
$body=$b1+$b2+$b3
write-host $resturi testing.....invoke command
Invoke-RestMethod -uri $resturi -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method post -ContentType "application/json" -Body $body
Write-Host "JIRA updating success"

}

Add use case: Migrate my blog comments from Disqus to Github Issues

Not sure if you would be interested to add this into your Readme examples/use cases.
I used your module to migrate all my disqus blog comments to Github issues. It is using Utterances-Bot to create new issues and display existing comments.

This is how i found the issue fixed by my PR #76
Thanks for this tool, I'll continue to contribute if i see other bugs.

Here is my blog post where i talked about it: https://lazywinadmin.com/2019/04/moving_blog_comments.html

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.