├── static └── demo.gif ├── src ├── WorkFlowGenerator │ ├── appsettings.json │ ├── Properties │ │ └── launchSettings.json │ ├── Services │ │ ├── IProjectDiscoveryService.cs │ │ ├── IRepoService.cs │ │ ├── IGitHubService.cs │ │ ├── IAzureService.cs │ │ ├── RepoService.cs │ │ ├── ProjectDiscoveryService.cs │ │ ├── AzureService.cs │ │ └── GitHubService.cs │ ├── Models │ │ ├── AppSettings.cs │ │ ├── GitHub │ │ │ ├── RepositoryExtended.cs │ │ │ ├── PublicKey.cs │ │ │ └── Secrets.cs │ │ └── ProjectProperties.cs │ ├── Exceptions │ │ └── CommandValidationException.cs │ ├── AzureIdentityHelpers │ │ ├── AzureIdentityCredentialAdapter.cs │ │ ├── AzureIdentityTokenProvider.cs │ │ └── AzureIdentityFluentCredentialAdapter.cs │ ├── WorkflowSettings.cs │ ├── templates │ │ ├── function.txt │ │ ├── webapp.txt │ │ ├── AzureWebAppTemplate.cs │ │ └── AzureFunctionTemplate.cs │ ├── WorkFlowGenerator.csproj │ ├── Resources │ │ ├── ValidationErrorMessages.Designer.cs │ │ └── ValidationErrorMessages.resx │ └── Program.cs ├── WorkFlowGenerator.Tests │ ├── Utility.cs │ ├── WorkFlowGenerator.Tests.csproj │ └── WorkflowGeneratorTemplateTests.cs ├── WorkFlowGenerator.sln └── .editorconfig ├── createtool.cmd ├── createtool.sh ├── version.json ├── .github └── workflows │ ├── pr_build.yaml │ └── main_release.yaml ├── README.md └── .gitignore /static/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isaacrlevin/WorkFlowGenerator/HEAD/static/demo.gif -------------------------------------------------------------------------------- /src/WorkFlowGenerator/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "GitHubClientId": "", 3 | "GitHubClientSecret": "" 4 | } -------------------------------------------------------------------------------- /createtool.cmd: -------------------------------------------------------------------------------- 1 | cd src\WorkFlowGenerator 2 | dotnet pack 3 | dotnet tool install -g --add-source .\nupkg dotnet-workflow-generator 4 | -------------------------------------------------------------------------------- /createtool.sh: -------------------------------------------------------------------------------- 1 | cd src/WorkFlowGenerator 2 | dotnet pack 3 | dotnet tool install -g --add-source /nupkg dotnet-workflow-generator 4 | -------------------------------------------------------------------------------- /version.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2", 3 | "publicReleaseRefSpec": [ 4 | "^refs/heads/main$", 5 | "^refs/heads/develop$", 6 | "^refs/heads/rel/v\\d+\\.\\d+" 7 | ] 8 | } -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "WorkFlowGenerator": { 4 | "commandName": "Project", 5 | "workingDirectory": "D:\\dev\\Demos\\.NET-Conf-Demos\\AdvancedActions" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Services/IProjectDiscoveryService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace WorkFlowGenerator.Services; 6 | 7 | public interface IProjectDiscoveryService 8 | { 9 | string DiscoverProject(string path); 10 | } 11 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Models/AppSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace WorkFlowGenerator.Models; 6 | 7 | public class AppSettings 8 | { 9 | public string GitHubClientId { get; set; } 10 | public string GitHubClientSecret { get; set; } 11 | } 12 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Services/IRepoService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using LibGit2Sharp; 5 | using WorkFlowGenerator.Models.GitHub; 6 | 7 | namespace WorkFlowGenerator.Services; 8 | 9 | public interface IRepoService 10 | { 11 | public RepositoryExtended GetGitRepo(string path); 12 | 13 | public void CommitAndPushToRepo(string path, string workflowFilePath, string accessToken); 14 | } 15 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Models/GitHub/RepositoryExtended.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using LibGit2Sharp; 5 | 6 | namespace WorkFlowGenerator.Models.GitHub; 7 | 8 | public class RepositoryExtended 9 | { 10 | public Uri RemoteOriginUrl { get; set; } 11 | 12 | public string GitHubOwner { get; set; } 13 | 14 | public string GitHubRepo { get; set; } 15 | 16 | public Repository Repository { get; set; } 17 | } 18 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Models/GitHub/PublicKey.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace WorkFlowGenerator.Models.GitHub; 4 | 5 | public class PublicKey 6 | { 7 | [JsonProperty("key_id")] 8 | public string Key_Id { get; set; } 9 | [JsonProperty("key")] 10 | public string Key { get; set; } 11 | } 12 | 13 | public class CreateSecretRequest 14 | { 15 | public string key_id { get; set; } 16 | 17 | public byte[] encrypted_value { get; set; } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator.Tests/Utility.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | 3 | namespace WorkFlowGenerator.Tests; 4 | 5 | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] 6 | [TestClass] 7 | public class Utility 8 | { 9 | public static string TrimNewLines(string input) 10 | { 11 | //Trim off any leading or trailing new lines 12 | input = input.TrimStart('\r', '\n'); 13 | input = input.TrimEnd('\r', '\n'); 14 | 15 | return input; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Exceptions/CommandValidationException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace WorkFlowGenerator.Exceptions; 6 | 7 | public class CommandValidationException : Exception 8 | { 9 | public CommandValidationException(string message) 10 | : base(message) 11 | { 12 | } 13 | 14 | public CommandValidationException(string message, Exception innerException) 15 | : base(message, innerException) 16 | { 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Services/IGitHubService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using WorkFlowGenerator.Models.GitHub; 3 | 4 | namespace WorkFlowGenerator.Services; 5 | 6 | public interface IGitHubService 7 | { 8 | public Task GetGitHubToken(); 9 | 10 | public Task GetSecrets(string owner, string repo); 11 | 12 | public Task CreateSecret(string owner, string repo, string secretName, string secretValue); 13 | 14 | public Task CreateAndCommit(string owner, string repo, string fileName); 15 | } 16 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/AzureIdentityHelpers/AzureIdentityCredentialAdapter.cs: -------------------------------------------------------------------------------- 1 | using Azure.Core; 2 | using Microsoft.Rest; 3 | 4 | namespace Azure.Identity.Extensions; 5 | 6 | public class AzureIdentityCredentialAdapter : TokenCredentials 7 | { 8 | public AzureIdentityCredentialAdapter(string[] scopes = null) : base(new AzureIdentityTokenProvider(scopes)) 9 | { 10 | } 11 | 12 | public AzureIdentityCredentialAdapter(TokenCredential tokenCredential, string[] scopes = null) : base(new AzureIdentityTokenProvider(tokenCredential, scopes)) 13 | { 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Models/GitHub/Secrets.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json; 3 | 4 | namespace WorkFlowGenerator.Models.GitHub; 5 | 6 | public class SecretRoot 7 | { 8 | [JsonProperty("total_count")] 9 | public int TotalCount { get; set; } 10 | [JsonProperty("secrets")] 11 | public Secret[] Secrets { get; set; } 12 | } 13 | 14 | public class Secret 15 | { 16 | [JsonProperty("name")] 17 | public string Name { get; set; } 18 | [JsonProperty("created_at")] 19 | public DateTime CreatedAt { get; set; } 20 | [JsonProperty("updated_at")] 21 | public DateTime UpdatedAt { get; set; } 22 | } 23 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Services/IAzureService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using Azure.ResourceManager.Resources; 6 | using Microsoft.Azure.Management.AppService.Fluent; 7 | 8 | namespace WorkFlowGenerator.Services; 9 | 10 | public interface IAzureService 11 | { 12 | public Subscription GetSubscription(); 13 | 14 | public ResourceGroup GetResourceGroups(); 15 | 16 | public Task GetWebApps(); 17 | 18 | public Task GetFunctions(); 19 | 20 | public Task GetPublishProfile(string resource); 21 | } 22 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator.Tests/WorkFlowGenerator.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/WorkflowSettings.cs: -------------------------------------------------------------------------------- 1 | namespace WorkFlowGenerator; 2 | 3 | public class WorkflowSettings 4 | { 5 | public string WorkflowName { get; set; } 6 | public string AzureSubscription { get; set; } 7 | 8 | public string AzureResourceGroup { get; set; } 9 | 10 | public AppType AppType { get; set; } 11 | 12 | public AppPlatform AppPlatform { get; set; } 13 | 14 | public string AzureResourceName { get; set; } 15 | 16 | public string DOTNETVersion { get; set; } 17 | 18 | public string AzurePublishProfile { get; set; } 19 | 20 | public string PackagePath { get; set; } 21 | 22 | public string WorkflowFolderPath { get; set; } 23 | 24 | public string WorkingDirectory { get; set; } 25 | 26 | public string GitHubOwner { get; set; } 27 | 28 | public string GitHubRepo { get; set; } 29 | } 30 | 31 | public enum AppType 32 | { 33 | WebApp, 34 | Function 35 | } 36 | 37 | public enum AppPlatform 38 | { 39 | Windows, 40 | Linux 41 | } 42 | -------------------------------------------------------------------------------- /.github/workflows/pr_build.yaml: -------------------------------------------------------------------------------- 1 | name: "PR Build" 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | paths-ignore: 8 | - '**/*.md' 9 | - '**/*.gitignore' 10 | - '**/*.gitattributes' 11 | workflow_dispatch: 12 | branches: 13 | - main 14 | paths-ignore: 15 | - '**/*.md' 16 | - '**/*.gitignore' 17 | - '**/*.gitattributes' 18 | 19 | jobs: 20 | build: 21 | name: Build 22 | runs-on: ubuntu-latest 23 | env: 24 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 25 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 26 | DOTNET_NOLOGO: true 27 | DOTNET_GENERATE_ASPNET_CERTIFICATE: false 28 | DOTNET_ADD_GLOBAL_TOOLS_TO_PATH: false 29 | DOTNET_MULTILEVEL_LOOKUP: 0 30 | 31 | steps: 32 | - uses: actions/checkout@v2 33 | 34 | - name: Setup .NET Core SDK 35 | uses: actions/setup-dotnet@v1.8.2 36 | with: 37 | dotnet-version: 6.0.x 38 | 39 | - name: Restore 40 | run: dotnet restore 41 | working-directory: src 42 | 43 | - name: Build 44 | run: dotnet build --configuration Release --no-restore 45 | working-directory: src 46 | 47 | - name: Test 48 | run: dotnet test 49 | working-directory: src 50 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/templates/function.txt: -------------------------------------------------------------------------------- 1 | name: {WORKFLOW_NAME} 2 | on: 3 | push: 4 | branches: 5 | - {BRANCH_NAME} 6 | env: 7 | AZURE_FUNCTIONAPP_NAME: {AZURE_RESOURCE_NAME} 8 | AZURE_FUNCTIONAPP_PACKAGE_PATH: {PACKAGE_PATH} 9 | CONFIGURATION: Release 10 | DOTNET_CORE_VERSION: {DOTNET_VERSION} 11 | WORKING_DIRECTORY: {PROJECT_ROOT} 12 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 13 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 14 | DOTNET_NOLOGO: true 15 | DOTNET_GENERATE_ASPNET_CERTIFICATE: false 16 | DOTNET_ADD_GLOBAL_TOOLS_TO_PATH: false 17 | DOTNET_MULTILEVEL_LOOKUP: 0 18 | jobs: 19 | build: 20 | runs-on: {PLATFORM}-latest 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Setup .NET Core 24 | uses: actions/setup-dotnet@v1.8.0 25 | with: 26 | dotnet-version: ${{ env.DOTNET_CORE_VERSION }} 27 | - name: Restore 28 | run: dotnet restore "${{ env.WORKING_DIRECTORY }}" 29 | - name: Build 30 | run: dotnet build "${{ env.WORKING_DIRECTORY }}" --configuration ${{ env.CONFIGURATION }} --no-restore 31 | - name: Test 32 | run: dotnet test 33 | - name: Publish 34 | run: dotnet publish "${{ env.WORKING_DIRECTORY }}" --configuration ${{ env.CONFIGURATION }} --no-build --output "${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}" 35 | - name: Deploy to Azure Function App 36 | uses: Azure/functions-action@v1 37 | with: 38 | app-name: ${{ env.AZURE_FUNCTIONAPP_NAME }} 39 | publish-profile: ${{ secrets.{PUBLISH_PROFILE} }} 40 | package: ${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }} 41 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/templates/webapp.txt: -------------------------------------------------------------------------------- 1 | name: {WORKFLOW_NAME} 2 | on: 3 | push: 4 | branches: 5 | - {BRANCH_NAME} 6 | env: 7 | AZURE_WEBAPP_NAME: {AZURE_RESOURCE_NAME} 8 | AZURE_WEBAPP_PACKAGE_PATH: {PACKAGE_PATH} 9 | CONFIGURATION: Release 10 | DOTNET_CORE_VERSION: {DOTNET_VERSION} 11 | WORKING_DIRECTORY: {PROJECT_ROOT} 12 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 13 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 14 | DOTNET_NOLOGO: true 15 | DOTNET_GENERATE_ASPNET_CERTIFICATE: false 16 | DOTNET_ADD_GLOBAL_TOOLS_TO_PATH: false 17 | DOTNET_MULTILEVEL_LOOKUP: 0 18 | jobs: 19 | build: 20 | runs-on: {PLATFORM}-latest 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Setup .NET Core 24 | uses: actions/setup-dotnet@v1.8.0 25 | with: 26 | dotnet-version: ${{ env.DOTNET_CORE_VERSION }} 27 | - name: Restore 28 | run: dotnet restore "${{ env.WORKING_DIRECTORY }}" 29 | - name: Build 30 | run: dotnet build "${{ env.WORKING_DIRECTORY }}" --configuration ${{ env.CONFIGURATION }} --no-restore 31 | - name: Test 32 | run: dotnet test 33 | - name: Publish 34 | run: dotnet publish "${{ env.WORKING_DIRECTORY }}" --configuration ${{ env.CONFIGURATION }} -r win-x86 --self-contained true --output "${{ env.AZURE_WEBAPP_PACKAGE_PATH }}" 35 | - name: 'Run Azure webapp deploy action using publish profile credentials' 36 | uses: azure/webapps-deploy@v2 37 | with: 38 | app-name: ${{ env.AZURE_WEBAPP_NAME }} 39 | publish-profile: ${{ secrets.{PUBLISH_PROFILE} }} 40 | package: ${{ env.AZURE_WEBAPP_PACKAGE_PATH }} -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Services/RepoService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using LibGit2Sharp; 3 | using LibGit2Sharp.Handlers; 4 | using WorkFlowGenerator.Models.GitHub; 5 | 6 | namespace WorkFlowGenerator.Services; 7 | 8 | public class RepoService : IRepoService 9 | { 10 | public RepositoryExtended GetGitRepo(string path) 11 | { 12 | var repo = new Repository(Repository.Discover(path)); 13 | var url = new Uri(repo.Config.Get("remote.origin.url").Value); 14 | var repoExtended = new RepositoryExtended 15 | { 16 | Repository = repo, 17 | RemoteOriginUrl = url, 18 | GitHubOwner = url.Segments[url.Segments.Length - 2].Replace("/", ""), 19 | GitHubRepo = url.Segments[url.Segments.Length - 1].Replace("/", "") 20 | }; 21 | 22 | return repoExtended; 23 | } 24 | 25 | public void CommitAndPushToRepo(string path, string workflowFilePath, string accessToken) 26 | { 27 | using (var repo = new Repository(Repository.Discover(path))) 28 | { 29 | // Stage the file 30 | repo.Index.Add(workflowFilePath); 31 | repo.Index.Write(); 32 | 33 | Configuration config = repo.Config; 34 | Signature author = config.BuildSignature(DateTimeOffset.Now); 35 | 36 | // Commit to the repository 37 | Commit commit = repo.Commit("Adding GitHub Workflow file", author, author); 38 | 39 | // LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); 40 | 41 | // options.CredentialsProvider = new CredentialsHandler( 42 | //(url, usernameFromUrl, types) => new UsernamePasswordCredentials() 43 | //{ 44 | // Username = "isaacrlevin", 45 | // Password = accessToken 46 | //}); 47 | 48 | // repo.Network.Push(repo.Branches[repo.Head.FriendlyName], options); 49 | 50 | 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/AzureIdentityHelpers/AzureIdentityTokenProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http.Headers; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using Azure.Core; 6 | using Microsoft.Rest; 7 | 8 | 9 | namespace Azure.Identity.Extensions; 10 | 11 | public class AzureIdentityTokenProvider : ITokenProvider 12 | 13 | 14 | { 15 | private AccessToken? accessToken; 16 | private static readonly TimeSpan ExpirationThreshold = TimeSpan.FromMinutes(5); 17 | private string[] scopes; 18 | 19 | private TokenCredential tokenCredential; 20 | 21 | public AzureIdentityTokenProvider(string[] scopes = null) : this(new DefaultAzureCredential(), scopes) 22 | { 23 | } 24 | 25 | public AzureIdentityTokenProvider(TokenCredential tokenCredential, string[] scopes = null) 26 | { 27 | if (scopes == null || scopes.Length == 0) 28 | { 29 | scopes = new string[] { "https://management.azure.com/.default" }; 30 | } 31 | 32 | this.scopes = scopes; 33 | this.tokenCredential = tokenCredential; 34 | } 35 | 36 | public virtual async Task GetAuthenticationHeaderAsync(CancellationToken cancellationToken) 37 | { 38 | var accessToken = await GetTokenAsync(cancellationToken); 39 | return new AuthenticationHeaderValue("Bearer", accessToken.Token); 40 | } 41 | 42 | public virtual Task GetTokenAsync(CancellationToken cancellationToken) 43 | { 44 | if (!this.accessToken.HasValue || AccessTokenExpired) 45 | { 46 | this.accessToken = this.tokenCredential.GetTokenAsync(new TokenRequestContext(this.scopes), cancellationToken).Result; 47 | } 48 | return Task.FromResult(this.accessToken.Value); 49 | } 50 | 51 | protected virtual bool AccessTokenExpired 52 | { 53 | get { return !this.accessToken.HasValue ? true : (DateTime.UtcNow + ExpirationThreshold >= this.accessToken.Value.ExpiresOn); } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.1.31903.286 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WorkFlowGenerator", "WorkFlowGenerator\WorkFlowGenerator.csproj", "{457229C5-4108-430F-B87D-488D12D52C6F}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{EAAAC7C7-26E4-4D8B-B586-D23539C4DD5E}" 9 | ProjectSection(SolutionItems) = preProject 10 | .editorconfig = .editorconfig 11 | ..\.github\workflows\main_release.yaml = ..\.github\workflows\main_release.yaml 12 | ..\.github\workflows\pr_build.yaml = ..\.github\workflows\pr_build.yaml 13 | ..\README.md = ..\README.md 14 | EndProjectSection 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WorkFlowGenerator.Tests", "WorkFlowGenerator.Tests\WorkFlowGenerator.Tests.csproj", "{DDEF95A7-5F65-446E-AB36-77A3512D196F}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {457229C5-4108-430F-B87D-488D12D52C6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {457229C5-4108-430F-B87D-488D12D52C6F}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {457229C5-4108-430F-B87D-488D12D52C6F}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {457229C5-4108-430F-B87D-488D12D52C6F}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {DDEF95A7-5F65-446E-AB36-77A3512D196F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {DDEF95A7-5F65-446E-AB36-77A3512D196F}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {DDEF95A7-5F65-446E-AB36-77A3512D196F}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {DDEF95A7-5F65-446E-AB36-77A3512D196F}.Release|Any CPU.Build.0 = Release|Any CPU 32 | EndGlobalSection 33 | GlobalSection(SolutionProperties) = preSolution 34 | HideSolutionNode = FALSE 35 | EndGlobalSection 36 | GlobalSection(ExtensibilityGlobals) = postSolution 37 | SolutionGuid = {D4FAF071-B3A4-42BB-B70C-34249C8BFDEB} 38 | EndGlobalSection 39 | EndGlobal 40 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Models/ProjectProperties.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace WorkFlowGenerator.Models; 6 | 7 | // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0. 8 | /// 9 | [System.SerializableAttribute()] 10 | [System.ComponentModel.DesignerCategoryAttribute("code")] 11 | [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] 12 | [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] 13 | public partial class Project 14 | { 15 | 16 | private ProjectPropertyGroup propertyGroupField; 17 | 18 | private string sdkField; 19 | 20 | /// 21 | public ProjectPropertyGroup PropertyGroup 22 | { 23 | get 24 | { 25 | return this.propertyGroupField; 26 | } 27 | set 28 | { 29 | this.propertyGroupField = value; 30 | } 31 | } 32 | 33 | /// 34 | [System.Xml.Serialization.XmlAttributeAttribute()] 35 | public string Sdk 36 | { 37 | get 38 | { 39 | return this.sdkField; 40 | } 41 | set 42 | { 43 | this.sdkField = value; 44 | } 45 | } 46 | } 47 | 48 | /// 49 | [System.SerializableAttribute()] 50 | [System.ComponentModel.DesignerCategoryAttribute("code")] 51 | [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] 52 | public partial class ProjectPropertyGroup 53 | { 54 | 55 | private string targetFrameworkField; 56 | 57 | private string targetFrameworksField; 58 | 59 | private string azureFunctionsVersionField; 60 | 61 | /// 62 | public string TargetFramework 63 | { 64 | get 65 | { 66 | return this.targetFrameworkField; 67 | } 68 | set 69 | { 70 | this.targetFrameworkField = value; 71 | } 72 | } 73 | 74 | public string TargetFrameworks 75 | { 76 | get 77 | { 78 | return this.targetFrameworksField; 79 | } 80 | set 81 | { 82 | this.targetFrameworksField = value; 83 | } 84 | } 85 | 86 | /// 87 | public string AzureFunctionsVersion 88 | { 89 | get 90 | { 91 | return this.azureFunctionsVersionField; 92 | } 93 | set 94 | { 95 | this.azureFunctionsVersionField = value; 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/templates/AzureWebAppTemplate.cs: -------------------------------------------------------------------------------- 1 | using GitHubActionsDotNet.Helpers; 2 | using GitHubActionsDotNet.Models; 3 | 4 | namespace WorkFlowGenerator.Templates; 5 | 6 | public static class AzureWebAppTemplate 7 | { 8 | public static string Get( 9 | string workflow_name, 10 | string branch_name, 11 | string azure_resource_name, 12 | string package_path, 13 | string dotnet_version, 14 | string project_root, 15 | string platform, 16 | string publishProfileName) 17 | { 18 | //Arrange 19 | GitHubActionsRoot root = new(); 20 | root.name = workflow_name; 21 | root.on = TriggerHelper.AddStandardPushTrigger(branch_name); 22 | root.env = new() 23 | { 24 | { "AZURE_WEBAPP_NAME", azure_resource_name }, 25 | { "AZURE_WEBAPP_PACKAGE_PATH", package_path }, 26 | { "CONFIGURATION", "Release" }, 27 | { "DOTNET_CORE_VERSION", dotnet_version }, 28 | { "WORKING_DIRECTORY", project_root }, 29 | { "DOTNET_CLI_TELEMETRY_OPTOUT", "1" }, 30 | { "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1" }, 31 | { "DOTNET_NOLOGO", "true" }, 32 | { "DOTNET_GENERATE_ASPNET_CERTIFICATE", "false" }, 33 | { "DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", "false" }, 34 | { "DOTNET_MULTILEVEL_LOOKUP", "0" } 35 | }; 36 | Step[] buildSteps = new Step[] { 37 | CommonStepHelper.AddCheckoutStep(), 38 | DotNetStepHelper.AddDotNetSetupStep("Setup .NET Core","${{ env.DOTNET_CORE_VERSION }}"), 39 | DotNetStepHelper.AddDotNetRestoreStep("Restore","${{ env.WORKING_DIRECTORY }}"), 40 | DotNetStepHelper.AddDotNetBuildStep("Build","${{ env.WORKING_DIRECTORY }}","${{ env.CONFIGURATION }}","--no-restore"), 41 | DotNetStepHelper.AddDotNetTestStep("Test"), 42 | DotNetStepHelper.AddDotNetPublishStep("Publish","${{ env.WORKING_DIRECTORY }}", "${{ env.CONFIGURATION }}", "${{ env.AZURE_WEBAPP_PACKAGE_PATH }}", "-r win-x86 --self-contained true"), 43 | AzureStepHelper.AddAzureWebAppDeployStep("Deploy to Azure Web App","${{ env.AZURE_WEBAPP_NAME }}", "${{ env.AZURE_WEBAPP_PACKAGE_PATH }}", publishProfileName) 44 | }; 45 | root.jobs = new(); 46 | JobHelper jobHelper = new(); 47 | Job buildJob = jobHelper.AddJob( 48 | "Build job", 49 | platform + "-latest", 50 | buildSteps); 51 | root.jobs.Add("build", buildJob); 52 | 53 | //Act 54 | return GitHubActionsDotNet.Serialization.GitHubActionsSerialization.Serialize(root); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/templates/AzureFunctionTemplate.cs: -------------------------------------------------------------------------------- 1 | using GitHubActionsDotNet.Helpers; 2 | using GitHubActionsDotNet.Models; 3 | 4 | namespace WorkFlowGenerator.Templates; 5 | 6 | public static class AzureFunctionTemplate 7 | { 8 | public static string Get( 9 | string workflow_name, 10 | string branch_name, 11 | string azure_resource_name, 12 | string package_path, 13 | string dotnet_version, 14 | string project_root, 15 | string platform, 16 | string publishProfileName) 17 | { 18 | //Arrange 19 | GitHubActionsRoot root = new(); 20 | root.name = workflow_name; 21 | root.on = TriggerHelper.AddStandardPushTrigger(branch_name); 22 | root.env = new() 23 | { 24 | { "AZURE_FUNCTIONAPP_NAME", azure_resource_name }, 25 | { "AZURE_FUNCTIONAPP_PACKAGE_PATH", package_path }, 26 | { "CONFIGURATION", "Release" }, 27 | { "DOTNET_CORE_VERSION", dotnet_version }, 28 | { "WORKING_DIRECTORY", project_root }, 29 | { "DOTNET_CLI_TELEMETRY_OPTOUT", "1" }, 30 | { "DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1" }, 31 | { "DOTNET_NOLOGO", "true" }, 32 | { "DOTNET_GENERATE_ASPNET_CERTIFICATE", "false" }, 33 | { "DOTNET_ADD_GLOBAL_TOOLS_TO_PATH", "false" }, 34 | { "DOTNET_MULTILEVEL_LOOKUP", "0" } 35 | }; 36 | Step[] buildSteps = new Step[] { 37 | CommonStepHelper.AddCheckoutStep(), 38 | DotNetStepHelper.AddDotNetSetupStep("Setup .NET Core","${{ env.DOTNET_CORE_VERSION }}"), 39 | DotNetStepHelper.AddDotNetRestoreStep("Restore","${{ env.WORKING_DIRECTORY }}"), 40 | DotNetStepHelper.AddDotNetBuildStep("Build","${{ env.WORKING_DIRECTORY }}","${{ env.CONFIGURATION }}","--no-restore"), 41 | DotNetStepHelper.AddDotNetTestStep("Test"), 42 | DotNetStepHelper.AddDotNetPublishStep("Publish","${{ env.WORKING_DIRECTORY }}", "${{ env.CONFIGURATION }}", "${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}", "--no-build"), 43 | AzureStepHelper.AddAzureFunctionDeployStep("Deploy to Azure Function App","${{ env.AZURE_FUNCTIONAPP_NAME }}", "${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }}", publishProfileName) 44 | }; 45 | root.jobs = new(); 46 | JobHelper jobHelper = new(); 47 | Job buildJob = jobHelper.AddJob( 48 | "Build job", 49 | platform + "-latest", 50 | buildSteps); 51 | root.jobs.Add("build", buildJob); 52 | 53 | //Act 54 | return GitHubActionsDotNet.Serialization.GitHubActionsSerialization.Serialize(root); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Services/ProjectDiscoveryService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.IO.Abstractions; 5 | using System.Linq; 6 | using Spectre.Console; 7 | using WorkFlowGenerator.Exceptions; 8 | 9 | namespace WorkFlowGenerator.Services; 10 | 11 | public class ProjectDiscoveryService : IProjectDiscoveryService 12 | { 13 | private readonly IFileSystem _fileSystem; 14 | 15 | public ProjectDiscoveryService(IFileSystem fileSystem) 16 | { 17 | _fileSystem = fileSystem; 18 | } 19 | 20 | public string DiscoverProject(string path) 21 | { 22 | if (!(_fileSystem.File.Exists(path) || _fileSystem.Directory.Exists(path))) 23 | throw new CommandValidationException(string.Format(Resources.ValidationErrorMessages.DirectoryOrFileDoesNotExist, path)); 24 | 25 | var fileAttributes = _fileSystem.File.GetAttributes(path); 26 | 27 | // If a directory was passed in, search for a .sln or .csproj file 28 | if (fileAttributes.HasFlag(FileAttributes.Directory)) 29 | { 30 | // We did not find any solutions, so try and find individual projects 31 | var projectFiles = _fileSystem.Directory.GetFiles(path, "*.csproj").Concat(_fileSystem.Directory.GetFiles(path, "*.fsproj")).ToArray(); 32 | if (projectFiles.Length == 1) 33 | { 34 | AnsiConsole.WriteLine($"Project discovered: {projectFiles[0]}"); 35 | return _fileSystem.Path.GetFullPath(projectFiles[0]); 36 | } 37 | if (projectFiles.Length > 1) 38 | throw new CommandValidationException(string.Format(Resources.ValidationErrorMessages.DirectoryContainsMultipleProjects, path)); 39 | 40 | // At this point the path contains no solutions or projects, so throw an exception 41 | throw new CommandValidationException(string.Format(Resources.ValidationErrorMessages.DirectoryDoesNotContainSolutionsOrProjects, path)); 42 | } 43 | 44 | if ( 45 | (string.Compare(_fileSystem.Path.GetExtension(path), ".csproj", StringComparison.OrdinalIgnoreCase) == 0) || 46 | (string.Compare(_fileSystem.Path.GetExtension(path), ".fsproj", StringComparison.OrdinalIgnoreCase) == 0)) 47 | { 48 | AnsiConsole.WriteLine($"Project discovered: {_fileSystem.Path.GetFullPath(path)}"); 49 | return _fileSystem.Path.GetFullPath(path); 50 | } 51 | // At this point, we know the file passed in is not a valid project or solution 52 | throw new CommandValidationException(string.Format(Resources.ValidationErrorMessages.FileNotAValidSolutionOrProject, path)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WorkFlowGenerator 2 | 3 | A .NET global tool to generate workflows for GitHub Actions based on project configuration and user inputs. The tool is published to NuGet as well 4 | 5 | https://www.nuget.org/packages/dotnet-workflow-generator/ 6 | 7 | ## Getting Started 8 | 9 | The fastest way to use this tool is to install it using the .NET CLI 10 | 11 | ```cmd 12 | dotnet tool install --global dotnet-workflow-generator 13 | ``` 14 | 15 | and if you want to update 16 | 17 | ```cmd 18 | dotnet tool update --global dotnet-workflow-generator 19 | ``` 20 | 21 | After you have the tool installed, you can run it from a inside a directory with a `.csproj` in it, or pass the path to one directly 22 | 23 | ```cmd 24 | REM Run tool from inside folder 25 | cd C:\dev\somefolderwithaprojectfile 26 | dotnet-workflow-generator 27 | 28 | REM Pass path into tool 29 | dotnet-workflow-generator C:\dev\somefolderwithaprojectfile 30 | ``` 31 | 32 | When you run the tool, it will parse the `.csproj` in the folder and prompt you for a target location to publish. You will select an Azure Subscription, a Resource Group, and an Azure Resource. If the app is an Azure Function (determined by the presence of the `AzureFunctionsVersion` property) it will only list Function Apps to deploy to, otherwise, it will only list Web Apps. 33 | 34 | After you select your target, it will create a sample workflow based on the `TargetFramework` specified in the project file. 35 | 36 | ![Demo](https://github.com/isaacrlevin/WorkFlowGenerator/raw/main/static/demo.gif) 37 | 38 | ## Building from source 39 | 40 | You can run this code from source after cloning the repo. Once you have the code locally, you can install the tool by running the included `.cmd/.sh` file 41 | 42 | ### Windows 43 | ``` 44 | git clone https://github.com/isaacrlevin/WorkFlowGenerator.git 45 | cd WorkflowGenerator 46 | createtool.cmd 47 | ``` 48 | 49 | ### Mac/Linux 50 | ``` 51 | git clone https://github.com/isaacrlevin/WorkFlowGenerator.git 52 | cd WorkflowGenerator 53 | createtool.sh 54 | ``` 55 | 56 | At this point you will have whatever installed the latest version of the tool in the `main` branch. If you want to update the tool in the future, you can run the pack and update commands 57 | 58 | ``` 59 | dotnet pack 60 | dotnet tool update -g --add-source .\nupkg dotnet-workflow-generator 61 | ``` 62 | 63 | You can also run the app from Visual Studio/VS Code/.NET CLI with the following command from the folder with WorkflowGenerator.csproj inside it 64 | 65 | **NOTE: You will need to set a path of the .csproj you want to generate an workflow for using Debug Profiles in VS or passing the path into the command line** 66 | 67 | ``` 68 | dotnet run C:\dev\somefolderwithaprojectfileinit 69 | ``` 70 | ## Contributing 71 | 72 | I would love folks to contribute to this idea. Currently I see 2 main forms of contribution that can take place and below are the steps folks can take 73 | 74 | * You found a bug or some other issue (gap in docs, missing tests) 75 | * Create an issue (than a PR?) detailing what your expectation is vs what you are getting 76 | * You have an idea for additional functionality (want to add a new project type or target) 77 | * Create a discussion with your proposal and why you think it is a good idea. 78 | * More than likely I will ask you to do the work, so be ready 😊 79 | 80 | 81 | ## Open Source Tools Used in this project 82 | 83 | * [Spectre.Console](https://github.com/spectreconsole/spectre.console) 84 | * [Azure SDK](https://github.com/Azure/azure-sdk) 85 | * [IdentityModel.OidcClient](https://github.com/IdentityModel/IdentityModel.OidcClient) 86 | * [McMaster.Extensions.CommandLineUtils](https://github.com/natemcmaster/CommandLineUtils) 87 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/AzureIdentityHelpers/AzureIdentityFluentCredentialAdapter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Net.Http; 6 | using System.Text.RegularExpressions; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | using Azure.Core; 10 | using Microsoft.Azure.Management.ResourceManager.Fluent; 11 | using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication; 12 | using Microsoft.Rest; 13 | using Microsoft.Rest.Azure.Authentication; 14 | 15 | namespace Azure.Identity.Extensions; 16 | 17 | public class AzureIdentityFluentCredentialAdapter : AzureCredentials 18 | { 19 | private IDictionary credentialsCache = new ConcurrentDictionary(); 20 | private TokenCredential tokenCredential; 21 | 22 | public AzureIdentityFluentCredentialAdapter(TokenCredential tokenCredential, string tenantId, AzureEnvironment environment) : base(default(DeviceCredentialInformation), tenantId, environment) 23 | { 24 | this.tokenCredential = tokenCredential; 25 | } 26 | 27 | public AzureIdentityFluentCredentialAdapter(string tenantId, AzureEnvironment environment) : base(default(DeviceCredentialInformation), tenantId, environment) 28 | { 29 | this.tokenCredential = new DefaultAzureCredential(); 30 | } 31 | 32 | public async override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) 33 | { 34 | 35 | // BEING COPY FROM FLUENT 36 | var adSettings = new ActiveDirectoryServiceSettings 37 | { 38 | AuthenticationEndpoint = new Uri(Environment.AuthenticationEndpoint), 39 | TokenAudience = new Uri(Environment.ManagementEndpoint), 40 | ValidateAuthority = true 41 | }; 42 | 43 | string url = request.RequestUri.ToString(); 44 | if (url.StartsWith(Environment.GraphEndpoint, StringComparison.OrdinalIgnoreCase)) 45 | { 46 | adSettings.TokenAudience = new Uri(Environment.GraphEndpoint); 47 | } 48 | 49 | string host = request.RequestUri.Host; 50 | if (host.EndsWith(Environment.KeyVaultSuffix, StringComparison.OrdinalIgnoreCase)) 51 | { 52 | var resource = new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://")); 53 | if (credentialsCache.ContainsKey(new Uri(Regex.Replace(Environment.KeyVaultSuffix, "^.", "https://")))) 54 | { 55 | adSettings.TokenAudience = resource; 56 | } 57 | else 58 | { 59 | using (var r = new HttpRequestMessage(request.Method, url)) 60 | { 61 | var response = await new HttpClient().SendAsync(r).ConfigureAwait(false); 62 | 63 | if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized && response.Headers.WwwAuthenticate != null) 64 | { 65 | var header = response.Headers.WwwAuthenticate.ElementAt(0).ToString(); 66 | var regex = new Regex("authorization=\"([^\"]+)\""); 67 | var match = regex.Match(header); 68 | adSettings.AuthenticationEndpoint = new Uri(match.Groups[1].Value); 69 | regex = new Regex("resource=\"([^\"]+)\""); 70 | match = regex.Match(header); 71 | adSettings.TokenAudience = new Uri(match.Groups[1].Value); 72 | } 73 | } 74 | } 75 | } 76 | 77 | // END COPY FROM FLUENT 78 | 79 | if (!credentialsCache.ContainsKey(adSettings.TokenAudience)) 80 | { 81 | credentialsCache[adSettings.TokenAudience] = new AzureIdentityCredentialAdapter(this.tokenCredential); 82 | } 83 | await credentialsCache[adSettings.TokenAudience].ProcessHttpRequestAsync(request, cancellationToken); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/WorkFlowGenerator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | true 7 | dotnet-workflow-generator 8 | dotnet-workflow-generator 9 | ./nupkg 10 | dotnet-workflow-generator 11 | Isaac Levin 12 | A .NET global tool to generate workflows for GitHub Actions based on project configuration and user inputs 13 | Copyright (c) Isaac Levin 14 | A .NET global tool to generate workflows for GitHub Actions based on project configuration and user inputs 15 | dotnet-workflow-generator 16 | MIT 17 | https://github.com/isaacrlevin/WorkFlowGenerator 18 | See https://github.com/isaacrlevin/WorkFlowGenerator/releases for release information 19 | $(Version) 20 | git 21 | dotnet github workflow actions generate 22 | https://github.com/isaacrlevin/WorkFlowGenerator.git 23 | README.md 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | Always 35 | 36 | 37 | Always 38 | 39 | 40 | Always 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | True 53 | \ 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /.github/workflows/main_release.yaml: -------------------------------------------------------------------------------- 1 | name: "Build" 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths-ignore: 8 | - '**/*.md' 9 | - '**/*.gitignore' 10 | - '**/*.gitattributes' 11 | workflow_dispatch: 12 | branches: 13 | - main 14 | paths-ignore: 15 | - '**/*.md' 16 | - '**/*.gitignore' 17 | - '**/*.gitattributes' 18 | 19 | jobs: 20 | build: 21 | name: Build 22 | runs-on: ubuntu-latest 23 | outputs: 24 | version: ${{ steps.set_proj_version.outputs.VERSION }} 25 | relnotes: ${{ steps.set_proj_version.outputs.RELNOTES }} 26 | env: 27 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 28 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 29 | DOTNET_NOLOGO: true 30 | DOTNET_GENERATE_ASPNET_CERTIFICATE: false 31 | DOTNET_ADD_GLOBAL_TOOLS_TO_PATH: false 32 | DOTNET_MULTILEVEL_LOOKUP: 0 33 | 34 | 35 | steps: 36 | - uses: actions/checkout@v2 37 | with: 38 | fetch-depth: 0 39 | 40 | - name: Setup .NET Core SDK 41 | uses: actions/setup-dotnet@v1.8.2 42 | with: 43 | dotnet-version: 6.0.x 44 | 45 | - name: Nerdbank.GitVersioning 46 | uses: dotnet/nbgv@v0.4.0 47 | with: 48 | setCommonVars: true 49 | 50 | - run: echo "BuildNumber - ${{ env.GitBuildVersionSimple }}" 51 | 52 | - name: Update appsettings.json 53 | run: | 54 | # Update AppSettings.json. This must be done before build. 55 | $appsettings= get-content "./src/WorkFlowGenerator/appsettings.json" -raw | ConvertFrom-Json 56 | $appsettings.GitHubClientId = "${{ secrets.GITHUBCLIENTID }}" 57 | $appsettings.GitHubClientSecret = "${{ secrets.GITHUBCLIENTSECRET }}" 58 | $appsettings | ConvertTo-Json -depth 32| set-content './src/WorkFlowGenerator/appsettings.json' 59 | shell: pwsh 60 | 61 | - name: Restore 62 | run: dotnet restore 63 | working-directory: src 64 | 65 | - name: Build 66 | run: dotnet build --configuration Release --no-restore 67 | working-directory: src 68 | 69 | - name: Test 70 | run: dotnet test 71 | working-directory: src 72 | 73 | - name: Pack 74 | run: dotnet pack --configuration Release -o finalpackage --no-build /p:Version=${{ env.GitBuildVersionSimple }} 75 | working-directory: src 76 | 77 | - name: Publish artifact 78 | uses: actions/upload-artifact@master 79 | with: 80 | name: nupkg 81 | path: src/finalpackage 82 | 83 | - name: Get version 84 | id: set_proj_version 85 | shell: pwsh 86 | run: | 87 | [xml]$nuspec = Get-Content /home/runner/work/WorkFlowGenerator/WorkFlowGenerator/src/WorkFlowGenerator/WorkFlowGenerator.csproj 88 | $relnotes=$nuspec.project.propertygroup.packagereleasenotes 89 | Write-Output "::set-output name=VERSION::${{ env.GitBuildVersionSimple }} " 90 | Write-Output "::set-output name=RELNOTES::$relnotes" 91 | deploy: 92 | needs: build 93 | environment: 94 | name: production 95 | url: https://www.nuget.org/packages/dotnet-workflow-generator/ 96 | name: Sign and publish 97 | runs-on: ubuntu-latest 98 | steps: 99 | - name: Download Package artifact 100 | uses: actions/download-artifact@v2 101 | with: 102 | name: nupkg 103 | 104 | - name: Setup .NET Core SDK 105 | uses: actions/setup-dotnet@v1.8.2 106 | with: 107 | dotnet-version: 6.0.x 108 | 109 | - name: Push to NuGet 110 | run: dotnet nuget push **/*.nupkg -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json --skip-duplicate 111 | 112 | - name: Generate changelog 113 | id: changelog 114 | uses: jaywcjlove/changelog-generator@main 115 | with: 116 | token: ${{ secrets.GITHUB_TOKEN }} 117 | filter: '' 118 | env: 119 | commitMode: true 120 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 121 | 122 | - name: Tag and Release 123 | id: tag_release 124 | uses: softprops/action-gh-release@v0.1.13 125 | with: 126 | tag_name: ${{ needs.build.outputs.version }} 127 | files: | 128 | **/*.nupkg 129 | body: | 130 | ${{ steps.changelog.outputs.compareurl }} 131 | ${{ steps.changelog.outputs.changelog }} 132 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Resources/ValidationErrorMessages.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace WorkFlowGenerator.Resources 12 | { 13 | using System; 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class ValidationErrorMessages 26 | { 27 | 28 | private static global::System.Resources.ResourceManager resourceMan; 29 | 30 | private static global::System.Globalization.CultureInfo resourceCulture; 31 | 32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 33 | internal ValidationErrorMessages() 34 | { 35 | } 36 | 37 | /// 38 | /// Returns the cached ResourceManager instance used by this class. 39 | /// 40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 41 | internal static global::System.Resources.ResourceManager ResourceManager 42 | { 43 | get 44 | { 45 | if (object.ReferenceEquals(resourceMan, null)) 46 | { 47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WorkFlowGenerator.Resources.ValidationErrorMessages", typeof(ValidationErrorMessages).Assembly); 48 | resourceMan = temp; 49 | } 50 | return resourceMan; 51 | } 52 | } 53 | 54 | /// 55 | /// Overrides the current thread's CurrentUICulture property for all 56 | /// resource lookups using this strongly typed resource class. 57 | /// 58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 59 | internal static global::System.Globalization.CultureInfo Culture 60 | { 61 | get 62 | { 63 | return resourceCulture; 64 | } 65 | set 66 | { 67 | resourceCulture = value; 68 | } 69 | } 70 | 71 | /// 72 | /// Looks up a localized string similar to Specify which project file to use because the directory '{0}' contains more than one.. 73 | /// 74 | internal static string DirectoryContainsMultipleProjects 75 | { 76 | get 77 | { 78 | return ResourceManager.GetString("DirectoryContainsMultipleProjects", resourceCulture); 79 | } 80 | } 81 | 82 | /// 83 | /// Looks up a localized string similar to Specify which solution file to use because the directory '{0}' contains more than one.. 84 | /// 85 | internal static string DirectoryContainsMultipleSolutions 86 | { 87 | get 88 | { 89 | return ResourceManager.GetString("DirectoryContainsMultipleSolutions", resourceCulture); 90 | } 91 | } 92 | 93 | /// 94 | /// Looks up a localized string similar to The directory '{0}' does not contain any solutions or projects.. 95 | /// 96 | internal static string DirectoryDoesNotContainSolutionsOrProjects 97 | { 98 | get 99 | { 100 | return ResourceManager.GetString("DirectoryDoesNotContainSolutionsOrProjects", resourceCulture); 101 | } 102 | } 103 | 104 | /// 105 | /// Looks up a localized string similar to The directory or file '{0}' does not exist.. 106 | /// 107 | internal static string DirectoryOrFileDoesNotExist 108 | { 109 | get 110 | { 111 | return ResourceManager.GetString("DirectoryOrFileDoesNotExist", resourceCulture); 112 | } 113 | } 114 | 115 | /// 116 | /// Looks up a localized string similar to The file '{0}' is not a valid solution or project.. 117 | /// 118 | internal static string FileNotAValidSolutionOrProject 119 | { 120 | get 121 | { 122 | return ResourceManager.GetString("FileNotAValidSolutionOrProject", resourceCulture); 123 | } 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator.Tests/WorkflowGeneratorTemplateTests.cs: -------------------------------------------------------------------------------- 1 | using GitHubActionsDotNet.Helpers; 2 | using GitHubActionsDotNet.Models; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using WorkFlowGenerator.Templates; 5 | 6 | namespace WorkFlowGenerator.Tests; 7 | 8 | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] 9 | [TestClass] 10 | public class WorkflowGeneratorTemplateTests 11 | { 12 | [TestMethod] 13 | public void FunctionTest() 14 | { 15 | //Arrange 16 | string workflow_name = "Workflow generator for functions"; 17 | string branch_name = "main"; 18 | string azure_resource_name = "myazurefunction"; 19 | string package_path = "function/function.zip"; 20 | string dotnet_version = "3.1.x"; 21 | string project_root = "src/"; 22 | string platform = "windows"; 23 | string publishProfileName = "${{ secrets.PUBLISH_PROFILE }}"; 24 | 25 | //Act 26 | string yaml = AzureFunctionTemplate.Get(workflow_name, 27 | branch_name, 28 | azure_resource_name, 29 | package_path, 30 | dotnet_version, 31 | project_root, 32 | platform, 33 | publishProfileName); 34 | 35 | //Assert 36 | string expected = @" 37 | name: Workflow generator for functions 38 | on: 39 | push: 40 | branches: 41 | - main 42 | env: 43 | AZURE_FUNCTIONAPP_NAME: myazurefunction 44 | AZURE_FUNCTIONAPP_PACKAGE_PATH: function/function.zip 45 | CONFIGURATION: Release 46 | DOTNET_CORE_VERSION: 3.1.x 47 | WORKING_DIRECTORY: src/ 48 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 49 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 50 | DOTNET_NOLOGO: true 51 | DOTNET_GENERATE_ASPNET_CERTIFICATE: false 52 | DOTNET_ADD_GLOBAL_TOOLS_TO_PATH: false 53 | DOTNET_MULTILEVEL_LOOKUP: 0 54 | jobs: 55 | build: 56 | name: Build job 57 | runs-on: windows-latest 58 | steps: 59 | - uses: actions/checkout@v2 60 | - name: Setup .NET Core 61 | uses: actions/setup-dotnet@v1 62 | with: 63 | dotnet-version: ${{ env.DOTNET_CORE_VERSION }} 64 | - name: Restore 65 | run: dotnet restore ${{ env.WORKING_DIRECTORY }} 66 | - name: Build 67 | run: dotnet build ${{ env.WORKING_DIRECTORY }} --configuration ${{ env.CONFIGURATION }} --no-restore 68 | - name: Test 69 | run: dotnet test 70 | - name: Publish 71 | run: dotnet publish ${{ env.WORKING_DIRECTORY }} --configuration ${{ env.CONFIGURATION }} --output ${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }} --no-build 72 | - name: Deploy to Azure Function App 73 | uses: Azure/functions-action@v1 74 | with: 75 | app-name: ${{ env.AZURE_FUNCTIONAPP_NAME }} 76 | publish-profile: ${{ secrets.PUBLISH_PROFILE }} 77 | package: ${{ env.AZURE_FUNCTIONAPP_PACKAGE_PATH }} 78 | "; 79 | expected = Utility.TrimNewLines(expected); 80 | Assert.AreEqual(expected, yaml); 81 | } 82 | 83 | [TestMethod] 84 | public void WebAppTest() 85 | { 86 | //Arrange 87 | string workflow_name = "Workflow generator for webapps"; 88 | string branch_name = "main"; 89 | string azure_resource_name = "myazurewebapp"; 90 | string package_path = "webapp/webapp.zip"; 91 | string dotnet_version = "3.1.x"; 92 | string project_root = "src/"; 93 | string platform = "windows"; 94 | string publishProfileName = "${{ secrets.PUBLISH_PROFILE }}"; 95 | 96 | //Act 97 | string yaml = AzureWebAppTemplate.Get(workflow_name, 98 | branch_name, 99 | azure_resource_name, 100 | package_path, 101 | dotnet_version, 102 | project_root, 103 | platform, 104 | publishProfileName); 105 | 106 | //Assert 107 | string expected = @" 108 | name: Workflow generator for webapps 109 | on: 110 | push: 111 | branches: 112 | - main 113 | env: 114 | AZURE_WEBAPP_NAME: myazurewebapp 115 | AZURE_WEBAPP_PACKAGE_PATH: webapp/webapp.zip 116 | CONFIGURATION: Release 117 | DOTNET_CORE_VERSION: 3.1.x 118 | WORKING_DIRECTORY: src/ 119 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 120 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 121 | DOTNET_NOLOGO: true 122 | DOTNET_GENERATE_ASPNET_CERTIFICATE: false 123 | DOTNET_ADD_GLOBAL_TOOLS_TO_PATH: false 124 | DOTNET_MULTILEVEL_LOOKUP: 0 125 | jobs: 126 | build: 127 | name: Build job 128 | runs-on: windows-latest 129 | steps: 130 | - uses: actions/checkout@v2 131 | - name: Setup .NET Core 132 | uses: actions/setup-dotnet@v1 133 | with: 134 | dotnet-version: ${{ env.DOTNET_CORE_VERSION }} 135 | - name: Restore 136 | run: dotnet restore ${{ env.WORKING_DIRECTORY }} 137 | - name: Build 138 | run: dotnet build ${{ env.WORKING_DIRECTORY }} --configuration ${{ env.CONFIGURATION }} --no-restore 139 | - name: Test 140 | run: dotnet test 141 | - name: Publish 142 | run: dotnet publish ${{ env.WORKING_DIRECTORY }} --configuration ${{ env.CONFIGURATION }} --output ${{ env.AZURE_WEBAPP_PACKAGE_PATH }} -r win-x86 --self-contained true 143 | - name: Deploy to Azure Web App 144 | uses: Azure/webapps-deploy@v2 145 | with: 146 | app-name: ${{ env.AZURE_WEBAPP_NAME }} 147 | publish-profile: ${{ secrets.PUBLISH_PROFILE }} 148 | package: ${{ env.AZURE_WEBAPP_PACKAGE_PATH }} 149 | "; 150 | expected = Utility.TrimNewLines(expected); 151 | Assert.AreEqual(expected, yaml); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Services/AzureService.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Threading.Tasks; 3 | using Azure.Identity; 4 | using Azure.Identity.Extensions; 5 | using Azure.ResourceManager; 6 | using Azure.ResourceManager.Resources; 7 | using Microsoft.Azure.Management.AppService.Fluent; 8 | using Microsoft.Azure.Management.ResourceManager.Fluent; 9 | using Spectre.Console; 10 | using System.Collections.Generic; 11 | using System.Net.Http; 12 | 13 | namespace WorkFlowGenerator.Services; 14 | 15 | public class AzureService : IAzureService 16 | { 17 | private ArmClient _armClient; 18 | private AzureCliCredential _credential; 19 | private AzureIdentityFluentCredentialAdapter _credentialAdapter; 20 | private Subscription _subscription; 21 | private ResourceGroup _resourceGroup; 22 | private Azure.Core.AccessToken _accessToken; 23 | 24 | public AzureService() 25 | { 26 | _credential = new AzureCliCredential(); 27 | _armClient = new ArmClient(_credential); 28 | } 29 | 30 | public Subscription GetSubscription() 31 | { 32 | List subscriptions = null; 33 | AnsiConsole.Status() 34 | .Start("Gathering Subscriptions...", ctx => 35 | { 36 | subscriptions = _armClient.GetSubscriptions().ToList(); 37 | }); 38 | 39 | var pickedSub = AnsiConsole.Prompt( 40 | new SelectionPrompt<(string, string)>() 41 | .Title("What Azure subscription would you like to deploy to?") 42 | .PageSize(10) 43 | .AddChoices(subscriptions.Select(a => (a.Data.SubscriptionGuid, a.Data.DisplayName)))); 44 | 45 | _subscription = subscriptions.Where(a => a.Data.SubscriptionGuid == pickedSub.Item1).FirstOrDefault(); 46 | 47 | AnsiConsole.WriteLine($"The selected subscription is {_subscription.Data.SubscriptionGuid}"); 48 | 49 | _accessToken = _credential.GetTokenAsync(new Azure.Core.TokenRequestContext(new[] { "https://management.azure.com/.default" })).Result; 50 | return _subscription; 51 | } 52 | 53 | public ResourceGroup GetResourceGroups() 54 | { 55 | List resourceGroups = null; 56 | AnsiConsole.Status().Start("Gathering Resource Groups...", ctx => 57 | { 58 | resourceGroups = _subscription.GetResourceGroups().ToList(); 59 | }); 60 | 61 | var pickedRg = AnsiConsole.Prompt( 62 | new SelectionPrompt() 63 | .Title($"What Azure Resource Group in {_subscription.Data.DisplayName} would you like to deploy to?") 64 | .PageSize(10) 65 | .MoreChoicesText("[grey](Move up and down to reveal more resource groups)[/]") 66 | .AddChoices(resourceGroups.Select(a => a.Data.Name))); 67 | 68 | _resourceGroup = resourceGroups.Where(a => a.Data.Name == pickedRg).FirstOrDefault(); 69 | 70 | AnsiConsole.WriteLine($"The selected Resource Group is {_resourceGroup.Data.Name}"); 71 | 72 | return _resourceGroup; 73 | } 74 | 75 | public async Task GetWebApps() 76 | { 77 | 78 | if (_credentialAdapter == null) 79 | { 80 | _credentialAdapter = new AzureIdentityFluentCredentialAdapter(_credential, _subscription.Data.TenantId, AzureEnvironment.AzureGlobalCloud); 81 | } 82 | List websites = null; 83 | AnsiConsole.Status().Start("Gathering Web Apps...", ctx => 84 | { 85 | websites = Microsoft.Azure.Management.Fluent.Azure 86 | .Authenticate(_credentialAdapter) 87 | .WithSubscription(_subscription.Data.DisplayName) 88 | .AppServices.WebApps.ListByResourceGroupAsync(_resourceGroup.Data.Name).Result.ToList(); 89 | }); 90 | 91 | var pickedwebsites = AnsiConsole.Prompt( 92 | new SelectionPrompt() 93 | .Title($"What Azure Web App in {_resourceGroup.Data.Name} would you like to deploy to?") 94 | .PageSize(10) 95 | .MoreChoicesText("[grey](Move up and down to reveal more resource groups)[/]") 96 | .AddChoices(websites.Select(a => a.Name))); 97 | 98 | var webapp = websites.Where(a => a.Name == pickedwebsites).FirstOrDefault(); 99 | 100 | AnsiConsole.WriteLine($"The selected Web App is {webapp.Name}"); 101 | return webapp; 102 | } 103 | 104 | public async Task GetFunctions() 105 | { 106 | if (_credentialAdapter == null) 107 | { 108 | _credentialAdapter = new AzureIdentityFluentCredentialAdapter(_credential, _subscription.Data.TenantId, AzureEnvironment.AzureGlobalCloud); 109 | } 110 | 111 | List functions = null; 112 | AnsiConsole.Status().Start("Gathering Functions...", ctx => 113 | { 114 | functions = Microsoft.Azure.Management.Fluent.Azure 115 | .Authenticate(_credentialAdapter) 116 | .WithSubscription(_subscription.Data.DisplayName) 117 | .AppServices.FunctionApps.ListByResourceGroupAsync(_resourceGroup.Data.Name).Result.ToList(); 118 | }); 119 | 120 | var pickedFunctions = AnsiConsole.Prompt( 121 | new SelectionPrompt() 122 | .Title($"What Azure Function in {_resourceGroup.Data.Name} would you like to deploy to?") 123 | .PageSize(10) 124 | .MoreChoicesText("[grey](Move up and down to reveal more resource groups)[/]") 125 | .AddChoices(functions.Select(a => a.Name))); 126 | 127 | var function = functions.Where(a => a.Name == pickedFunctions).FirstOrDefault(); 128 | AnsiConsole.WriteLine($"The selected Function is {function.Name}"); 129 | return function; 130 | } 131 | 132 | public async Task GetPublishProfile(string resource) 133 | { 134 | using var httpClient = new HttpClient 135 | { 136 | BaseAddress = new System.Uri("https://management.azure.com") 137 | }; 138 | 139 | httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _accessToken.Token); 140 | 141 | using var response = httpClient.PostAsync($"subscriptions/{_subscription.Data.DisplayName}/resourceGroups/{_resourceGroup.Data.Name}/providers/Microsoft.Web/sites/{resource}/publishxml?api-version=2018-02-01", new StringContent("{}", System.Text.Encoding.UTF8, "application/json")).Result; 142 | 143 | var content = await response.Content.ReadAsStringAsync(); 144 | 145 | return content; 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/.editorconfig: -------------------------------------------------------------------------------- 1 | # To learn more about .editorconfig see https://aka.ms/editorconfigdocs 2 | ############################### 3 | # Core EditorConfig Options # 4 | ############################### 5 | # All files 6 | [*] 7 | indent_style = space 8 | 9 | # XML project files 10 | [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] 11 | indent_size = 2 12 | 13 | # XML config files 14 | [*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] 15 | indent_size = 2 16 | 17 | # Code files 18 | [*.{cs,csx,vb,vbx}] 19 | indent_size = 4 20 | insert_final_newline = true 21 | charset = utf-8-bom 22 | ############################### 23 | # .NET Coding Conventions # 24 | ############################### 25 | [*.{cs,vb}] 26 | # Organize usings 27 | dotnet_sort_system_directives_first = true 28 | # this. preferences 29 | dotnet_style_qualification_for_field = false:silent 30 | dotnet_style_qualification_for_property = false:silent 31 | dotnet_style_qualification_for_method = false:silent 32 | dotnet_style_qualification_for_event = false:silent 33 | # Language keywords vs BCL types preferences 34 | dotnet_style_predefined_type_for_locals_parameters_members = true:silent 35 | dotnet_style_predefined_type_for_member_access = true:silent 36 | # Parentheses preferences 37 | dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent 38 | dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent 39 | dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent 40 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent 41 | # Modifier preferences 42 | dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent 43 | dotnet_style_readonly_field = true:suggestion 44 | # Expression-level preferences 45 | dotnet_style_object_initializer = true:suggestion 46 | dotnet_style_collection_initializer = true:suggestion 47 | dotnet_style_explicit_tuple_names = true:suggestion 48 | dotnet_style_null_propagation = true:suggestion 49 | dotnet_style_coalesce_expression = true:suggestion 50 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent 51 | dotnet_style_prefer_inferred_tuple_names = true:suggestion 52 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion 53 | dotnet_style_prefer_auto_properties = true:silent 54 | dotnet_style_prefer_conditional_expression_over_assignment = true:silent 55 | dotnet_style_prefer_conditional_expression_over_return = true:silent 56 | ############################### 57 | # Naming Conventions # 58 | ############################### 59 | # Style Definitions 60 | dotnet_naming_style.pascal_case_style.capitalization = pascal_case 61 | # Use PascalCase for constant fields 62 | dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion 63 | dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields 64 | dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style 65 | dotnet_naming_symbols.constant_fields.applicable_kinds = field 66 | dotnet_naming_symbols.constant_fields.applicable_accessibilities = * 67 | dotnet_naming_symbols.constant_fields.required_modifiers = const 68 | ############################### 69 | # C# Coding Conventions # 70 | ############################### 71 | [*.cs] 72 | # var preferences 73 | csharp_style_var_for_built_in_types = true:silent 74 | csharp_style_var_when_type_is_apparent = true:silent 75 | csharp_style_var_elsewhere = true:silent 76 | # Expression-bodied members 77 | csharp_style_expression_bodied_methods = false:silent 78 | csharp_style_expression_bodied_constructors = false:silent 79 | csharp_style_expression_bodied_operators = false:silent 80 | csharp_style_expression_bodied_properties = true:silent 81 | csharp_style_expression_bodied_indexers = true:silent 82 | csharp_style_expression_bodied_accessors = true:silent 83 | # Pattern matching preferences 84 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion 85 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion 86 | # Null-checking preferences 87 | csharp_style_throw_expression = true:suggestion 88 | csharp_style_conditional_delegate_call = true:suggestion 89 | # Modifier preferences 90 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion 91 | # Expression-level preferences 92 | csharp_prefer_braces = true:silent 93 | csharp_style_deconstructed_variable_declaration = true:suggestion 94 | csharp_prefer_simple_default_expression = true:suggestion 95 | csharp_style_pattern_local_over_anonymous_function = true:suggestion 96 | csharp_style_inlined_variable_declaration = true:suggestion 97 | ############################### 98 | # C# Formatting Rules # 99 | ############################### 100 | # New line preferences 101 | csharp_new_line_before_open_brace = all 102 | csharp_new_line_before_else = true 103 | csharp_new_line_before_catch = true 104 | csharp_new_line_before_finally = true 105 | csharp_new_line_before_members_in_object_initializers = true 106 | csharp_new_line_before_members_in_anonymous_types = true 107 | csharp_new_line_between_query_expression_clauses = true 108 | # Indentation preferences 109 | csharp_indent_case_contents = true 110 | csharp_indent_switch_labels = true 111 | csharp_indent_labels = flush_left 112 | # Space preferences 113 | csharp_space_after_cast = false 114 | csharp_space_after_keywords_in_control_flow_statements = true 115 | csharp_space_between_method_call_parameter_list_parentheses = false 116 | csharp_space_between_method_declaration_parameter_list_parentheses = false 117 | csharp_space_between_parentheses = false 118 | csharp_space_before_colon_in_inheritance_clause = true 119 | csharp_space_after_colon_in_inheritance_clause = true 120 | csharp_space_around_binary_operators = before_and_after 121 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 122 | csharp_space_between_method_call_name_and_opening_parenthesis = false 123 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 124 | # Wrapping preferences 125 | csharp_preserve_single_line_statements = true 126 | csharp_preserve_single_line_blocks = true 127 | csharp_style_namespace_declarations=file_scoped:warning 128 | ############################### 129 | # VB Coding Conventions # 130 | ############################### 131 | [*.vb] 132 | # Modifier preferences 133 | visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:suggestion 134 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Resources/ValidationErrorMessages.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | Specify which project file to use because the directory '{0}' contains more than one. 122 | 123 | 124 | Specify which solution file to use because the directory '{0}' contains more than one. 125 | 126 | 127 | The directory '{0}' does not contain any solutions or projects. 128 | 129 | 130 | The directory or file '{0}' does not exist. 131 | 132 | 133 | The file '{0}' is not a valid solution or project. 134 | 135 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Nuget personal access tokens and Credentials 210 | # nuget.config 211 | 212 | # Microsoft Azure Build Output 213 | csx/ 214 | *.build.csdef 215 | 216 | # Microsoft Azure Emulator 217 | ecf/ 218 | rcf/ 219 | 220 | # Windows Store app package directories and files 221 | AppPackages/ 222 | BundleArtifacts/ 223 | Package.StoreAssociation.xml 224 | _pkginfo.txt 225 | *.appx 226 | *.appxbundle 227 | *.appxupload 228 | 229 | # Visual Studio cache files 230 | # files ending in .cache can be ignored 231 | *.[Cc]ache 232 | # but keep track of directories ending in .cache 233 | !?*.[Cc]ache/ 234 | 235 | # Others 236 | ClientBin/ 237 | ~$* 238 | *~ 239 | *.dbmdl 240 | *.dbproj.schemaview 241 | *.jfm 242 | *.pfx 243 | *.publishsettings 244 | orleans.codegen.cs 245 | 246 | # Including strong name files can present a security risk 247 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 248 | #*.snk 249 | 250 | # Since there are multiple workflows, uncomment next line to ignore bower_components 251 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 252 | #bower_components/ 253 | 254 | # RIA/Silverlight projects 255 | Generated_Code/ 256 | 257 | # Backup & report files from converting an old project file 258 | # to a newer Visual Studio version. Backup files are not needed, 259 | # because we have git ;-) 260 | _UpgradeReport_Files/ 261 | Backup*/ 262 | UpgradeLog*.XML 263 | UpgradeLog*.htm 264 | ServiceFabricBackup/ 265 | *.rptproj.bak 266 | 267 | # SQL Server files 268 | *.mdf 269 | *.ldf 270 | *.ndf 271 | 272 | # Business Intelligence projects 273 | *.rdl.data 274 | *.bim.layout 275 | *.bim_*.settings 276 | *.rptproj.rsuser 277 | *- [Bb]ackup.rdl 278 | *- [Bb]ackup ([0-9]).rdl 279 | *- [Bb]ackup ([0-9][0-9]).rdl 280 | 281 | # Microsoft Fakes 282 | FakesAssemblies/ 283 | 284 | # GhostDoc plugin setting file 285 | *.GhostDoc.xml 286 | 287 | # Node.js Tools for Visual Studio 288 | .ntvs_analysis.dat 289 | node_modules/ 290 | 291 | # Visual Studio 6 build log 292 | *.plg 293 | 294 | # Visual Studio 6 workspace options file 295 | *.opt 296 | 297 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 298 | *.vbw 299 | 300 | # Visual Studio LightSwitch build output 301 | **/*.HTMLClient/GeneratedArtifacts 302 | **/*.DesktopClient/GeneratedArtifacts 303 | **/*.DesktopClient/ModelManifest.xml 304 | **/*.Server/GeneratedArtifacts 305 | **/*.Server/ModelManifest.xml 306 | _Pvt_Extensions 307 | 308 | # Paket dependency manager 309 | .paket/paket.exe 310 | paket-files/ 311 | 312 | # FAKE - F# Make 313 | .fake/ 314 | 315 | # CodeRush personal settings 316 | .cr/personal 317 | 318 | # Python Tools for Visual Studio (PTVS) 319 | __pycache__/ 320 | *.pyc 321 | 322 | # Cake - Uncomment if you are using it 323 | # tools/** 324 | # !tools/packages.config 325 | 326 | # Tabs Studio 327 | *.tss 328 | 329 | # Telerik's JustMock configuration file 330 | *.jmconfig 331 | 332 | # BizTalk build output 333 | *.btp.cs 334 | *.btm.cs 335 | *.odx.cs 336 | *.xsd.cs 337 | 338 | # OpenCover UI analysis results 339 | OpenCover/ 340 | 341 | # Azure Stream Analytics local run output 342 | ASALocalRun/ 343 | 344 | # MSBuild Binary and Structured Log 345 | *.binlog 346 | 347 | # NVidia Nsight GPU debugger configuration file 348 | *.nvuser 349 | 350 | # MFractors (Xamarin productivity tool) working folder 351 | .mfractor/ 352 | 353 | # Local History for Visual Studio 354 | .localhistory/ 355 | 356 | # BeatPulse healthcheck temp database 357 | healthchecksdb 358 | 359 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 360 | MigrationBackup/ 361 | 362 | # Ionide (cross platform F# VS Code tools) working folder 363 | .ionide/ 364 | 365 | # Fody - auto-generated XML schema 366 | FodyWeavers.xsd 367 | 368 | # VS Code files for those working on multiple tools 369 | .vscode/* 370 | !.vscode/settings.json 371 | !.vscode/tasks.json 372 | !.vscode/launch.json 373 | !.vscode/extensions.json 374 | *.code-workspace 375 | 376 | # Local History for Visual Studio Code 377 | .history/ 378 | 379 | # Windows Installer files from build outputs 380 | *.cab 381 | *.msi 382 | *.msix 383 | *.msm 384 | *.msp 385 | 386 | # JetBrains Rider 387 | .idea/ 388 | *.sln.iml 389 | /src/WorkFlowGenerator/appsettings.Development.json 390 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Services/GitHubService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.IO; 5 | using System.Net.Http; 6 | using System.Net.Http.Json; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Web; 10 | using Microsoft.AspNetCore.Builder; 11 | using Microsoft.AspNetCore.Http; 12 | using Microsoft.Extensions.Hosting; 13 | using Microsoft.Extensions.Logging; 14 | using Newtonsoft.Json; 15 | using Octokit; 16 | using WorkFlowGenerator.Models; 17 | using WorkFlowGenerator.Models.GitHub; 18 | 19 | namespace WorkFlowGenerator.Services; 20 | 21 | public class GitHubService : IGitHubService 22 | { 23 | GitHubClient _gitHub = new GitHubClient(new ProductHeaderValue("WorkflowGenerator")); 24 | HttpClient client = new HttpClient(); 25 | private AppSettings _options; 26 | private string _accessToken; 27 | 28 | public GitHubService(Microsoft.Extensions.Options.IOptionsMonitor optionsAccessor) 29 | { 30 | _options = optionsAccessor.CurrentValue; 31 | client.BaseAddress = new Uri("https://api.github.com"); 32 | client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("WorkflowGenerator", "1.0")); 33 | client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); 34 | } 35 | void OpenBrowser(string url) 36 | { 37 | try 38 | { 39 | Process.Start(url); 40 | } 41 | catch 42 | { 43 | // hack because of this: https://github.com/dotnet/corefx/issues/10361 44 | if (OperatingSystem.IsWindows()) 45 | { 46 | url = url.Replace("&", "^&"); 47 | Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }); 48 | } 49 | else if (OperatingSystem.IsLinux()) 50 | { 51 | Process.Start("xdg-open", url); 52 | } 53 | else if (OperatingSystem.IsMacOS()) 54 | { 55 | Process.Start("open", url); 56 | } 57 | else 58 | { 59 | throw; 60 | } 61 | } 62 | } 63 | public async Task GetGitHubToken() 64 | { 65 | 66 | var builder = WebApplication.CreateBuilder(); 67 | builder.Host.ConfigureLogging(logging => 68 | { 69 | logging.ClearProviders(); 70 | }); 71 | var app = builder.Build(); 72 | 73 | var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); 74 | 75 | app.Run(async ctx => 76 | { 77 | Task WriteResponse(HttpContext ctx) 78 | { 79 | ctx.Response.StatusCode = 200; 80 | ctx.Response.ContentType = "text/html"; 81 | return ctx.Response.WriteAsync("

