ProductivityTools.PSCloneGithubRepositories.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
function CloneRepository($sshurl)
{
    git clone $sshurl
}

function CloneRepositories($repositories)
{
    foreach($repository in $repositories)
    {
        $repoName=$repository.name
        if ($(Test-Path $repoName) -eq $true)
        {
            Write-Host "Directory $repoName exists. - Skipping." -ForegroundColor Yellow
        }
        else
        {
            $sshurl=$repository.ssh_url
            CloneRepository $sshurl
            Write-Host "Repository $repoName cloned" -ForegroundColor Green
        }
    }
}

function GetRepositories($token)
{
    $GitHubUri="https://api.github.com/user/repos"
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    $i=1;
    do
    {
        $paginateduri=$GitHubUri+"?page="+$i
        Write-Host "Requesting repositories with address $paginateduri" -ForegroundColor DarkGreen
        $repos=Invoke-WebRequest -Uri $paginateduri -Headers @{"Authorization"="Bearer $token"}
        $repositories=$repos|ConvertFrom-Json
        CloneRepositories $repositories
        $i++
    }while ($repositories.Count -gt 0)
}

function Clone-GithubRepositories($TargetDirectory,$Token)
{
    Push-Location

    if ((Test-Path $TargetDirectory) -eq $false)
    {
        New-Item $TargetDirectory -ItemType Directory
    }
    cd $TargetDirectory
    GetRepositories $Token

    Pop-Location
}

Export-ModuleMember Clone-GithubRepositories