Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GitHubRepositories: Add New-GitHubRepositoryFromTemplate Function #221

Merged
merged 18 commits into from
Jun 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,7 @@ Thank you to all of our contributors, no matter how big or small the contributio
- **[Jess Pomfret (@jpomfret)](https://github.com/jpomfret)**
- **[Giuseppe Campanelli (@themilanfan)](https://github.com/themilanfan)**
- **[Christoph Bergmeister (@bergmeister)](https://github.com/bergmeister)**
- **[Simon Heather (@X-Guardian)](https://github.com/X-Guardian)**

----------

Expand Down
169 changes: 169 additions & 0 deletions GitHubRepositories.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,175 @@ filter New-GitHubRepository
return (Invoke-GHRestMethod @params | Add-GitHubRepositoryAdditionalProperties)
}

filter New-GitHubRepositoryFromTemplate
{
<#
.SYNOPSIS
Creates a new repository on GitHub from a template repository.

.DESCRIPTION
Creates a new repository on GitHub from a template repository.

The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub

.PARAMETER OwnerName
Owner of the template repository.
If no value is specified, the DefaultOwnerName configuration property value will be used,
and if there is no configuration value defined, the current authenticated user will be used.

.PARAMETER RepositoryName
Name of the template repository.
X-Guardian marked this conversation as resolved.
Show resolved Hide resolved

.PARAMETER Uri
Uri for the repository.
The OwnerName and RepositoryName will be extracted from here instead of needing to provide
them individually.

.PARAMETER TargetOwnerName
X-Guardian marked this conversation as resolved.
Show resolved Hide resolved
The organization or person who will own the new repository.
To create a new repository in an organization, the authenticated user must be a member
of the specified organization.

.PARAMETER TargetRepositoryName
Name of the repository to be created.

.PARAMETER Description
A short description of the repository.

.PARAMETER Private
By default, this repository will created Public. Specify this to create a private
repository.

.PARAMETER AccessToken
If provided, this will be used as the AccessToken for authentication with the
REST Api. Otherwise, will attempt to use the configured value or will run unauthenticated.

.PARAMETER NoStatus
If this switch is specified, long-running commands will run on the main thread
with no commandline status update. When not specified, those commands run in
the background, enabling the command prompt to provide status information.
If not supplied here, the DefaultNoStatus configuration property value will be used.

.INPUTS
GitHub.Branch
GitHub.Content
GitHub.Event
GitHub.Issue
GitHub.IssueComment
GitHub.Label
GitHub.Milestone
GitHub.PullRequest
GitHub.Project
GitHub.ProjectCard
GitHub.ProjectColumn
GitHub.Release
GitHub.Repository

.OUTPUTS
GitHub.Repository

.NOTES
The authenticated user must own or be a member of an organization that owns the repository.

To check if a repository is available to use as a template, call `Get-GitHubRepository` on the
repository in question and check that the is_template property is $true.

.EXAMPLE
New-GitHubRepositoryFromTemplate -OwnerName MyOrg -RepositoryName MyTemplateRepo -TargetRepositoryName MyNewRepo -TargetOwnerName Me

Creates a new GitHub repository from the specified template repository.

.EXAMPLE
$repo = Get-GitHubRepository -OwnerName MyOrg -RepositoryName MyTemplateRepo
$repo | New-GitHubRepositoryFromTemplate -TargetRepositoryName MyNewRepo -TargetOwnerName Me

You can also pipe in a repo that was returned from a previous command.
#>
[CmdletBinding(
SupportsShouldProcess,
PositionalBinding = $false)]
[OutputType({$script:GitHubRepositoryTypeName})]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSShouldProcess", "",
X-Guardian marked this conversation as resolved.
Show resolved Hide resolved
Justification="Methods called within here make use of PSShouldProcess, and the switch is
passed on to them inherently.")]
param(
[Parameter(ParameterSetName = 'Elements')]
[string] $OwnerName,

[Parameter(
X-Guardian marked this conversation as resolved.
Show resolved Hide resolved
Mandatory,
Position = 1,
ParameterSetName = 'Elements')]
[ValidateNotNullOrEmpty()]
[string] $RepositoryName,

[Parameter(
Mandatory,
Position = 2,
ValueFromPipelineByPropertyName,
ParameterSetName = 'Uri')]
[Alias('RepositoryUrl')]
[string] $Uri,

[Parameter(
Mandatory,
Position = 3)]
[ValidateNotNullOrEmpty()]
[string] $TargetOwnerName,

[Parameter(
Mandatory,
Position = 4)]
[ValidateNotNullOrEmpty()]
[string] $TargetRepositoryName,

[string] $Description,

[switch] $Private,

[string] $AccessToken,

[switch] $NoStatus
)

Write-InvocationLog

$elements = Resolve-RepositoryElements -BoundParameters $PSBoundParameters
$OwnerName = $elements.ownerName

$telemetryProperties = @{
RepositoryName = (Get-PiiSafeString -PlainText $RepositoryName)
X-Guardian marked this conversation as resolved.
Show resolved Hide resolved
OwnerName = (Get-PiiSafeString -PlainText $OwnerName)
TargetRepositoryName = (Get-PiiSafeString -PlainText $TargetRepositoryName)
TargetOwnerName = (Get-PiiSafeString -PlainText $TargetOwnerName)
}

$uriFragment = "repos/$OwnerName/$RepositoryName/generate"

$hashBody = @{
owner = $TargetOwnerName
name = $TargetRepositoryName
}

if ($PSBoundParameters.ContainsKey('Description')) { $hashBody['description'] = $Description }
if ($PSBoundParameters.ContainsKey('Private')) { $hashBody['private'] = $Private.ToBool() }

$params = @{
'UriFragment' = $uriFragment
'Body' = (ConvertTo-Json -InputObject $hashBody)
'Method' = 'Post'
'Description' = "Creating $TargetRepositoryName from Template"
'AcceptHeader' = $script:baptisteAcceptHeader
'AccessToken' = $AccessToken
'TelemetryEventName' = $MyInvocation.MyCommand.Name
'TelemetryProperties' = $telemetryProperties
'NoStatus' = (Resolve-ParameterWithDefaultConfigurationValue `
-BoundParameters $PSBoundParameters -Name NoStatus -ConfigValueName DefaultNoStatus)
}

return (Invoke-GHRestMethod @params | Add-GitHubRepositoryAdditionalProperties)
}

filter Remove-GitHubRepository
{
<#
Expand Down
1 change: 1 addition & 0 deletions PowerShellForGitHub.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
'New-GitHubProjectColumn',
'New-GitHubPullRequest',
'New-GitHubRepository',
'New-GitHubRepositoryFromTemplate',
'New-GitHubRepositoryFork',
'Remove-GitHubAssignee',
'Remove-GitHubIssueComment',
Expand Down
78 changes: 78 additions & 0 deletions Tests/GitHubRepositories.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,84 @@ try
}
}

Describe 'GitHubRepositories\New-GitHubRepositoryFromTemplate' {
BeforeAll {
$templateRepoName = ([Guid]::NewGuid().Guid)
$ownerName = $script:ownerName
$testGitIgnoreTemplate = (Get-GitHubGitIgnore)[0]
$testLicenseTemplate = (Get-GitHubLicense)[0].key

$newGitHubRepositoryParms = @{
RepositoryName = $templateRepoName
Description = $defaultRepoDesc
GitIgnoreTemplate = $testGitIgnoreTemplate
LicenseTemplate = $testLicenseTemplate
IsTemplate = $true
}

$templateRepo = New-GitHubRepository @newGitHubRepositoryParms
X-Guardian marked this conversation as resolved.
Show resolved Hide resolved
}

Context 'When creating a public repository from a template' {
BeforeAll {
$repoName = ([Guid]::NewGuid().Guid)
$newRepoDesc = 'New Repo Description'
$newGitHubRepositoryFromTemplateParms = @{
RepositoryName = $templateRepoName
OwnerName = $templateRepo.owner.login
TargetOwnerName = $ownerName
TargetRepositoryName = $repoName
Description = $newRepoDesc
}

$repo = New-GitHubRepositoryFromTemplate @newGitHubRepositoryFromTemplateParms
X-Guardian marked this conversation as resolved.
Show resolved Hide resolved
}

It 'Should support pipeline input for the uri parameter' {
$newGitHubRepositoryFromTemplateParms = @{
TargetOwnerName = $ownerName
TargetRepositoryName = $repoName
}

{ $templateRepo | New-GitHubRepositoryFromTemplate @newGitHubRepositoryFromTemplateParms -WhatIf } |
X-Guardian marked this conversation as resolved.
Show resolved Hide resolved
Should -Not -Throw
}

It 'Should have the expected type and addititional properties' {
$repo.PSObject.TypeNames[0] | Should -Be 'GitHub.Repository'
$repo.name | Should -Be $repoName
$repo.private | Should -BeFalse
$repo.owner.login | Should -Be $script:ownerName
$repo.description | Should -Be $newRepoDesc
$repo.is_template | Should -BeFalse
$repo.RepositoryId | Should -Be $repo.id
$repo.RepositoryUrl | Should -Be $repo.html_url
}

It 'Should have created a .gitignore file' {
{ Get-GitHubContent -Uri $repo.svn_url -Path '.gitignore' } | Should -Not -Throw
}

It 'Should have created a LICENSE file' {
{ Get-GitHubContent -Uri $repo.svn_url -Path 'LICENSE' } | Should -Not -Throw
}

AfterAll {
if (Get-Variable -Name repo -ErrorAction SilentlyContinue)
{
Remove-GitHubRepository -Uri $repo.svn_url -Confirm:$false
}
}
}

AfterAll {
if (Get-Variable -Name templateRepo -ErrorAction SilentlyContinue)
{
Remove-GitHubRepository -Uri $templateRepo.svn_url -Confirm:$false
}
}
}

Describe 'Getting repositories' {
Context 'For authenticated user' {
BeforeAll -Scriptblock {
Expand Down
34 changes: 32 additions & 2 deletions USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@
* [Updating the current authenticated user](#updating-the-current-authenticated-user)
* [Getting any user](#getting-any-user)
* [Getting all users](#getting-all-users)
* [Repositories](#repositories)
* [Repositories](#repositories])
* [Create a repository](#Create-a-repository)
* [Create a repository in an organization](#Create-a-repository-in-an-organization)
* [Create a repository in an organization and grant access to a team](#Create-a-repository-in-an-organization-and-grant-access-to-a-team)
* [Create a repository from a template repository](#Create-a-repository-from-a-template-repository)
* [Get repository vulnerability alert status](#get-repository-vulnerability-alert-status)
* [Enable repository vulnerability alerts](#enable-repository-vulnerability-alerts)
* [Disable repository vulnerability alerts](#disable-repository-vulnerability-alerts)
Expand Down Expand Up @@ -103,7 +107,9 @@ The logging is affected by configuration properties (which can be checked with
different log file for each PowerShell process. An easy way to view the filtered
entries for a session is (replacing `PID` with the PID that you are interested in):

Get-Content -Path <logPath> -Encoding UTF8 | Where { $_ -like '*[[]PID[]]*' }
```powershell
Get-Content -Path <logPath> -Encoding UTF8 | Where { $_ -like '*[[]PID[]]*' }
```

----------

Expand Down Expand Up @@ -422,6 +428,30 @@ Get-GitHubUser

### Repositories

#### Create a repository

```powershell
New-GitHubRepository -RepositoryName TestRepo
```

#### Create a repository in an organization

```powershell
New-GitHubRepository -RepositoryName TestRepo -OrganizationName MyOrg
```

#### Create a repository in an organization and grant access to a team

```powershell
$myTeam = Get-GitHubTeam -OrganizationName MyOrg | Where-Object -Property name -eq MyTeam
New-GitHubRepository -RepositoryName TestRepo -OrganizationName MyOrg -TeamId $myTeam.id
```

#### Create a repository from a template repository

```powershell
New-GitHubRepositoryFromTemplate -OwnerName MyOrg -RepositoryName MyNewRepo-TemplateOwnerName MyOrg -TemplateRepositoryName MyTemplateRepo
=======
#### Get repository vulnerability alert status

```powershell
Expand Down