You can now return to the application.

", Encoding.UTF8); 82 | } 83 | 84 | switch (ctx.Request.Method) 85 | { 86 | case "GET": 87 | await WriteResponse(ctx); 88 | 89 | tcs.TrySetResult(ctx.Request.QueryString.Value); 90 | break; 91 | 92 | case "POST" when !ctx.Request.HasFormContentType: 93 | ctx.Response.StatusCode = 415; 94 | break; 95 | 96 | case "POST": 97 | { 98 | using var sr = new StreamReader(ctx.Request.Body, Encoding.UTF8); 99 | var body = await sr.ReadToEndAsync(); 100 | 101 | await WriteResponse(ctx); 102 | 103 | tcs.TrySetResult(body); 104 | break; 105 | } 106 | 107 | default: 108 | ctx.Response.StatusCode = 405; 109 | break; 110 | } 111 | }); 112 | 113 | var browserPort = 7777; 114 | 115 | app.Urls.Add($"https://127.0.0.1:{browserPort}"); 116 | 117 | app.Start(); 118 | 119 | var timeout = TimeSpan.FromMinutes(5); 120 | 121 | string redirectUri = string.Format($"https://127.0.0.1:{browserPort}"); 122 | string authUrl = $"https://github.com/login/oauth/authorize?client_id={_options.GitHubClientId}&scope=gist%2Cread%3Aorg%2Crepo%2Cuser%2Cworkflow%2Cwrite%3Apublic_key&redirect_uri={HttpUtility.UrlEncode(redirectUri)}"; 123 | 124 | OpenBrowser(authUrl); 125 | 126 | var code = await tcs.Task.WaitAsync(timeout); 127 | code = code.Replace("?code=", ""); 128 | await app.DisposeAsync(); 129 | 130 | string tokenRequestBody = string.Format("code={0}&client_id={1}&client_secret={2}", 131 | code, 132 | _options.GitHubClientId, 133 | _options.GitHubClientSecret 134 | ); 135 | 136 | var formContent = new FormUrlEncodedContent(new[] 137 | { 138 | new KeyValuePair("code", code), 139 | new KeyValuePair("client_id", _options.GitHubClientId), 140 | new KeyValuePair("client_secret", _options.GitHubClientSecret) 141 | }); 142 | 143 | // sends the request 144 | HttpClient _client = new HttpClient(); 145 | _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); 146 | var response = await _client.PostAsync("https://github.com/login/oauth/access_token", formContent); 147 | 148 | string responseText = await response.Content.ReadAsStringAsync(); 149 | 150 | Dictionary tokenEndpointDecoded = JsonConvert.DeserializeObject>(responseText); 151 | 152 | _accessToken = tokenEndpointDecoded["access_token"]; 153 | 154 | client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Token", _accessToken); 155 | _gitHub.Credentials = new Credentials(_accessToken); 156 | return _accessToken; 157 | } 158 | 159 | public async Task CreateAndCommit(string owner, string repo, string fileName) 160 | { 161 | var headMasterRef = "heads/main"; 162 | 163 | // Get reference of master branch 164 | var masterReference = await _gitHub.Git.Reference.Get(owner, repo, headMasterRef); 165 | // Get the laster commit of this branch 166 | var latestCommit = await _gitHub.Git.Commit.Get(owner, repo, masterReference.Object.Sha); 167 | 168 | // Create new Tree 169 | var nt = new NewTree { BaseTree = latestCommit.Tree.Sha }; 170 | // Add items based on blobs 171 | nt.Tree.Add(new NewTreeItem { Path = fileName, Mode = "100644" }); 172 | 173 | var newTree = await _gitHub.Git.Tree.Create(owner, repo, nt); 174 | 175 | // Create Commit 176 | var newCommit = new NewCommit("Adding GitHub Workflow file", newTree.Sha, masterReference.Object.Sha); 177 | var commit = await _gitHub.Git.Commit.Create(owner, repo, newCommit); 178 | await _gitHub.Git.Reference.Update(owner, repo, "heads/master", new ReferenceUpdate(commit.Sha, true)); 179 | 180 | } 181 | 182 | public async Task GetSecrets(string owner, string repo) 183 | { 184 | string endpoint = $"/repos/{owner}/{repo}/actions/secrets"; 185 | return await GetAsync(endpoint); 186 | } 187 | 188 | public async Task CreateSecret(string owner, string repo, string secretName, string secretValue) 189 | { 190 | var key = await GetAsync($"/repos/{owner}/{repo}/actions/secrets/public-key"); 191 | var secretValueBytes = System.Text.Encoding.UTF8.GetBytes(secretValue); 192 | var publicKey = Convert.FromBase64String(key.Key); 193 | var sealedPublicKeyBox = Sodium.SealedPublicKeyBox.Create(secretValueBytes, publicKey); 194 | 195 | var request = new CreateSecretRequest 196 | { 197 | key_id = key.Key_Id, 198 | encrypted_value = sealedPublicKeyBox 199 | }; 200 | 201 | var response = await PutAsync($"/repos/{owner}/{repo}/actions/secrets/{secretName}", request); 202 | } 203 | 204 | private async Task GetAsync(string endpoint) 205 | { 206 | 207 | var foo = await client.GetAsync(endpoint); 208 | 209 | return await client.GetFromJsonAsync(endpoint); 210 | } 211 | 212 | private async Task PutAsync(string endpoint, object content) 213 | { 214 | return await client.PutAsync(endpoint, new StringContent(System.Text.Json.JsonSerializer.Serialize(content))); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /src/WorkFlowGenerator/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.IO.Abstractions; 4 | using System.Reflection; 5 | using System.Threading.Tasks; 6 | using System.Xml; 7 | using System.Xml.Serialization; 8 | using McMaster.Extensions.CommandLineUtils; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Hosting; 12 | using Spectre.Console; 13 | using WorkFlowGenerator.Exceptions; 14 | using WorkFlowGenerator.Models; 15 | using WorkFlowGenerator.Services; 16 | using WorkFlowGenerator.Templates; 17 | 18 | namespace WorkFlowGenerator; 19 | 20 | internal class Program 21 | { 22 | private readonly IFileSystem _fileSystem; 23 | private readonly IAzureService _azureService; 24 | private readonly IReporter _reporter; 25 | private readonly IProjectDiscoveryService _projectDiscoveryService; 26 | private readonly IRepoService _repoService; 27 | private readonly IGitHubService _gitHubService; 28 | private static IConfiguration Configuration { get; set; } 29 | 30 | private WorkflowSettings WorkflowSettings { get; set; } 31 | 32 | [Argument(0, Description = "The path to a .csproj or .fsproj file, or to a directory containing a .NET Core solution/project. " + 33 | "If none is specified, the current directory will be used.")] 34 | public string Path { get; set; } 35 | 36 | static IHostBuilder CreateDefaultBuilder() 37 | { 38 | return Host.CreateDefaultBuilder() 39 | .ConfigureAppConfiguration(app => 40 | { 41 | app.AddJsonFile("appsettings.json"); 42 | app.AddJsonFile("appsettings.Development.json"); 43 | }) 44 | .ConfigureServices(services => 45 | { 46 | services.AddSingleton(PhysicalConsole.Singleton); 47 | services.AddSingleton(provider => new ConsoleReporter(provider.GetService())); 48 | services.AddSingleton(); 49 | services.AddSingleton(); 50 | services.AddSingleton(); 51 | services.AddSingleton(); 52 | services.AddSingleton(); 53 | }); ; 54 | } 55 | 56 | public static int Main(string[] args) 57 | { 58 | Configuration = new ConfigurationBuilder() 59 | .AddJsonFile("appsettings.json", true, true) 60 | .AddJsonFile("appsettings.Development.json", true, true) 61 | .Build(); 62 | 63 | using ( 64 | var services = new ServiceCollection() 65 | .AddSingleton(PhysicalConsole.Singleton) 66 | .AddSingleton(provider => new ConsoleReporter(provider.GetService())) 67 | .AddSingleton() 68 | .AddSingleton() 69 | .AddSingleton() 70 | .AddSingleton() 71 | .AddSingleton() 72 | .Configure(Configuration) 73 | .BuildServiceProvider()) 74 | { 75 | var app = new CommandLineApplication(); 76 | app.Conventions 77 | .UseDefaultConventions() 78 | .UseConstructorInjection(services); 79 | 80 | return app.Execute(args); 81 | } 82 | } 83 | 84 | public static string GetVersion() => typeof(Program) 85 | .Assembly 86 | .GetCustomAttribute() 87 | .InformationalVersion; 88 | 89 | public Program(IFileSystem fileSystem, IReporter reporter, IProjectDiscoveryService projectDiscoveryService, IRepoService repoService, IAzureService azureService, IGitHubService gitHubService) 90 | { 91 | _gitHubService = gitHubService; 92 | _azureService = azureService; 93 | _fileSystem = fileSystem; 94 | _reporter = reporter; 95 | _projectDiscoveryService = projectDiscoveryService; 96 | _repoService = repoService; 97 | WorkflowSettings = new WorkflowSettings(); 98 | } 99 | 100 | public async Task OnExecute(CommandLineApplication app, IConsole console) 101 | { 102 | try 103 | { 104 | PopulateDirectories(); 105 | await GetAzureResources(); 106 | 107 | if (AnsiConsole.Confirm($"Do you want to create the GitHub Secret for your Azure Publishing Profile (selecting no will leave value blank in workflow)?")) 108 | { 109 | var token = await _gitHubService.GetGitHubToken(); 110 | var secrets = await _gitHubService.GetSecrets(WorkflowSettings.GitHubOwner, WorkflowSettings.GitHubRepo); 111 | bool writeSecret = true; 112 | foreach (var secret in secrets.Secrets) 113 | { 114 | if (secret.Name == $"{WorkflowSettings.AzureResourceName.ToUpper()}_PUBLISH_PROFILE") 115 | { 116 | if (AnsiConsole.Confirm($"GitHub Secret {WorkflowSettings.AzureResourceName.ToUpper()}_PUBLISH_PROFILE exists, do you want to update it?")) 117 | { 118 | writeSecret = true; 119 | } 120 | else 121 | { 122 | writeSecret = false; 123 | } 124 | break; 125 | } 126 | else 127 | { 128 | writeSecret = true; 129 | } 130 | } 131 | 132 | if (writeSecret) 133 | { 134 | // UPDATE SECRET 135 | await _gitHubService.CreateSecret(WorkflowSettings.GitHubOwner, WorkflowSettings.GitHubRepo, $"{WorkflowSettings.AzureResourceName.ToUpper()}_PUBLISH_PROFILE", WorkflowSettings.AzurePublishProfile); 136 | } 137 | } 138 | 139 | PopulateWorkflow(console); 140 | return 0; 141 | } 142 | catch (CommandValidationException e) 143 | { 144 | _reporter.Error(e.Message); 145 | return 1; 146 | } 147 | } 148 | 149 | public async Task GetAzureResources() 150 | { 151 | var subscription = _azureService.GetSubscription(); 152 | WorkflowSettings.AzureSubscription = subscription.Data.DisplayName; 153 | var resourceGroup = _azureService.GetResourceGroups(); 154 | WorkflowSettings.AzureResourceGroup = resourceGroup.Data.Name; 155 | if (WorkflowSettings.AppType == AppType.Function) 156 | { 157 | var function = await _azureService.GetFunctions(); 158 | WorkflowSettings.AzureResourceName = function.Name; 159 | if (function.Inner.Kind.Contains("linux")) 160 | { 161 | WorkflowSettings.AppPlatform = AppPlatform.Linux; 162 | } 163 | else 164 | { 165 | WorkflowSettings.AppPlatform = AppPlatform.Windows; 166 | } 167 | } 168 | else 169 | { 170 | var webapp = await _azureService.GetWebApps(); 171 | WorkflowSettings.AzureResourceName = webapp.Name; 172 | if (webapp.Inner.Kind.Contains("linux")) 173 | { 174 | WorkflowSettings.AppPlatform = AppPlatform.Linux; 175 | } 176 | else 177 | { 178 | WorkflowSettings.AppPlatform = AppPlatform.Windows; 179 | } 180 | } 181 | WorkflowSettings.AzurePublishProfile = await _azureService.GetPublishProfile(WorkflowSettings.AzureResourceName); 182 | } 183 | 184 | public int PopulateWorkflow(IConsole console) 185 | { 186 | if (!Directory.Exists(WorkflowSettings.WorkflowFolderPath)) 187 | { 188 | Directory.CreateDirectory(WorkflowSettings.WorkflowFolderPath); 189 | } 190 | 191 | string yaml; 192 | if (WorkflowSettings.AppType == AppType.Function) 193 | { 194 | yaml = AzureFunctionTemplate.Get("Build and Deploy", 195 | "main", 196 | WorkflowSettings.AzureResourceName, 197 | WorkflowSettings.PackagePath, 198 | WorkflowSettings.DOTNETVersion, 199 | WorkflowSettings.WorkingDirectory, 200 | WorkflowSettings.AppPlatform == AppPlatform.Linux ? "ubuntu" : "windows", 201 | "${{ secrets." + WorkflowSettings.AzureResourceName.ToUpper() + "_PUBLISH_PROFILE }}"); 202 | } 203 | else 204 | { 205 | yaml = AzureWebAppTemplate.Get("Build and Deploy", 206 | "main", 207 | WorkflowSettings.AzureResourceName, 208 | WorkflowSettings.PackagePath, 209 | WorkflowSettings.DOTNETVersion, 210 | WorkflowSettings.WorkingDirectory, 211 | WorkflowSettings.AppPlatform == AppPlatform.Linux ? "ubuntu" : "windows", 212 | "${{ secrets." + WorkflowSettings.AzureResourceName.ToUpper() + "_PUBLISH_PROFILE }}"); 213 | } 214 | 215 | if (string.IsNullOrEmpty(yaml) == false) 216 | { 217 | File.WriteAllText(System.IO.Path.Combine(WorkflowSettings.WorkflowFolderPath, "base.yml"), yaml); 218 | } 219 | 220 | AnsiConsole.Write($"GitHub Workflow Created at {WorkflowSettings.WorkflowFolderPath}"); 221 | return 0; 222 | } 223 | 224 | private int PopulateDirectories() 225 | { 226 | // If no path is set, use the current directory 227 | if (string.IsNullOrEmpty(Path)) 228 | Path = _fileSystem.Directory.GetCurrentDirectory(); 229 | 230 | // Get all the projects 231 | 232 | AnsiConsole.WriteLine("Discovering project.."); 233 | 234 | var projectPath = _projectDiscoveryService.DiscoverProject(Path); 235 | 236 | XmlSerializer ser = new XmlSerializer(typeof(WorkFlowGenerator.Models.Project)); 237 | WorkFlowGenerator.Models.Project projectProperties = new WorkFlowGenerator.Models.Project(); 238 | using (XmlReader reader = XmlReader.Create(projectPath)) 239 | { 240 | projectProperties = (WorkFlowGenerator.Models.Project)ser.Deserialize(reader); 241 | } 242 | 243 | if (!string.IsNullOrEmpty(projectProperties.PropertyGroup.TargetFrameworks)) 244 | { 245 | string[] frameworks = projectProperties.PropertyGroup.TargetFrameworks.Split(";"); 246 | 247 | if (frameworks.Length > 1) 248 | { 249 | WorkflowSettings.DOTNETVersion = frameworks[frameworks.Length - 1].Replace("net", "") + ".x"; 250 | } 251 | else if (frameworks.Length == 1) 252 | { 253 | WorkflowSettings.DOTNETVersion = frameworks[0].Replace("net", "") + ".x"; 254 | } 255 | else 256 | { 257 | throw new Exception(); 258 | } 259 | } 260 | else if (!string.IsNullOrEmpty(projectProperties.PropertyGroup.TargetFramework)) 261 | { 262 | WorkflowSettings.DOTNETVersion = projectProperties.PropertyGroup.TargetFramework.Replace("net", "") + ".x"; 263 | } 264 | else 265 | { 266 | throw new Exception(); 267 | } 268 | 269 | if (!string.IsNullOrEmpty(projectProperties.PropertyGroup.AzureFunctionsVersion)) 270 | { 271 | WorkflowSettings.AppType = AppType.Function; 272 | } 273 | else 274 | { 275 | WorkflowSettings.AppType = AppType.WebApp; 276 | } 277 | 278 | if (!string.IsNullOrEmpty(projectPath)) 279 | { 280 | string workingDir = ""; 281 | var repoInfo = _repoService.GetGitRepo(projectPath); 282 | string gitRepoRoot = repoInfo.Repository.Info.WorkingDirectory; 283 | //check if Git Repo 284 | if (!string.IsNullOrEmpty(gitRepoRoot)) 285 | { 286 | workingDir = gitRepoRoot; 287 | } 288 | else 289 | { 290 | workingDir = System.IO.Path.GetDirectoryName(projectPath); 291 | } 292 | 293 | WorkflowSettings.GitHubRepo = repoInfo.GitHubRepo; 294 | WorkflowSettings.GitHubOwner = repoInfo.GitHubOwner; 295 | WorkflowSettings.WorkflowFolderPath = System.IO.Path.Combine(workingDir, ".github", "workflows"); 296 | WorkflowSettings.WorkingDirectory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(projectPath).Replace(workingDir, "")); 297 | WorkflowSettings.PackagePath = System.IO.Path.Combine(WorkflowSettings.WorkingDirectory, "publish"); 298 | 299 | return 0; 300 | } 301 | else 302 | { 303 | _reporter.Error(string.Format(Resources.ValidationErrorMessages.DirectoryDoesNotContainSolutionsOrProjects, projectPath)); 304 | return 1; 305 | } 306 | } 307 | 308 | public void ClearCurrentConsoleLine() 309 | { 310 | int currentLineCursor = Console.CursorTop; 311 | Console.SetCursorPosition(0, Console.CursorTop); 312 | Console.Write(new string(' ', Console.BufferWidth)); 313 | Console.SetCursorPosition(0, currentLineCursor); 314 | } 315 | 316 | } 317 | --------------------------------------------------------------------------------