From 2553afca7999fc75b808b9658dd2d1070ab56fc5 Mon Sep 17 00:00:00 2001 From: "Daniel P. Purkhus" Date: Fri, 17 Nov 2023 14:07:50 +0000 Subject: [PATCH] Delete unused files --- .gitmodules | 0 .gitpod.yml | 34 --- .gitpod/gitpod-init.sh | 27 --- .gitpod/gitpod.Dockerfile | 66 ----- .gitpod/vscode.settings.json | 74 ------ AUTHORS | 10 - CODEOWNERS | 2 +- CONTRIBUTORS | 16 -- README.md | 1 - renovate.json | 4 - tools/nuget/.editorconfig | 94 ------- tools/nuget/.gitignore | 14 -- tools/nuget/BUILD.bazel | 0 tools/nuget/BazelDotnet.sln | 37 --- tools/nuget/BazelDotnet.sln.DotSettings.user | 58 ----- tools/nuget/LICENSE | 21 -- tools/nuget/README.md | 32 --- tools/nuget/WORKSPACE | 34 --- tools/nuget/build.cake | 84 ------- tools/nuget/build.ps1 | 189 --------------- tools/nuget/nuget.config | 6 - .../Afas.BazelDotnet.Nuget.csproj | 32 --- .../src/Afas.BazelDotnet.Nuget/BUILD.bazel | 34 --- .../BazelDotnet.Nuget/ConsoleLogger.cs | 41 ---- .../BazelDotnet.Nuget/DependencyResolver.cs | 73 ------ .../BazelDotnet.Nuget/External/SdkList.cs | 170 ------------- .../BazelDotnet.Nuget/FileUtilities.cs | 38 --- .../FrameworkDependencyResolver.cs | 219 ----------------- .../LocalPackageExtractor.cs | 58 ----- .../BazelDotnet.Nuget/NugetRepositoryEntry.cs | 68 ------ .../NugetRepositoryEntryBuilder.cs | 160 ------------ .../NugetRepositoryGenerator.cs | 225 ----------------- .../TransitiveDependencyResolver.cs | 197 --------------- .../ZipArchiveRepositoryGenerator.cs | 49 ---- .../Afas.BazelDotnet.Project.csproj | 8 - .../src/Afas.BazelDotnet.Project/BUILD.bazel | 19 -- .../BazelDotnet.Project/BazelDefinition.cs | 223 ----------------- .../BazelDefinitionBuilder.cs | 113 --------- .../CsProjBuildFileGenerator.cs | 139 ----------- .../CsProjectFileDefinition.cs | 156 ------------ .../EmbeddedResourceDefinition.cs | 17 -- .../EmbeddedResourceType.cs | 9 - .../BazelDotnet.Project/_enums.cs | 10 - .../Afas.BazelDotnet/Afas.BazelDotnet.csproj | 30 --- tools/nuget/src/Afas.BazelDotnet/BUILD.bazel | 23 -- .../Afas.BazelDotnet/BazelDotnet/Program.cs | 229 ------------------ .../assets/bazel_dotnet.BUILD | 4 - .../assets/bazel_dotnet.WORKSPACE | 1 - 48 files changed, 1 insertion(+), 3147 deletions(-) delete mode 100644 .gitmodules delete mode 100644 .gitpod.yml delete mode 100755 .gitpod/gitpod-init.sh delete mode 100644 .gitpod/gitpod.Dockerfile delete mode 100644 .gitpod/vscode.settings.json delete mode 100644 AUTHORS delete mode 100644 CONTRIBUTORS delete mode 100644 renovate.json delete mode 100644 tools/nuget/.editorconfig delete mode 100644 tools/nuget/.gitignore delete mode 100644 tools/nuget/BUILD.bazel delete mode 100644 tools/nuget/BazelDotnet.sln delete mode 100644 tools/nuget/BazelDotnet.sln.DotSettings.user delete mode 100644 tools/nuget/LICENSE delete mode 100644 tools/nuget/README.md delete mode 100644 tools/nuget/WORKSPACE delete mode 100644 tools/nuget/build.cake delete mode 100644 tools/nuget/build.ps1 delete mode 100644 tools/nuget/nuget.config delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/Afas.BazelDotnet.Nuget.csproj delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BUILD.bazel delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/ConsoleLogger.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/DependencyResolver.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/External/SdkList.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/FileUtilities.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/FrameworkDependencyResolver.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/LocalPackageExtractor.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryEntry.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryEntryBuilder.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryGenerator.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/TransitiveDependencyResolver.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/ZipArchiveRepositoryGenerator.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Project/Afas.BazelDotnet.Project.csproj delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Project/BUILD.bazel delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/BazelDefinition.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/BazelDefinitionBuilder.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/CsProjBuildFileGenerator.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/CsProjectFileDefinition.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/EmbeddedResourceDefinition.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/EmbeddedResourceType.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/_enums.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet/Afas.BazelDotnet.csproj delete mode 100644 tools/nuget/src/Afas.BazelDotnet/BUILD.bazel delete mode 100644 tools/nuget/src/Afas.BazelDotnet/BazelDotnet/Program.cs delete mode 100644 tools/nuget/src/Afas.BazelDotnet/assets/bazel_dotnet.BUILD delete mode 100644 tools/nuget/src/Afas.BazelDotnet/assets/bazel_dotnet.WORKSPACE diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index e69de29b..00000000 diff --git a/.gitpod.yml b/.gitpod.yml deleted file mode 100644 index 0ac1507f..00000000 --- a/.gitpod.yml +++ /dev/null @@ -1,34 +0,0 @@ -image: - file: .gitpod/gitpod.Dockerfile - -tasks: - - name: install pre-commit git hooks - init: pre-commit install - - name: Bazel - before: "./.gitpod/gitpod-init.sh" - init: | - bazel build //... - -vscode: - extensions: - - BazelBuild.vscode-bazel - - Ionide.Ionide-fsharp - - muhammad-sammy.csharp - - timonwong.shellcheck - -github: - prebuilds: - # enable for the master/default branch (defaults to true) - master: true - # enable for all branches in this repo (defaults to false) - branches: false - # enable for pull requests coming from this repo (defaults to true) - pullRequests: true - # enable for pull requests coming from forks (defaults to false) - pullRequestsFromForks: true - # add a check to pull requests (defaults to true) - addCheck: false - # add a "Review in Gitpod" button as a comment to pull requests (defaults to false) - addComment: false - # add a "Review in Gitpod" button to the pull request's description (defaults to false) - addBadge: false diff --git a/.gitpod/gitpod-init.sh b/.gitpod/gitpod-init.sh deleted file mode 100755 index 3a0718c8..00000000 --- a/.gitpod/gitpod-init.sh +++ /dev/null @@ -1,27 +0,0 @@ -#! /usr/bin/env bash - -# This script only updates the settings if it's run in a Gitpod workspace. -if [[ -n "${GITPOD_WORKSPACE_URL}" ]]; then - if [[ -f ".bazelrc.user" ]]; then - rm .bazelrc.user - fi - - if [[ -f "examples/.bazelrc.user" ]]; then - rm examples/.bazelrc.user - fi - - cat <> .bazelrc.user -build --disk_cache=/workspace/bazel-disk-cache -build --repository_cache=/workspace/bazel-repository-cache -build --local_cpu_resources="HOST_CPUS*2" -build --local_ram_resources="HOST_RAM*0.9" -build --sandbox_tmpfs_path=/tmp -build --jobs=32 -startup --output_user_root=/workspace/bazel_user_root -startup --output_base=/workspace/bazel_output_base -EOT - - cp .bazelrc.user examples/.bazelrc.user - mkdir -p .vscode && cp .gitpod/vscode.settings.json .vscode/settings.json -fi - diff --git a/.gitpod/gitpod.Dockerfile b/.gitpod/gitpod.Dockerfile deleted file mode 100644 index 04a15f27..00000000 --- a/.gitpod/gitpod.Dockerfile +++ /dev/null @@ -1,66 +0,0 @@ -FROM gitpod/workspace-full - -############ -### .Net ### -############ -# Install .NET SDK (Current channel) -# Source: https://docs.microsoft.com/dotnet/core/install/linux-scripted-manual#scripted-install -USER gitpod - -# Remove this hack when the kernel bug is resolved. -# ref. https://github.com/gitpod-io/gitpod/issues/8901 -RUN bash \ - && { echo 'if [ ! -z $GITPOD_REPO_ROOT ]; then'; \ - echo '\tCONTAINER_DIR=$(awk '\''{ print $6 }'\'' /proc/self/maps | grep ^\/run\/containerd | head -n 1 | cut -d '\''/'\'' -f 1-6)'; \ - echo '\tif [ ! -z $CONTAINER_DIR ]; then'; \ - echo '\t\t[[ ! -d $CONTAINER_DIR ]] && sudo mkdir -p $CONTAINER_DIR && sudo ln -s / $CONTAINER_DIR/rootfs'; \ - echo '\tfi'; \ - echo 'fi'; } >> /home/gitpod/.bashrc.d/110-dotnet -RUN chmod +x /home/gitpod/.bashrc.d/110-dotnet - -ENV DOTNET_VERSION=7.0 -ENV DOTNET_ROOT=/home/gitpod/dotnet -ENV PATH=$PATH:$DOTNET_ROOT -ENV PATH=$PATH:/home/gitpod/.dotnet/tools -RUN mkdir -p $DOTNET_ROOT && curl -fsSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --channel $DOTNET_VERSION --install-dir $DOTNET_ROOT -RUN dotnet tool install --global --version 4.7.3 fantomas-tool -RUN dotnet tool install --global paket -ENV NUGET_PACKAGES=/workspace/nuget_cache - - -######################################################### -### Create bin folder under $HOME for random binaries ### -######################################################### -USER gitpod -RUN mkdir $HOME/bin -ENV PATH=$PATH:$HOME/bin - -######################################### -### Bazel and Bazel releated binaries ### -######################################### -# Install bazelisk and make it available on PATH as it as bazel -RUN curl -o bazelisk-linux-amd64 -fsSL https://github.com/bazelbuild/bazelisk/releases/download/v1.12.0/bazelisk-linux-amd64 \ - && mv ./bazelisk-linux-amd64 $HOME/bin/bazel \ - && chmod +x $HOME/bin/bazel - -# Install bazel-watcher -RUN curl -o ibazel_linux_amd64 -fsSL https://github.com/bazelbuild/bazel-watcher/releases/download/v0.16.2/ibazel_linux_amd64 \ - && mv ./ibazel_linux_amd64 $HOME/bin/ibazel \ - && chmod +x $HOME/bin/ibazel - -# Install buildifier -RUN curl -o buildifier-linux-amd64 -fsSL https://github.com/bazelbuild/buildtools/releases/download/5.1.0/buildifier-linux-amd64 \ - && mv ./buildifier-linux-amd64 $HOME/bin/buildifier \ - && chmod +x $HOME/bin/buildifier - -# Install buildozer -RUN curl -o buildozer-linux-amd64 -fsSL https://github.com/bazelbuild/buildtools/releases/download/5.1.0/buildozer-linux-amd64 \ - && mv ./buildozer-linux-amd64 $HOME/bin/buildozer \ - && chmod +x $HOME/bin/buildozer - -# pre-commit and shellcheck -USER root -RUN install-packages shellcheck \ - && pip3 install pre-commit - -USER gitpod diff --git a/.gitpod/vscode.settings.json b/.gitpod/vscode.settings.json deleted file mode 100644 index 1528baf1..00000000 --- a/.gitpod/vscode.settings.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - //////////// - // General - //////////// - "extensions.ignoreRecommendations": true, - "extensions.autoUpdate": false, - "editor.formatOnSave": true, - // Files excluded from watches for performance reasons - "files.watcherExclude": { - "**/.git": true, - "**/.svn": true, - "**/.hg": true, - "**/CVS": true, - "**/.DS_Store": true, - "**/.idea": true, - "**/.metals": true, - "**/.mypy_cache": true, - "**/.pants.d": true, - "**/.pids": true, - "**/bazel-out": true, - "**/bazel-testlogs": true, - "**/bazel-rules_dotnet": true, - "**/bazel-bin": true, - "**/dist": true, - "**/.cache": true, - "**/node_modules": true, - "**/bin": true, - "**/obj": true - }, - // Files excluded for performance reasons - "files.exclude": { - "**/.git": true, - "**/.svn": true, - "**/.hg": true, - "**/CVS": true, - "**/.DS_Store": true, - "**/.idea": true, - "**/.metals": true, - "**/.mypy_cache": true, - "**/.pants.d": true, - "**/.pids": true, - "**/bazel-out": true, - "**/bazel-testlogs": true, - "**/bazel-rules_dotnet": true, - "**/bazel-bin": true, - "**/dist": true, - "**/.cache": true, - "**/node_modules": true, - "**/bin": true, - "**/obj": true - }, - ////////// - // Bazel - ////////// - "bazel.buildifierFixOnFormat": true, - "bazel.enableCodeLens": true, - ////////// - // F# - ////////// - "FSharp.enableMSBuildProjectGraph": false, - "FSharp.externalAutocomplete": true, - "FSharp.excludeProjectDirectories": [ - ".git", - ".fable", - "node_modules", - "bazel-out", - "bazel-rules_dotnet", - "bazel-testlogs", - "bazel-bin", - "bazel-examples", - ".idea" - ], - "FSharp.workspaceModePeekDeepLevel": 15 -} diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index c11248bd..00000000 --- a/AUTHORS +++ /dev/null @@ -1,10 +0,0 @@ -# This the official list of Bazel authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as: -# Name or Organization -# The email address is not required for organizations. - -Google Inc. -Jeremy Wall diff --git a/CODEOWNERS b/CODEOWNERS index 63189759..4e8064b8 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1 +1 @@ -* @zaphar @tomaszstrejczek +* @purkhusid diff --git a/CONTRIBUTORS b/CONTRIBUTORS deleted file mode 100644 index f37a4f2f..00000000 --- a/CONTRIBUTORS +++ /dev/null @@ -1,16 +0,0 @@ -# People who have agreed to one of the CLAs and can contribute patches. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# https://developers.google.com/open-source/cla/individual -# https://developers.google.com/open-source/cla/corporate -# -# Names should be added to this file as: -# Name - -Damien Martin-Guillerez -David Chen -David Z. Chen -Jeremy Wall -Jacob Parker diff --git a/README.md b/README.md index 8602dffe..32b5fef5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-908a85?logo=gitpod)](https://gitpod.io/#https://github.com/bazelbuild/rules_dotnet) [![Build status](https://badge.buildkite.com/703775290818dcb2af754f503ed54dc11bb124fce2a6bf1606.svg?branch=master)](https://buildkite.com/bazel/rules-dotnet-edge) # Bazel rules for .Net diff --git a/renovate.json b/renovate.json deleted file mode 100644 index 4bd832f5..00000000 --- a/renovate.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "$schema": "https://docs.renovatebot.com/renovate-schema.json", - "extends": ["config:base"] -} diff --git a/tools/nuget/.editorconfig b/tools/nuget/.editorconfig deleted file mode 100644 index 3a546f30..00000000 --- a/tools/nuget/.editorconfig +++ /dev/null @@ -1,94 +0,0 @@ -# EditorConfig is awesome: http://EditorConfig.org - -# General properties: https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties#widely-supported-by-editors -# .NET-specific properties: https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference - -# Top-most EditorConfig file -root = true - -[*] -# Don't use tabs for indentation. -indent_style = space -# (Please don't specify an indent_size here; that has too many unintended consequences.) - -# Code files -[*.{cs,csx,vb,vbx,js,json,xml,xaml,md,sql,txt,cst,jst,cake}] -indent_size = 2 -max_line_length = 160 -insert_final_newline = false -charset = utf-8 -trim_trailing_whitespace = true - -# XML project files -[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] -indent_size = 2 - -# XML config files -[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] -indent_size = 2 - -# .NET code style settings: -[*.{cs,vb}] -# Sort using and Import directives with System.* appearing first -dotnet_sort_system_directives_first = true -# Avoid "this." and "Me." if not necessary -dotnet_style_qualification_for_field = false:error -dotnet_style_qualification_for_property = false:error -dotnet_style_qualification_for_method = false:error -dotnet_style_qualification_for_event = false:error - -# Use language keywords instead of framework type names for type references -dotnet_style_predefined_type_for_locals_parameters_members = true:error -dotnet_style_predefined_type_for_member_access = true:error - -# Suggest more modern language features when available -dotnet_style_object_initializer = true:suggestion -dotnet_style_collection_initializer = true:suggestion -dotnet_style_coalesce_expression = true:warning -dotnet_style_null_propagation = true:warning -dotnet_style_explicit_tuple_names = true:error - -# C# code style settings: -[*.cs] -csharp_prefer_braces = true:error - -# Prefer "var" everywhere -csharp_style_var_for_built_in_types = true:none -csharp_style_var_when_type_is_apparent = true:none -csharp_style_var_elsewhere = false:none - -# Prefer method-like constructs to have a block body -csharp_style_expression_bodied_methods = false:none -csharp_style_expression_bodied_constructors = false:none -csharp_style_expression_bodied_operators = false:none - -# Prefer property-like constructs to have an expression-body -csharp_style_expression_bodied_properties = true:none -csharp_style_expression_bodied_indexers = true:none -csharp_style_expression_bodied_accessors = true:none - -# Suggest more modern language features when available -csharp_style_pattern_matching_over_is_with_cast_check = true:warning -csharp_style_pattern_matching_over_as_with_null_check = true:warning -csharp_style_inlined_variable_declaration = true:suggestion -csharp_style_throw_expression = true:warning -csharp_style_conditional_delegate_call = true:warning - -# Newline settings -csharp_new_line_before_open_brace = all -csharp_new_line_before_else = true -csharp_new_line_before_catch = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_members_in_anonymous_types = true - -# Formatting -csharp_indent_case_contents = true -csharp_indent_switch_labels = true -csharp_indent_labels = no_change -csharp_space_after_cast = false -csharp_space_after_keywords_in_control_flow_statements = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_preserve_single_line_statements = false -csharp_preserve_single_line_blocks = true \ No newline at end of file diff --git a/tools/nuget/.gitignore b/tools/nuget/.gitignore deleted file mode 100644 index f923730c..00000000 --- a/tools/nuget/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -.vs/ -.vscode/ -.idea/ -bin/ -obj/ -**/Properties/launchSettings.json - -/bazel-out -/bazel-bin -/bazel-bazel-dotnet -/bazel-testlogs - -tools -publish \ No newline at end of file diff --git a/tools/nuget/BUILD.bazel b/tools/nuget/BUILD.bazel deleted file mode 100644 index e69de29b..00000000 diff --git a/tools/nuget/BazelDotnet.sln b/tools/nuget/BazelDotnet.sln deleted file mode 100644 index 4060b5c8..00000000 --- a/tools/nuget/BazelDotnet.sln +++ /dev/null @@ -1,37 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.28803.156 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Afas.BazelDotnet", "src\Afas.BazelDotnet\Afas.BazelDotnet.csproj", "{FF6E1C29-7423-45B5-8E50-521E4AAA630D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Afas.BazelDotnet.Nuget", "src\Afas.BazelDotnet.Nuget\Afas.BazelDotnet.Nuget.csproj", "{4E86357C-40B0-484A-8761-C2D02A526FE1}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Afas.BazelDotnet.Project", "src\Afas.BazelDotnet.Project\Afas.BazelDotnet.Project.csproj", "{449D3099-A5EE-40E1-9579-45B48050135D}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FF6E1C29-7423-45B5-8E50-521E4AAA630D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FF6E1C29-7423-45B5-8E50-521E4AAA630D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FF6E1C29-7423-45B5-8E50-521E4AAA630D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FF6E1C29-7423-45B5-8E50-521E4AAA630D}.Release|Any CPU.Build.0 = Release|Any CPU - {4E86357C-40B0-484A-8761-C2D02A526FE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4E86357C-40B0-484A-8761-C2D02A526FE1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4E86357C-40B0-484A-8761-C2D02A526FE1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4E86357C-40B0-484A-8761-C2D02A526FE1}.Release|Any CPU.Build.0 = Release|Any CPU - {449D3099-A5EE-40E1-9579-45B48050135D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {449D3099-A5EE-40E1-9579-45B48050135D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {449D3099-A5EE-40E1-9579-45B48050135D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {449D3099-A5EE-40E1-9579-45B48050135D}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {30B3AB2D-B8A8-444F-9D23-63628DD966BD} - EndGlobalSection -EndGlobal diff --git a/tools/nuget/BazelDotnet.sln.DotSettings.user b/tools/nuget/BazelDotnet.sln.DotSettings.user deleted file mode 100644 index 14c741d1..00000000 --- a/tools/nuget/BazelDotnet.sln.DotSettings.user +++ /dev/null @@ -1,58 +0,0 @@ - - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - ForceIncluded - C:\Program Files\dotnet\dotnet.exe \ No newline at end of file diff --git a/tools/nuget/LICENSE b/tools/nuget/LICENSE deleted file mode 100644 index a7421aa0..00000000 --- a/tools/nuget/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 AFAS Software B.V. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/tools/nuget/README.md b/tools/nuget/README.md deleted file mode 100644 index fd844e6a..00000000 --- a/tools/nuget/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# BazelDotnet - -This tool is used in conjunction with [AFASResearch/rules_dotnet](https://github.com/AFASResearch/rules_dotnet). - -## Commands - -### repository - -Generate the external nuget_repository in the current working directory. - -``` -BazelDotnet.exe repository [path to]/nuget.config [-p [path to]/Packages.Props, ...] [--tfm=net5.0] -``` - -TODO - -- allow speccing output dir -- make nuget.config optional -- document --imports - -### projects - -Globs all `.csproj` files and generates an accompanying `BUILD` file. - -``` -BazelDotnet.exe projects -``` - -TODO - -- document features -- migrate to Gazelle diff --git a/tools/nuget/WORKSPACE b/tools/nuget/WORKSPACE deleted file mode 100644 index 904f5d3e..00000000 --- a/tools/nuget/WORKSPACE +++ /dev/null @@ -1,34 +0,0 @@ -load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") - -git_repository( - name = "io_bazel_rules_dotnet", - commit = "48155ef3fa8a2bff3d55852010afce3305daffc5", - remote = "https://github.com/tomdegoede/rules_dotnet", -) - -sdk_version = "v3.1.100" - -# git_repository( -# name = "io_bazel_rules_dotnet", -# remote = "https://github.com/bazelbuild/rules_dotnet", -# tag = "0.0.4", -# ) - -# sdk_version = "v3.0.100" - -load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_register_sdk", "dotnet_register_toolchains") - -# Disabled because of naming collissions with newtonsoft.json -# dotnet_repositories() - -dotnet_register_toolchains(core_version = sdk_version) - -# core_register_sdk("v2.2.402", name = "core_sdk") -core_register_sdk( - sdk_version, - name = "core_sdk", -) - -load(":deps.bzl", "deps") - -deps() diff --git a/tools/nuget/build.cake b/tools/nuget/build.cake deleted file mode 100644 index 21fdb79f..00000000 --- a/tools/nuget/build.cake +++ /dev/null @@ -1,84 +0,0 @@ -#addin nuget:?package=Cake.FileHelpers&version=3.2.1 -#addin nuget:?package=Cake.Incubator&version=5.1.0 - -// ARGUMENTS -var target = Argument("target", "Default"); -var configuration = Argument("configuration", "Release"); - -var slnFile = "./BazelDotnet.sln"; - -// TASKS -Task("Clean").Does(() => -{ - var binDirs = GetDirectories("./src/**/bin/*"); - foreach(var directory in binDirs) - { - CleanDirectory(directory.FullPath); - } - // also the new obj folders - var objDirs = GetDirectories("./src/**/obj/*"); - foreach(var directory in objDirs) - { - CleanDirectory(directory.FullPath); - } -}); - -Task("Restore") - .Does(() => -{ - DotNetCoreRestore(slnFile); -}); - -Task("Build") - // This is the fast build, so no dependencies - .Does(() => -{ - var msBuildSettings = new DotNetCoreMSBuildSettings(); - msBuildSettings.Properties["AssemblyVersion"]= new [] {"1.0.0.0"}; - msBuildSettings.Verbosity = DotNetCoreVerbosity.Minimal; - - DotNetCoreBuild(slnFile, new DotNetCoreBuildSettings() { - MSBuildSettings = msBuildSettings, - Configuration = configuration, - Verbosity = DotNetCoreVerbosity.Minimal - }); -}); - -Task("Rebuild") - .IsDependentOn("Clean") - .IsDependentOn("Restore") - .IsDependentOn("Build") - .Does(() => -{ -}); - -Task("Publish") - .IsDependentOn("Rebuild") - .Does(() => -{ - var settings = new DotNetCorePublishSettings - { - Framework = "netcoreapp3.1", - Configuration = configuration, - OutputDirectory = $"./publish/{configuration}" - }; - - DotNetCorePublish(slnFile, settings); -}); - -Task("Release") - .IsDependentOn("Publish") - .Does(() => -{ - if(!configuration.EqualsIgnoreCase("Release")){ - throw new Exception("Run this script with configuration release to publish the binaries to the share"); - } - - var publishedFiles = GetFiles("./publish/" + configuration + "/**/*"); - CopyFiles(publishedFiles, Directory(@"\\afasgroep.nl\data\tfsbuild\output\Tools\bazel-dotnet"), true); -}); - -// TASK TARGETS -Task("Default").IsDependentOn("Restore").IsDependentOn("Build"); - -RunTarget(target); \ No newline at end of file diff --git a/tools/nuget/build.ps1 b/tools/nuget/build.ps1 deleted file mode 100644 index 8f9ebd9f..00000000 --- a/tools/nuget/build.ps1 +++ /dev/null @@ -1,189 +0,0 @@ -########################################################################## -# This is the Cake bootstrapper script for PowerShell. -# This file was downloaded from https://github.com/cake-build/resources -# Feel free to change this file to fit your needs. -########################################################################## - -<# - -.SYNOPSIS -This is a Powershell script to bootstrap a Cake build. - -.DESCRIPTION -This Powershell script will download NuGet if missing, restore NuGet tools (including Cake) -and execute your Cake build script with the parameters you provide. - -.PARAMETER Script -The build script to execute. -.PARAMETER Target -The build script target to run. -.PARAMETER Configuration -The build configuration to use. -.PARAMETER Verbosity -Specifies the amount of information to be displayed. -.PARAMETER Experimental -Tells Cake to use the latest Roslyn release. -.PARAMETER WhatIf -Performs a dry run of the build script. -No tasks will be executed. -.PARAMETER Mono -Tells Cake to use the Mono scripting engine. -.PARAMETER SkipToolPackageRestore -Skips restoring of packages. -.PARAMETER ScriptArgs -Remaining arguments are added here. - -.LINK -https://cakebuild.net - -#> - -[CmdletBinding()] -Param( - [string]$Script = "build.cake", - [string]$Target = "Default", - [ValidateSet("Release", "Debug")] - [string]$Configuration = "Debug", - [ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")] - [string]$Verbosity = "Normal", - [switch]$Experimental, - [Alias("DryRun","Noop")] - [switch]$WhatIf, - [switch]$Mono, - [switch]$SkipToolPackageRestore, - [Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)] - [string[]]$ScriptArgs -) - -[Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null -function MD5HashFile([string] $filePath) -{ - if ([string]::IsNullOrEmpty($filePath) -or !(Test-Path $filePath -PathType Leaf)) - { - return $null - } - - [System.IO.Stream] $file = $null; - [System.Security.Cryptography.MD5] $md5 = $null; - try - { - $md5 = [System.Security.Cryptography.MD5]::Create() - $file = [System.IO.File]::OpenRead($filePath) - return [System.BitConverter]::ToString($md5.ComputeHash($file)) - } - finally - { - if ($file -ne $null) - { - $file.Dispose() - } - } -} - -Write-Host "Preparing to run build script..." - -if(!$PSScriptRoot){ - $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent -} - -$TOOLS_DIR = Join-Path $PSScriptRoot "tools" -$NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe" -$CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe" -$NUGET_URL = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" -$PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config" -$PACKAGES_CONFIG_MD5 = Join-Path $TOOLS_DIR "packages.config.md5sum" - -# Should we use mono? -$UseMono = ""; -if($Mono.IsPresent) { - Write-Verbose -Message "Using the Mono based scripting engine." - $UseMono = "-mono" -} - -# Should we use the new Roslyn? -$UseExperimental = ""; -if($Experimental.IsPresent -and !($Mono.IsPresent)) { - Write-Verbose -Message "Using experimental version of Roslyn." - $UseExperimental = "-experimental" -} - -# Is this a dry run? -$UseDryRun = ""; -if($WhatIf.IsPresent) { - $UseDryRun = "-dryrun" -} - -# Make sure tools folder exists -if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) { - Write-Verbose -Message "Creating tools directory..." - New-Item -Path $TOOLS_DIR -Type directory | out-null -} - -# Make sure that packages.config exist. -if (!(Test-Path $PACKAGES_CONFIG)) { - Write-Verbose -Message "Downloading packages.config..." - try { (New-Object System.Net.WebClient).DownloadFile("https://cakebuild.net/download/bootstrapper/packages", $PACKAGES_CONFIG) } catch { - Throw "Could not download packages.config." - } -} - -# Try find NuGet.exe in path if not exists -if (!(Test-Path $NUGET_EXE)) { - Write-Verbose -Message "Trying to find nuget.exe in PATH..." - $existingPaths = $Env:Path -Split ';' | Where-Object { (![string]::IsNullOrEmpty($_)) -and (Test-Path $_ -PathType Container) } - $NUGET_EXE_IN_PATH = Get-ChildItem -Path $existingPaths -Filter "nuget.exe" | Select -First 1 - if ($NUGET_EXE_IN_PATH -ne $null -and (Test-Path $NUGET_EXE_IN_PATH.FullName)) { - Write-Verbose -Message "Found in PATH at $($NUGET_EXE_IN_PATH.FullName)." - $NUGET_EXE = $NUGET_EXE_IN_PATH.FullName - } -} - -# Try download NuGet.exe if not exists -if (!(Test-Path $NUGET_EXE)) { - Write-Verbose -Message "Downloading NuGet.exe..." - try { - (New-Object System.Net.WebClient).DownloadFile($NUGET_URL, $NUGET_EXE) - } catch { - Throw "Could not download NuGet.exe." - } -} - -# Save nuget.exe path to environment to be available to child processed -$ENV:NUGET_EXE = $NUGET_EXE - -# Restore tools from NuGet? -if(-Not $SkipToolPackageRestore.IsPresent) { - Push-Location - Set-Location $TOOLS_DIR - - # Check for changes in packages.config and remove installed tools if true. - [string] $md5Hash = MD5HashFile($PACKAGES_CONFIG) - if((!(Test-Path $PACKAGES_CONFIG_MD5)) -Or - ($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) { - Write-Verbose -Message "Missing or changed package.config hash..." - Remove-Item * -Recurse -Exclude packages.config,nuget.exe - } - - Write-Verbose -Message "Restoring tools from NuGet..." - $NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`"" - - if ($LASTEXITCODE -ne 0) { - Throw "An error occured while restoring NuGet tools." - } - else - { - $md5Hash | Out-File $PACKAGES_CONFIG_MD5 -Encoding "ASCII" - } - Write-Verbose -Message ($NuGetOutput | out-string) - Pop-Location -} - -# Make sure that Cake has been installed. -if (!(Test-Path $CAKE_EXE)) { - Throw "Could not find Cake.exe at $CAKE_EXE" -} - -# Start Cake -Write-Host "Running build script..." -Invoke-Expression "& `"$CAKE_EXE`" `"$Script`" -target=`"$Target`" -configuration=`"$Configuration`" -verbosity=`"$Verbosity`" $UseMono $UseDryRun $UseExperimental $ScriptArgs" -exit $LASTEXITCODE \ No newline at end of file diff --git a/tools/nuget/nuget.config b/tools/nuget/nuget.config deleted file mode 100644 index 6873eb95..00000000 --- a/tools/nuget/nuget.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/Afas.BazelDotnet.Nuget.csproj b/tools/nuget/src/Afas.BazelDotnet.Nuget/Afas.BazelDotnet.Nuget.csproj deleted file mode 100644 index 7d088646..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/Afas.BazelDotnet.Nuget.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - net5.0 - Library - false - true - true - AFAS Software B.V. - AFAS Software B.V. - Profit Focus - Afas - - 5.10.0 - - - - - - - - - - - - - - - - - - diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BUILD.bazel b/tools/nuget/src/Afas.BazelDotnet.Nuget/BUILD.bazel deleted file mode 100644 index a0a0f71c..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BUILD.bazel +++ /dev/null @@ -1,34 +0,0 @@ -load("//dotnet:defs.bzl", "csharp_library") - -csharp_library( - name = "Afas.BazelDotnet.Nuget", - srcs = glob( - ["**/*.cs"], - exclude = [ - "**/obj/**", - "**/bin/**", - ], - ), - target_frameworks = ["net6.0"], - targeting_packs = [ - "@paket.rules_dotnet_nuget_packages//microsoft.netcore.app.ref", - ], - visibility = ["//visibility:public"], - deps = [ - #Adding built-in .Net libs - "@paket.rules_dotnet_nuget_packages//nuget.commands", - "@paket.rules_dotnet_nuget_packages//nuget.common", - "@paket.rules_dotnet_nuget_packages//nuget.configuration", - "@paket.rules_dotnet_nuget_packages//nuget.dependencyresolver.core", - "@paket.rules_dotnet_nuget_packages//nuget.frameworks", - "@paket.rules_dotnet_nuget_packages//nuget.packagemanagement", - "@paket.rules_dotnet_nuget_packages//nuget.packaging.core", - "@paket.rules_dotnet_nuget_packages//nuget.packaging", - "@paket.rules_dotnet_nuget_packages//nuget.projectmodel", - "@paket.rules_dotnet_nuget_packages//nuget.protocol", - "@paket.rules_dotnet_nuget_packages//nuget.resolver", - "@paket.rules_dotnet_nuget_packages//nuget.versioning", - "@paket.rules_dotnet_nuget_packages//nuget.credentials", - "@paket.rules_dotnet_nuget_packages//nuget.librarymodel", - ], -) diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/ConsoleLogger.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/ConsoleLogger.cs deleted file mode 100644 index 891d53d0..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/ConsoleLogger.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Threading.Tasks; -using NuGet.Common; - -namespace Afas.BazelDotnet.Nuget -{ - internal class ConsoleLogger : LoggerBase - { - private readonly LogLevel _logLevel; - - public ConsoleLogger(LogLevel logLevel) - { - _logLevel = logLevel; - } - - public override void Log(ILogMessage message) - { - if(message.Level >= _logLevel) - { - Console.ForegroundColor = message.Level switch - { - LogLevel.Debug => ConsoleColor.DarkBlue, - LogLevel.Error => ConsoleColor.Red, - LogLevel.Information => ConsoleColor.White, - LogLevel.Minimal => ConsoleColor.White, - LogLevel.Verbose => ConsoleColor.Blue, - LogLevel.Warning => ConsoleColor.Yellow, - _ => Console.ForegroundColor - }; - Console.WriteLine(message.Message); - Console.ResetColor(); - } - } - - public override Task LogAsync(ILogMessage message) - { - Log(message); - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/DependencyResolver.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/DependencyResolver.cs deleted file mode 100644 index 0d03a049..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/DependencyResolver.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Credentials; -using NuGet.Frameworks; -using NuGet.Protocol.Core.Types; - -namespace Afas.BazelDotnet.Nuget -{ - - internal interface IDependencyResolver - { - Task Resolve(IEnumerable<(string package, string version)> packageReferences); - } - - internal class DependencyResolver : IDependencyResolver - { - private readonly string _nugetConfig; - private readonly string _targetFramework; - private readonly string _targetRuntime; - - public DependencyResolver(string nugetConfig, string targetFramework, string targetRuntime) - { - _nugetConfig = nugetConfig; - _targetFramework = targetFramework; - _targetRuntime = targetRuntime; - } - - public async Task Resolve(IEnumerable<(string package, string version)> packageReferences) - { - // allow interactions for 2 factor authentication. CI scenario should never hit this. - bool interactive = true; - - // prevent verbose logging when there could be interactive 2 factor output shown to the user. - ILogger logger = new ConsoleLogger(interactive ? LogLevel.Minimal : LogLevel.Debug); - var settings = Settings.LoadSpecificSettings(Path.GetDirectoryName(_nugetConfig), Path.GetFileName(_nugetConfig)); - DefaultCredentialServiceUtility.SetupDefaultCredentialService(logger, nonInteractive: !interactive); - - // ~/.nuget/packages - using var cache = new SourceCacheContext(); - - var dependencyGraphResolver = new TransitiveDependencyResolver(settings, logger, cache); - - foreach(var (package, version) in packageReferences) - { - dependencyGraphResolver.AddPackageReference(package, version); - } - - var dependencyGraph = await dependencyGraphResolver.ResolveGraph(_targetFramework, _targetRuntime).ConfigureAwait(false); - var localPackages = await dependencyGraphResolver.DownloadPackages(dependencyGraph).ConfigureAwait(false); - - var entryBuilder = new NugetRepositoryEntryBuilder(logger, dependencyGraph.Conventions) - .WithTarget(new FrameworkRuntimePair(NuGetFramework.Parse(_targetFramework), _targetRuntime)); - - var entries = localPackages.Select(entryBuilder.ResolveGroups).ToArray(); - - var (frameworkEntries, frameworkOverrides) = await new FrameworkDependencyResolver(dependencyGraphResolver) - .ResolveFrameworkPackages(entries, _targetFramework) - .ConfigureAwait(false); - - var overridenEntries = entries.Select(p => - frameworkOverrides.TryGetValue(p.LocalPackageSourceInfo.Package.Id, out var frameworkOverride) - ? entryBuilder.BuildFrameworkOverride(p, frameworkOverride) - : p); - - return frameworkEntries.Concat(overridenEntries).ToArray(); - - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/External/SdkList.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/External/SdkList.cs deleted file mode 100644 index dcfbe56f..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/External/SdkList.cs +++ /dev/null @@ -1,170 +0,0 @@ -namespace Afas.BazelDotnet.Nuget -{ - public static class SdkList - { - public static string[] Dlls = new string[] - { - "system.runtime.compilerservices.unsafe", - "system.text.encoding.codepages", - "system.text.encodings.web", - //"microsoft.aspnetcore.http.features", - - "system.private.corelib", - "microsoft.csharp", - "microsoft.visualbasic", - "microsoft.win32.primitives", - "microsoft.win32.registry", - "mscorlib", - "netstandard", - "sos.netcore", - "system.appcontext", - "system.buffers", - "system.collections.concurrent", - "system.collections", - "system.collections.immutable", - "system.collections.nongeneric", - "system.collections.specialized", - "system.componentmodel.annotations", - "system.componentmodel.composition", - "system.componentmodel.dataannotations", - "system.componentmodel", - "system.componentmodel.eventbasedasync", - "system.componentmodel.primitives", - "system.componentmodel.typeconverter", - "system.configuration", - "system.console", - "system.core", - "system.data.common", - "system.data", - "system.diagnostics.contracts", - "system.diagnostics.debug", - "system.diagnostics.diagnosticsource", - "system.diagnostics.fileversioninfo", - "system.diagnostics.process", - "system.diagnostics.stacktrace", - "system.diagnostics.textwritertracelistener", - "system.diagnostics.tools", - "system.diagnostics.tracesource", - "system.diagnostics.tracing", - "system", - "system.drawing", - "system.drawing.primitives", - "system.dynamic.runtime", - "system.globalization.calendars", - "system.globalization", - "system.globalization.extensions", - "system.io.compression", - "system.io.compression.filesystem", - "system.io.compression.zipfile", - "system.io", - "system.io.filesystem.accesscontrol", - "system.io.filesystem", - "system.io.filesystem.driveinfo", - "system.io.filesystem.primitives", - "system.io.filesystem.watcher", - "system.io.isolatedstorage", - "system.io.memorymappedfiles", - "system.io.pipes", - "system.io.unmanagedmemorystream", - "system.linq", - "system.linq.expressions", - "system.linq.parallel", - "system.linq.queryable", - "system.net", - "system.net.http", - "system.net.httplistener", - "system.net.mail", - "system.net.nameresolution", - "system.net.networkinformation", - "system.net.ping", - "system.net.primitives", - "system.net.requests", - "system.net.security", - "system.net.servicepoint", - "system.net.sockets", - "system.net.webclient", - "system.net.webheadercollection", - "system.net.webproxy", - "system.net.websockets.client", - "system.net.websockets", - "system.numerics", - "system.numerics.vectors", - "system.objectmodel", - "system.private.datacontractserialization", - "system.private.uri", - "system.private.xml", - "system.private.xml.linq", - "system.reflection.dispatchproxy", - "system.reflection", - "system.reflection.emit", - "system.reflection.emit.ilgeneration", - "system.reflection.emit.lightweight", - "system.reflection.extensions", - "system.reflection.metadata", - "system.reflection.primitives", - "system.reflection.typeextensions", - "system.resources.reader", - "system.resources.resourcemanager", - "system.resources.writer", - "system.runtime.compilerservices.visualc", - "system.runtime", - "system.runtime.extensions", - "system.runtime.handles", - "system.runtime.interopservices", - "system.runtime.interopservices.runtimeinformation", - "system.runtime.interopservices.windowsruntime", - "system.runtime.loader", - "system.runtime.numerics", - "system.runtime.serialization", - "system.runtime.serialization.formatters", - "system.runtime.serialization.json", - "system.runtime.serialization.primitives", - "system.runtime.serialization.xml", - "system.security.accesscontrol", - "system.security.claims", - "system.security.cryptography.algorithms", - "system.security.cryptography.cng", - "system.security.cryptography.csp", - "system.security.cryptography.encoding", - "system.security.cryptography.openssl", - "system.security.cryptography.primitives", - "system.security.cryptography.x509certificates", - "system.security", - "system.security.principal", - "system.security.principal.windows", - "system.security.securestring", - "system.servicemodel.web", - "system.serviceprocess", - "system.text.encoding", - "system.text.encoding.extensions", - "system.text.regularexpressions", - "system.threading", - "system.threading.overlapped", - "system.threading.tasks.dataflow", - "system.threading.tasks", - "system.threading.tasks.extensions", - "system.threading.tasks.parallel", - "system.threading.thread", - "system.threading.threadpool", - "system.threading.timer", - "system.transactions", - "system.transactions.local", - "system.valuetuple", - "system.web", - "system.web.httputility", - "system.windows", - "system.xml", - "system.xml.linq", - "system.xml.readerwriter", - "system.xml.serialization", - "system.xml.xdocument", - "system.xml.xmldocument", - "system.xml.xmlserializer", - "system.xml.xpath", - "system.xml.xpath.xdocument", - "windowsbase", - "netstandard.library", - "system.security.cryptography.protecteddata", - }; - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/FileUtilities.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/FileUtilities.cs deleted file mode 100644 index d9ce0614..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/FileUtilities.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.IO; -using System.Reflection.Metadata; -using System.Reflection.PortableExecutable; - -namespace Afas.BazelDotnet.Nuget -{ - internal static class FileUtilities - { - public static Version GetAssemblyVersion(string sourcePath) - { - using(var assemblyStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read)) - { - Version result = null; - try - { - using(PEReader peReader = new PEReader(assemblyStream, PEStreamOptions.LeaveOpen)) - { - if(peReader.HasMetadata) - { - MetadataReader reader = peReader.GetMetadataReader(); - if(reader.IsAssembly) - { - result = reader.GetAssemblyDefinition().Version; - } - } - } - } - catch(BadImageFormatException) - { - // not a PE - } - - return result; - } - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/FrameworkDependencyResolver.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/FrameworkDependencyResolver.cs deleted file mode 100644 index 990d092b..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/FrameworkDependencyResolver.cs +++ /dev/null @@ -1,219 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using System.Xml.Linq; -using NuGet.Frameworks; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Repositories; -using NuGet.Versioning; - -namespace Afas.BazelDotnet.Nuget -{ - internal class FrameworkDependencyResolver - { - private static readonly IReadOnlyDictionary _frameworkReferenceTargetPackMap = new Dictionary(StringComparer.OrdinalIgnoreCase) - { - ["Microsoft.NETCore.App"] = "Microsoft.NETCore.App.Ref", - ["Microsoft.AspNetCore.App"] = "Microsoft.AspNetCore.App.Ref", - }; - - private readonly TransitiveDependencyResolver _dependencyResolver; - - internal FrameworkDependencyResolver(TransitiveDependencyResolver dependencyResolver) - { - _dependencyResolver = dependencyResolver; - } - - private static string GetFrameworkVersion(string targetFramework) - { - var match = Regex.Match(targetFramework, "(?:net|netcoreapp)([0-9]+\\.[0-9]+)"); - - if(!match.Success) - { - throw new Exception($"Unsupported targetFramework {targetFramework}"); - } - - return $"{match.Groups[1].Value}.0"; - } - - public async Task<(IReadOnlyCollection entries, IReadOnlyDictionary overrides)> ResolveFrameworkPackages( - IReadOnlyCollection localPackages, string targetFramework) - { - var existingPackagesLookup = localPackages.ToDictionary(l => l.LocalPackageSourceInfo.Package.Id, l => l, StringComparer.OrdinalIgnoreCase); - var entries = new List(); - var overrides = new Dictionary(StringComparer.OrdinalIgnoreCase); - - // Resolve distinct FrameworkReferences from each nuget package - var localTargetPackages = await Task.WhenAll( - GetTargetPackages(localPackages) - .Select(p => DownloadTargetPackage(p, targetFramework)) - ).ConfigureAwait(false); - - foreach(var targetPackage in localTargetPackages) - { - var frameworkList = GetFrameworkList(targetPackage, targetFramework); - var packageOverrides = GetPackageOverrides(targetPackage); - - // Resolve overrides as specified in the TargetPackage (FrameworkReference) data/PackageOverrides.txt - foreach(var (id, packageOverride) in packageOverrides) - { - // The override does not apply since there is nothing to override - if(!existingPackagesLookup.TryGetValue(id, out var existingPackage)) - { - continue; - } - - var existingPackageIsEmpty = existingPackage.RefItemGroups.SingleOrDefault()?.Items.Any() != true; - if(existingPackageIsEmpty || packageOverride >= existingPackage.Version) - { - if(frameworkList.TryGetValue(id, out var frameworkItem)) - { - // override to a binary from this TargetPackage (data/FrameworkList.xml) - overrides.Add(id, $"//{targetPackage.Package.Id.ToLower()}:current/{frameworkItem.file}"); - } - else - { - // override to null, resulting in dropping the binary reference - overrides.Add(id, null); - } - } - } - - // Keep track of a list of packages that have higher versions than the TargetPackage provided ones - // These binaries are dropped from the TargetPackage and redirected (using deps) to the nuget package - var upgrades = new HashSet(); - - // Resolve conflicts using the assembly version - foreach(var (id, (assemblyName, assemblyVersion)) in frameworkList) - { - // No conflict - if(!existingPackagesLookup.TryGetValue(id, out var existingPackage)) - { - continue; - } - - // Handled by the overrides, no conflict - if(overrides.ContainsKey(id)) - { - continue; - } - - if(OverridesAssemblyVersion(existingPackage, assemblyVersion)) - { - overrides.Add(id, $"//{targetPackage.Package.Id.ToLower()}:current/{assemblyName}"); - } - else - { - upgrades.Add(id); - } - } - - entries.Add( - BuildEntry(targetPackage, targetFramework, frameworkList, upgrades) - ); - } - - return (entries, overrides); - - bool OverridesAssemblyVersion(NugetRepositoryEntry package, Version frameworkListVersion) - { - var refItems = package.RefItemGroups.Single(); - if(!refItems.Items.Any()) - { - return true; - } - var refAssembly = refItems.Items.Single(); - - var conflictingFile = $"{package.LocalPackageSourceInfo.Package.ExpandedPath}/{refAssembly}"; - var conflictingVersion = FileUtilities.GetAssemblyVersion(conflictingFile); - - return frameworkListVersion >= conflictingVersion; - } - } - - private IEnumerable GetTargetPackages(IReadOnlyCollection localPackages) - { - // see core_sdk\core\sdk\3.1.100\Microsoft.NETCoreSdk.BundledVersions.props - var frameworkRefs = localPackages - // TODO consider target framework when multiple specified - .SelectMany(l => l.LocalPackageSourceInfo.Package.Nuspec - .GetFrameworkRefGroups() - .SelectMany(g => g.FrameworkReferences)) - // Temp solution: this is not included in packages props and should be included as an additional argument instead - .Prepend(new FrameworkReference("Microsoft.AspNetCore.App")) - .Distinct() - // Implicit dependency of al netcoreapp projects - .Prepend(new FrameworkReference("Microsoft.NETCore.App")) - .ToArray(); - return frameworkRefs.Select(r => _frameworkReferenceTargetPackMap[r.Name]); - } - - private NugetRepositoryEntry BuildEntry( - LocalPackageSourceInfo targetPackage, - string targetFramework, - Dictionary frameworkList, - HashSet upgrades) - { - var nuGetFramework = NuGetFramework.Parse(targetFramework); - var entry = new NugetRepositoryEntry(targetPackage); - entry.RefItemGroups.Add(new FrameworkSpecificGroup( - nuGetFramework, - frameworkList.Where(pair => !upgrades.Contains(pair.Key)).Select(pair => pair.Value.file).ToArray())); - entry.DependencyGroups.Add(new PackageDependencyGroup( - nuGetFramework, - upgrades.Select(id => new PackageDependency(id)).ToArray())); - return entry; - } - - private async Task DownloadTargetPackage(string targetPackId, string targetFramework) - { - var packGraph = await _dependencyResolver - .ResolveFrameworkReference(targetPackId, GetFrameworkVersion(targetFramework), targetFramework).ConfigureAwait(false); - - var packNode = packGraph.Flattened.Single(); - return await _dependencyResolver.DownloadPackage(packNode).ConfigureAwait(false); - } - - private Dictionary GetFrameworkList(LocalPackageSourceInfo targetPackage, string targetFramework) - { - var frameworkListPath = "data/FrameworkList.xml"; - - if(!targetPackage.Package.Files.Contains(frameworkListPath)) - { - throw new Exception($"No data/FrameworkList.xml found in {targetPackage.Package.Id}"); - } - - return XDocument.Load(Path.Combine(targetPackage.Package.ExpandedPath, frameworkListPath)) - .Descendants("File") - .Where(f => !string.Equals(f.Attribute("Type").Value, "Analyzer", StringComparison.OrdinalIgnoreCase)) - .ToDictionary( - f => f.Attribute("AssemblyName").Value, - f => (file: FixPath(f.Attribute("Path").Value), version: Version.Parse(f.Attribute("AssemblyVersion").Value)), - StringComparer.OrdinalIgnoreCase); - - // Some inconsistency in FrameworkList - string FixPath(string v) => v.StartsWith("ref/") ? v : $"ref/{targetFramework}/{v}"; - } - - private IReadOnlyDictionary GetPackageOverrides(LocalPackageSourceInfo targetPackage) - { - var packageOverridesPath = "data/PackageOverrides.txt"; - - if(!targetPackage.Package.Files.Contains(packageOverridesPath)) - { - return new Dictionary(); - } - - return File.ReadAllLines(Path.Combine(targetPackage.Package.ExpandedPath, packageOverridesPath)) - .Select(l => l.Split("|")) - .ToDictionary(s => s[0], s => NuGetVersion.Parse(s[1]), StringComparer.OrdinalIgnoreCase); - } - - public static PackageDependency ConvertToDependency(FrameworkReference framework) => - new PackageDependency(_frameworkReferenceTargetPackMap[framework.Name]); - } -} diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/LocalPackageExtractor.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/LocalPackageExtractor.cs deleted file mode 100644 index 3adac9b7..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/LocalPackageExtractor.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.DependencyResolver; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Packaging.Signing; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; -using NuGet.Repositories; - -namespace Afas.BazelDotnet.Nuget -{ - internal class LocalPackageExtractor - { - private readonly NuGetv3LocalRepository _v3LocalRepository; - private readonly SourceCacheContext _cache; - private readonly PackageExtractionContext _context; - - public LocalPackageExtractor(ISettings settings, ILogger logger, SourceCacheContext cache) - { - _v3LocalRepository = new NuGetv3LocalRepository(SettingsUtility.GetGlobalPackagesFolder(settings), new LocalPackageFileCache(), false); - _cache = cache; - _context = new PackageExtractionContext(PackageSaveMode.Defaultv3, XmlDocFileSaveMode.Skip, ClientPolicyContext.GetClientPolicy(settings, logger), logger); - } - - public async Task EnsureLocalPackage(IRemoteDependencyProvider provider, - PackageIdentity packageIdentity) - { - if(!_v3LocalRepository.Exists(packageIdentity.Id, packageIdentity.Version)) - { - var downloader = await provider.GetPackageDownloaderAsync(packageIdentity, _cache, _context.Logger, CancellationToken.None); - - var installed = await PackageExtractor.InstallFromSourceAsync( - packageIdentity, - downloader, - _v3LocalRepository.PathResolver, - _context, - CancellationToken.None, - Guid.NewGuid()); - - // 1) If another project in this process installs the package this will return false but userPackageFolder will contain the package. - // 2) If another process installs the package then this will also return false but we still need to update the cache. - // For #2 double check that the cache has the package now otherwise clear - if(installed || !_v3LocalRepository.Exists(packageIdentity.Id, packageIdentity.Version)) - { - // If the package was added, clear the cache so that the next caller can see it. - // Avoid calling this for packages that were not actually installed. - _v3LocalRepository.ClearCacheForIds(new string[] { packageIdentity.Id }); - } - } - - return NuGetv3LocalRepositoryUtility.GetPackage(new[] { _v3LocalRepository }, packageIdentity.Id, packageIdentity.Version); - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryEntry.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryEntry.cs deleted file mode 100644 index 4517ddc6..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryEntry.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using NuGet.Packaging; -using NuGet.Repositories; -using NuGet.Versioning; - -namespace Afas.BazelDotnet.Nuget -{ - internal interface INugetRepositoryEntry - { - NuGetVersion Version { get; } - string Id { get; } - string ExpandedPath { get; } - List RefItemGroups { get; } - List RuntimeItemGroups { get; } - List DebugRuntimeItemGroups { get; } - List ContentFileGroups { get; } - List AnalyzerItemGroups { get; } - List DependencyGroups { get; } - string Hash { get; } - } - - internal class NugetRepositoryEntry : INugetRepositoryEntry - { - public NugetRepositoryEntry(LocalPackageSourceInfo localPackageSourceInfo, - List refItemGroups = null, - List runtimeItemGroups = null, - List debugRuntimeItemGroups = null, - List contentFileGroups = null, - List analyzerItemGroups = null, - List dependencyGroups = null) - { - LocalPackageSourceInfo = localPackageSourceInfo; - RefItemGroups = refItemGroups ?? new List(); - RuntimeItemGroups = runtimeItemGroups ?? new List(); - DebugRuntimeItemGroups = debugRuntimeItemGroups ?? new List(); - ContentFileGroups = contentFileGroups ?? new List(); - AnalyzerItemGroups = analyzerItemGroups ?? new List(); - DependencyGroups = dependencyGroups ?? new List(); - } - - public LocalPackageSourceInfo LocalPackageSourceInfo { get; } - - public NuGetVersion Version => LocalPackageSourceInfo.Package.Version; - - public string Id => LocalPackageSourceInfo.Package.Id; - - public string ExpandedPath => LocalPackageSourceInfo.Package.ExpandedPath; - - public List RefItemGroups { get; } - - public List RuntimeItemGroups { get; } - - public List DebugRuntimeItemGroups { get; } - - public List ContentFileGroups { get; } - - public List AnalyzerItemGroups { get; } - - public List DependencyGroups { get; } - - public string Hash => $"sha512-{ReadHash()}"; - - private string ReadHash() => File.ReadAllText(LocalPackageSourceInfo.Repository.PathResolver.GetHashPath(LocalPackageSourceInfo.Package.Id, LocalPackageSourceInfo.Package.Version)).Trim(); - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryEntryBuilder.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryEntryBuilder.cs deleted file mode 100644 index bd6788f8..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryEntryBuilder.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NuGet.Client; -using NuGet.Common; -using NuGet.ContentModel; -using NuGet.Frameworks; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Repositories; - -namespace Afas.BazelDotnet.Nuget -{ - internal class NugetRepositoryEntryBuilder - { - private readonly ILogger _logger; - private readonly ManagedCodeConventions _conventions; - private readonly List _targets; - - public NugetRepositoryEntryBuilder(ILogger logger, ManagedCodeConventions conventions) - { - _logger = logger; - _conventions = conventions; - _targets = new List(); - } - - public NugetRepositoryEntryBuilder WithTarget(FrameworkRuntimePair target) - { - _targets.Add(target); - return this; - } - - public NugetRepositoryEntryBuilder WithTarget(NuGetFramework target) - { - _targets.Add(new FrameworkRuntimePair(target, runtimeIdentifier: null)); - return this; - } - - public NugetRepositoryEntry ResolveGroups(LocalPackageSourceInfo localPackageSourceInfo) - { - var collection = new ContentItemCollection(); - collection.Load(localPackageSourceInfo.Package.Files); - var allPackageDependencyGroups = localPackageSourceInfo.Package.Nuspec.GetDependencyGroups().ToArray(); - var frameworkReferenceGroups = localPackageSourceInfo.Package.Nuspec.GetFrameworkRefGroups().ToArray(); - - var entry = new NugetRepositoryEntry(localPackageSourceInfo); - - foreach(var target in _targets) - { - SelectionCriteria criteria = _conventions.Criteria.ForFrameworkAndRuntime(target.Framework, target.RuntimeIdentifier); - - // The nunit3testadapter package publishes dll's in build/ - var buildAssemblies = new PatternSet(_conventions.Properties, new[] - { - new PatternDefinition("build/{tfm}/{any?}"), - new PatternDefinition("build/{assembly?}") - }, new[] - { - new PatternDefinition("build/{tfm}/{assembly}"), - new PatternDefinition("build/{assembly}") - }); - - // shipped debug binaries - var netcoreappdebugAssemblies = new PatternSet(_conventions.Properties, new[] - { - new PatternDefinition("netcoreappdebug/{tfm}/{any?}"), - new PatternDefinition("netcoreappdebug/{assembly?}") - }, new[] - { - new PatternDefinition("netcoreappdebug/{tfm}/{assembly}"), - new PatternDefinition("netcoreappdebug/{assembly}") - }); - - // The analyzer dll's are published in analyzers/ or analyzers/dotnet/cs/ - var analyzerAssemblies = new PatternSet(_conventions.Properties, new [] - { - new PatternDefinition("analyzers/dotnet/cs/{assembly?}"), - new PatternDefinition("analyzers/{assembly?}") - }, new [] - { - new PatternDefinition("analyzers/dotnet/cs/{assembly}"), - new PatternDefinition("analyzers/{assembly}") - }); - - AddIfNotNull(entry.RefItemGroups, target.Framework, - collection.FindBestItemGroup(criteria, - _conventions.Patterns.CompileRefAssemblies, - _conventions.Patterns.CompileLibAssemblies) - ?.Items); - - AddIfNotNull(entry.RuntimeItemGroups, target.Framework, - collection.FindBestItemGroup(criteria, - _conventions.Patterns.RuntimeAssemblies, - _conventions.Patterns.NativeLibraries, - buildAssemblies) - ?.Items.Where(IsDll)); - - AddIfNotNull(entry.DebugRuntimeItemGroups, target.Framework, - collection.FindItemGroups(netcoreappdebugAssemblies) - .SingleOrDefault() - ?.Items.Where(IsDll)); - - AddIfNotNull(entry.ContentFileGroups, target.Framework, - collection.FindBestItemGroup(criteria, - _conventions.Patterns.ContentFiles) - ?.Items); - - AddIfNotNull(entry.AnalyzerItemGroups, target.Framework, - collection.FindItemGroups(analyzerAssemblies) - .SingleOrDefault() - ?.Items); - - // Merge FrameworkReferences with normal PackageReferences - var dependencies = NuGetFrameworkUtility.GetNearest(allPackageDependencyGroups, target.Framework); - var frameworks = NuGetFrameworkUtility.GetNearest(frameworkReferenceGroups, target.Framework); - - if(dependencies != null || frameworks != null) - { - entry.DependencyGroups.Add(new PackageDependencyGroup( - dependencies?.TargetFramework ?? frameworks?.TargetFramework, - new[] - { - frameworks?.FrameworkReferences.Select(FrameworkDependencyResolver.ConvertToDependency), - dependencies?.Packages, - } - .SelectMany(v => v ?? Array.Empty()))); - } - } - - return entry; - - // Because Patterns.NativeLibraries matches any we sometimes contain pdb's - // Constructing NativeLibraries ourselves is not possible due to some internal ManagedCodeConventions - static bool IsDll(ContentItem item) => item.Path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase); - - void AddIfNotNull(ICollection c, NuGetFramework targetFramework, IEnumerable items) - { - if(items != null) - { - c.Add(new FrameworkSpecificGroup(targetFramework, items.Select(i => i.Path))); - } - } - } - - public NugetRepositoryEntry BuildFrameworkOverride(NugetRepositoryEntry entry, string frameworkOverride) - { - _logger.LogInformation($"Overwriting {entry.LocalPackageSourceInfo.Package.Id}"); - var newEntry = new NugetRepositoryEntry(entry.LocalPackageSourceInfo); - newEntry.DependencyGroups.AddRange(entry.DependencyGroups); - if(frameworkOverride != null) - { - newEntry.RefItemGroups.Add(new FrameworkSpecificGroup(_targets.Single().Framework, new [] - { - frameworkOverride, - })); - } - return newEntry; - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryGenerator.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryGenerator.cs deleted file mode 100644 index f9dd4ba6..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/NugetRepositoryGenerator.cs +++ /dev/null @@ -1,225 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Credentials; -using NuGet.Frameworks; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; -using NuGet.Protocol.Plugins; - -namespace Afas.BazelDotnet.Nuget -{ - public class NugetRepositoryGenerator - { - private readonly IDependencyResolver _dependencyResolver; - private readonly ILookup _imports; - - public NugetRepositoryGenerator(string nugetConfig, string targetFramework, string targetRuntime, ILookup imports) - : this(new DependencyResolver(nugetConfig, targetFramework, targetRuntime), imports) - { - } - - private NugetRepositoryGenerator(IDependencyResolver dependencyResolver, ILookup imports) - { - _dependencyResolver = dependencyResolver; - _imports = imports; - } - - public async Task WriteRepository(IEnumerable<(string package, string version)> packageReferences) - { - var packages = await _dependencyResolver.Resolve(packageReferences).ConfigureAwait(false); - - var symlinks = new HashSet<(string link, string target)>(); - - foreach(var entryGroup in packages.GroupBy(e => e.Id, StringComparer.OrdinalIgnoreCase)) - { - var id = entryGroup.Key.ToLower(); - bool isSingle = entryGroup.Count() == 1; - - if(isSingle) - { - WriteBuildFile(entryGroup.Single(), id); - } - else - { - WriteBuildFile(entryGroup, id); - } - - // Possibly link multiple versions - foreach(var entry in entryGroup) - { - symlinks.Add(($"{id}/{entry.Version}", entry.ExpandedPath)); - - if(isSingle) - { - symlinks.Add(($"{id}/current", entry.ExpandedPath)); - } - } - } - - File.WriteAllText("BUILD", ""); - - File.WriteAllText("symlinks_manifest", string.Join("\n", symlinks - .Select(sl => $@"{sl.link} {sl.target}"))); - - File.WriteAllText("link.cmd", @" -for /F ""usebackq tokens=1,2 delims= "" %%i in (""symlinks_manifest"") do mklink /J ""%%i"" ""%%j"" -exit /b %errorlevel% -"); - var proc = Process.Start(new ProcessStartInfo("cmd.exe", "/C link.cmd") - { - RedirectStandardOutput = true, - }); - proc.StandardOutput.ReadToEnd(); - proc.WaitForExit(); - - if(proc.ExitCode != 0) - { - throw new Exception("Creating symlinks exited non 0"); - } - } - - private void WriteBuildFile(INugetRepositoryEntry entry, string id) - { - var content = $@"package(default_visibility = [""//visibility:public""]) -load(""@io_bazel_rules_dotnet//dotnet:defs.bzl"", ""core_import_library"") - -exports_files([""contentfiles.txt""]) - -{CreateTarget(entry)}"; - - var filePath = $"{id}/BUILD"; - new FileInfo(filePath).Directory.Create(); - File.WriteAllText(filePath, content); - - // Also write a special file that lists the content files in this package. - // This is to work around the fact that we cannot easily expose folders. - File.WriteAllLines($"{id}/contentfiles.txt", GetContentFiles(entry).Select(v => $"current/{v}")); - } - - private void WriteBuildFile(IGrouping entryGroup, string id) - { - var content = $@"package(default_visibility = [""//visibility:public""]) -load(""@io_bazel_rules_dotnet//dotnet:defs.bzl"", ""core_import_library"") - -{string.Join("\n\n", entryGroup.Select(CreateTarget))}"; - - var filePath = $"{id}/BUILD"; - new FileInfo(filePath).Directory.Create(); - File.WriteAllText(filePath, content); - } - - private IEnumerable GetContentFiles(INugetRepositoryEntry package) - { - var group = package.ContentFileGroups.SingleOrDefault(); - if(group?.Items.Any() == true) - { - // Symlink optimization to link the entire group folder e.g. contentFiles/any/netcoreapp3.1 - // We assume all files in a group have the same prefix - //yield return string.Join('/', group.Items.First().Split('/').Take(3)); - - foreach(var item in group.Items) - { - yield return item; - } - } - } - - private string CreateTarget(INugetRepositoryEntry package) - { - var folder = package.Version.ToString(); - - IEnumerable Elems() - { - yield return $@"exports_files(glob([""current/**"", ""{package.Version}/**""]))"; - - yield return $@"filegroup( - name = ""content_files"", - srcs = {StringArray(GetContentFiles(package).Select(v => $"{folder}/{v}"))}, -)"; - - var name = package.Id.ToLower(); - - if(_imports.Contains(name)) - { - var selects = _imports[name].ToDictionary(i => i.configSetting, i => i.target); - name += "__nuget"; - selects["//conditions:default"] = name; - - yield return $@"alias( - name = ""{package.Id.ToLower()}"", - actual = select({Indent(Dict(selects))}) -)"; - } - - bool hasDebugDlls = package.DebugRuntimeItemGroups.Count != 0; - var libs = StringArray(package.RuntimeItemGroups.SingleOrDefault()?.Items.Select(v => $"{folder}/{v}")); - - if(hasDebugDlls) - { - yield return @" -config_setting( - name = ""compilation_mode_dbg"", - values = { - ""compilation_mode"": ""dbg"", - }, -)"; - libs = Indent($@"select({{ - "":compilation_mode_dbg"": {StringArray(package.DebugRuntimeItemGroups.Single().Items.Select(v => $"{folder}/{v}"))}, - ""//conditions:default"": {libs}, -}})"); - } - - - yield return $@"core_import_library( - name = ""{name}"", - libs = {libs}, - refs = {StringArray(package.RefItemGroups.SingleOrDefault()?.Items.Select(v => v.StartsWith("//") ? v : $"{folder}/{v}"))}, - analyzers = {StringArray(package.AnalyzerItemGroups.SingleOrDefault()?.Items.Select(v => v.StartsWith("//") ? v : $"{folder}/{v}"))}, - deps = {StringArray(package.DependencyGroups.SingleOrDefault()?.Packages.Select(p => $"//{p.Id.ToLower()}"))}, - data = ["":content_files""], - version = ""{package.Version}"", -)"; - } - - return string.Join("\n\n", Elems()); - } - - private static string Indent(string input) - { - var lines = input.Split('\n'); - if(lines.Length > 1) - { - return $"{lines[0]}\n{string.Join('\n', lines[1..].Select(l => "" + $" {l}"))}"; - } - return lines[0]; - } - - private static string StringArray(IEnumerable items) => items?.Any() != true ? "[]" : Indent($@"[ -{string.Join(",\n", items.Select(i => $@" ""{i}"""))} -]"); - - private static string Dict(IReadOnlyDictionary items) - { - var s = new StringBuilder(); - - s.Append("{\n"); - - foreach(var (key, value) in items) - { - s.Append($@" ""{key}"": ""{value}"", -"); - } - - s.Append("}"); - - return s.ToString(); - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/TransitiveDependencyResolver.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/TransitiveDependencyResolver.cs deleted file mode 100644 index f85f8417..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/TransitiveDependencyResolver.cs +++ /dev/null @@ -1,197 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using NuGet.Commands; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.DependencyResolver; -using NuGet.Frameworks; -using NuGet.LibraryModel; -using NuGet.Packaging.Core; -using NuGet.ProjectModel; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; -using NuGet.Repositories; -using NuGet.RuntimeModel; -using NuGet.Versioning; - -namespace Afas.BazelDotnet.Nuget -{ - internal class TransitiveDependencyResolver - { - private const string _rootProjectName = "Root"; - private const string _rootProjectVersion = "1.0.0"; - - private readonly RemoteWalkContext _context; - private readonly LocalPackageExtractor _localPackageExtractor; - private readonly List _packages; - - public TransitiveDependencyResolver(ISettings settings, ILogger logger, SourceCacheContext cache) - { - _context = CreateRemoteWalkContext(settings, cache, logger); - _localPackageExtractor = new LocalPackageExtractor(settings, _context.Logger, _context.CacheContext); - _packages = new List(); - } - - public TransitiveDependencyResolver AddPackageReference(string package, string version) - { - _packages.Add(new LibraryRange(package, VersionRange.Parse(version), LibraryDependencyTarget.Package)); - return this; - } - - public async Task ResolveFrameworkReference(string id, string version, string targetFramework) - { - var nugetTargetFramework = NuGetFramework.Parse(targetFramework); - return await GetIndependentGraph(id, version, nugetTargetFramework, _context).ConfigureAwait(false); - } - - public async Task ResolveGraph(string targetFramework, string targetRuntime = null) - { - var nugetTargetFramework = NuGetFramework.Parse(targetFramework); - PrepareRootProject(nugetTargetFramework); - - var independentGraph = await GetIndependentGraph(_rootProjectName, _rootProjectVersion, nugetTargetFramework, _context).ConfigureAwait(false); - - if(string.IsNullOrEmpty(targetRuntime)) - { - return independentGraph; - } - - // We could target multiple runtimes with RuntimeGraph.Merge - var platformSpecificGraph = await GetPlatformSpecificGraph(independentGraph, _rootProjectName, _rootProjectVersion, - nugetTargetFramework, targetRuntime, _context, _localPackageExtractor) - .ConfigureAwait(false); - - return platformSpecificGraph; - } - - public async Task> DownloadPackages(RestoreTargetGraph dependencyGraph) - { - return await Task.WhenAll(dependencyGraph.Flattened - .Where(i => !string.Equals(i.Key.Name, _rootProjectName, StringComparison.OrdinalIgnoreCase)) - .Select(DownloadPackage)); - } - - public Task DownloadPackage(GraphItem item) => - _localPackageExtractor.EnsureLocalPackage(item.Data.Match.Provider, ToPackageIdentity(item.Data.Match)); - - private void PrepareRootProject(NuGetFramework targetFramework) - { - PackageSpec project = new PackageSpec(new List - { - new TargetFrameworkInformation - { - FrameworkName = targetFramework, - } - }); - project.Name = _rootProjectName; - project.Version = NuGetVersion.Parse(_rootProjectVersion); - - project.Dependencies = _packages.Select(package => new LibraryDependency - { - LibraryRange = package, - Type = LibraryDependencyType.Build, - IncludeType = LibraryIncludeFlags.None, - SuppressParent = LibraryIncludeFlags.All, - AutoReferenced = true, - GeneratePathProperty = false, - }) - .ToList(); - - // In case we get re-used we clear the previous value first - _context.ProjectLibraryProviders.Clear(); - _context.ProjectLibraryProviders.Add(new PackageSpecReferenceDependencyProvider(new[] - { - new ExternalProjectReference( - project.Name, - project, - msbuildProjectPath: null, - projectReferences: Enumerable.Empty()), - }, _context.Logger)); - } - - private RemoteWalkContext CreateRemoteWalkContext(ISettings settings, SourceCacheContext cache, ILogger logger) - { - // nuget.org etc. - var globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(settings); - var localRepository = Repository.Factory.GetCoreV3(globalPackagesFolder, FeedType.FileSystemV3); - var sourceRepositoryProvider = new SourceRepositoryProvider(new PackageSourceProvider(settings), Repository.Provider.GetCoreV3()); - - var context = new RemoteWalkContext(cache, logger); - - context.LocalLibraryProviders.Add(new SourceRepositoryDependencyProvider(localRepository, logger, cache, - ignoreFailedSources: true, - fileCache: new LocalPackageFileCache(), - ignoreWarning: true, - isFallbackFolderSource: false)); - - foreach(var remoteRepository in sourceRepositoryProvider.GetRepositories()) - { - context.RemoteLibraryProviders.Add(new SourceRepositoryDependencyProvider(remoteRepository, logger, cache, - ignoreFailedSources: cache.IgnoreFailedSources, - fileCache: new LocalPackageFileCache(), - ignoreWarning: false, - isFallbackFolderSource: false)); - } - - return context; - } - - private async Task GetIndependentGraph(string package, string version, NuGetFramework nuGetFramework, RemoteWalkContext context) - { - var result = await new RemoteDependencyWalker(context).WalkAsync( - new LibraryRange(package, VersionRange.Parse(version), LibraryDependencyTarget.All), - nuGetFramework, - runtimeGraph: RuntimeGraph.Empty, - recursive: true, - runtimeIdentifier: null); - - return RestoreTargetGraph.Create(RuntimeGraph.Empty, new[] - { - result - }, _context, _context.Logger, nuGetFramework, runtimeIdentifier: null); - } - - private static async Task GetPlatformSpecificGraph(RestoreTargetGraph independentGraph, - string package, string version, NuGetFramework framework, string runtimeIdentifier, - RemoteWalkContext context, LocalPackageExtractor extractor) - { - var graphTask = independentGraph.Flattened - .Where(m => m.Data?.Match?.Library?.Type == LibraryType.Package) - .Select(GetRuntimeGraphTask); - - var graphs = (await Task.WhenAll(graphTask)) - .Where(i => i != null); - - var runtimeGraph = graphs.Aggregate(RuntimeGraph.Empty, RuntimeGraph.Merge); - - // This results in additional entries - var resultWin = await new RemoteDependencyWalker(context).WalkAsync( - new LibraryRange(package, VersionRange.Parse(version), LibraryDependencyTarget.All), - framework, - runtimeGraph: runtimeGraph, - recursive: true, - runtimeIdentifier: runtimeIdentifier); - - return RestoreTargetGraph.Create(runtimeGraph, new[] - { - resultWin - }, context, context.Logger, framework, runtimeIdentifier); - - async Task GetRuntimeGraphTask(GraphItem item) - { - var packageIdentity = ToPackageIdentity(item.Data.Match); - - var localPackageSourceInfo = await extractor.EnsureLocalPackage(item.Data.Match.Provider, packageIdentity); - - return localPackageSourceInfo?.Package?.RuntimeGraph; - } - } - - private static PackageIdentity ToPackageIdentity(RemoteMatch match) - { - return new PackageIdentity(match.Library.Name, match.Library.Version); - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/ZipArchiveRepositoryGenerator.cs b/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/ZipArchiveRepositoryGenerator.cs deleted file mode 100644 index bae6e24f..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Nuget/BazelDotnet.Nuget/ZipArchiveRepositoryGenerator.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using NuGet.Packaging.Core; - -namespace Afas.BazelDotnet.Nuget -{ - public class ZipArchiveRepositoryGenerator - { - private readonly IDependencyResolver _dependencyResolver; - - public ZipArchiveRepositoryGenerator(string nugetConfig, string targetFramework, string targetRuntime) - : this(new DependencyResolver(nugetConfig, targetFramework, targetRuntime)) - { - } - - private ZipArchiveRepositoryGenerator(IDependencyResolver dependencyResolver) - { - _dependencyResolver = dependencyResolver; - } - - public async Task Write(IEnumerable<(string package, string version)> packageReferences) - { - var packages = await _dependencyResolver.Resolve(packageReferences).ConfigureAwait(false); - - await using var file = File.Open("nuget.bzl", FileMode.Create, FileAccess.Write); - await using var writer = new StreamWriter(file); - - Write(packages, writer); - } - - private void Write(INugetRepositoryEntry[] nugetRepositoryEntries, TextWriter writer) - { - writer.WriteLine("packages = ["); - foreach(var entry in nugetRepositoryEntries) - { - writer.Write($"(\"{entry.Id}\", \"{entry.Version}\", \"{entry.Hash}\", ["); - foreach(var dependency in entry.DependencyGroups.SingleOrDefault()?.Packages ?? Array.Empty()) - { - writer.Write($"\n \"{dependency.Id}\","); - } - writer.WriteLine("]),"); - } - writer.WriteLine("]"); - } - } -} diff --git a/tools/nuget/src/Afas.BazelDotnet.Project/Afas.BazelDotnet.Project.csproj b/tools/nuget/src/Afas.BazelDotnet.Project/Afas.BazelDotnet.Project.csproj deleted file mode 100644 index 1ee09b0d..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Project/Afas.BazelDotnet.Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net5.0 - - - diff --git a/tools/nuget/src/Afas.BazelDotnet.Project/BUILD.bazel b/tools/nuget/src/Afas.BazelDotnet.Project/BUILD.bazel deleted file mode 100644 index 07eb4e3a..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Project/BUILD.bazel +++ /dev/null @@ -1,19 +0,0 @@ -load("//dotnet:defs.bzl", "csharp_library") - -csharp_library( - name = "Afas.BazelDotnet.Project", - srcs = glob( - ["**/*.cs"], - exclude = [ - "**/obj/**", - "**/bin/**", - ], - ), - target_frameworks = ["net6.0"], - targeting_packs = [ - "@paket.rules_dotnet_nuget_packages//microsoft.netcore.app.ref", - ], - visibility = ["//visibility:public"], - deps = [ - ], -) diff --git a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/BazelDefinition.cs b/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/BazelDefinition.cs deleted file mode 100644 index 2d001f44..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/BazelDefinition.cs +++ /dev/null @@ -1,223 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; - -namespace Afas.BazelDotnet.Project -{ - internal class BazelDefinition - { - private readonly CsProjectFileDefinition _csProjectFileDefinition; - internal const string DefaultVisibility = "//visibility:public"; - - public BazelDefinition(CsProjectFileDefinition csProjectFileDefinition, string label, string type, string outputAssembly, - IReadOnlyCollection srcPatterns, IReadOnlyCollection deps, - (IReadOnlyCollection, IReadOnlyCollection)? resources, - IReadOnlyCollection resx, - List dataFiles, - List data, - string visibility = DefaultVisibility, - bool testOnly = false) - { - _csProjectFileDefinition = csProjectFileDefinition; - Label = label; - Type = type; - OutputAssembly = outputAssembly; - SrcPatterns = srcPatterns; - Deps = deps; - Resources = resources; - Resx = resx; - DataFiles = dataFiles; - Data = data; - Visibility = visibility; - TestOnly = testOnly; - } - - public string Label { get; } - - public string Type { get; } - - public string OutputAssembly { get; } - - public IReadOnlyCollection SrcPatterns { get; } - - public IReadOnlyCollection Deps { get; } - - public (IReadOnlyCollection includes, IReadOnlyCollection excludes)? Resources { get; } - - public IReadOnlyCollection Resx { get; } - - public List DataFiles { get; } - - public List Data { get; } - - public string Visibility { get; } - - public bool TestOnly { get; } - - public string Serialize(string appendString) - { - // load - // package - // rules - return Regex.Replace(WriteRule(appendString), "(? GetUsedMethods() - { - if(!Type.Equals("core_nunit3_test")) - { - yield return Type; - } - - if(Resources != null) - { - yield return "core_resource_multi"; - } - - if(Resx.Any()) - { - yield return "core_resx"; - } - } - - private string RenderResources() - { - var result = string.Empty; - - if(Resources != null) - { - var includes = string.Join(", ", Resources.Value.includes.Select(Quote)); - var excludes = string.Join(", ", Resources.Value.excludes - .Append("**/obj/**") - .Append("**/bin/**") - .Select(Quote)); - - result += $"\ncore_resource_multi(name = \"Resources\", identifierBase = \"Afas\", srcs = glob([{includes}], exclude = [{excludes}]))\n" + - "resources.append(\"Resources\")\n"; - } - - if(Resx.Any()) - { - result += string.Join("\n", Resx.Select(RenderResx)) + "\n"; - } - - return result; - - string RenderResx(string resx) - { - var name = resx.Replace("/", "."); - var output = $"Afas.{Path.GetFileNameWithoutExtension(name)}.resources"; - if(name.Equals(resx, StringComparison.OrdinalIgnoreCase)) - { - name = $"_{name}"; - } - return $@"core_resx( - name = ""{name}"", - src = ""{resx}"", - out = ""{output}"", -) -resources.append(""{name}"")"; - } - } - - private string RenderLoad() - { - var result = string.Empty; - - var methods = string.Join(", ", GetUsedMethods().Select(Quote)); - - if(methods.Any()) - { - result += $"load(\"@io_bazel_rules_dotnet//dotnet:defs.bzl\", {methods})\n"; - } - - if(Type.Equals("core_nunit3_test")) - { - result += "load(\"//devtools/bazel:test.bzl\", \"core_nunit3_test\")\n"; - } - - return result; - } - - private string RenderData() - { - if(!Data.Any() && !DataFiles.Any()) - { - return "[]"; - } - - if(Data.Any() && DataFiles.Any()) - { - return $@"[{string.Join(", ", Data.Select(Quote))}] + glob([{string.Join(", ", DataFiles.Select(Quote))}], exclude = [""**/obj/**"", ""**/bin/**""])"; - } - - if(Data.Any()) - { - return $@"[{string.Join(", ", Data.Select(Quote))}]"; - } - - return $@"glob([{string.Join(", ", DataFiles.Select(Quote))}], exclude = [""**/obj/**"", ""**/bin/**""])"; - } - - private string WriteRule(string appendString) - { - var optionalProperties = string.Empty; - - if(_csProjectFileDefinition.IsWebSdk) - { - optionalProperties += @" - runtime_properties = { - ""System.GC.Server"": ""true"" - },"; - } - - if(TestOnly) - { - optionalProperties += @" - testonly = True,"; - } - - if(string.Equals(_csProjectFileDefinition.ReadPropertyValue("Nullable"), "enable", StringComparison.OrdinalIgnoreCase)) - { - optionalProperties += @" - nullable = True,"; - } - - var srcs = _csProjectFileDefinition.ReadPropertyValue("BazelSrcs"); - var srcsValue = string.IsNullOrEmpty(srcs) ? string.Join(",\n", SrcPatterns) : "srcs"; - - var processedAppendString = appendString == null ? null : - @$" - -name = ""{Label}"" -{appendString}"; - - return - $@"{RenderLoad()}resources = []{srcs} -{RenderResources()} - -filegroup( - name = ""{Label}__data"", - srcs = {RenderData()}, - visibility = [""{Visibility}""] -) - -{Type}( - name = ""{Label}"", - out = ""{OutputAssembly}"",{optionalProperties} - srcs = {srcsValue}, - resources = resources, - data = ["":{Label}__data""], - deps = [ - {string.Join(",\n ", Deps.Select(Quote))} - ], - dotnet_context_data = ""//:afas_context_data"", - visibility = [""{Visibility}""] -){processedAppendString}"; - } - - private static string Quote(string n) => $@"""{n}"""; - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/BazelDefinitionBuilder.cs b/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/BazelDefinitionBuilder.cs deleted file mode 100644 index cb8fea25..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/BazelDefinitionBuilder.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; - -namespace Afas.BazelDotnet.Project -{ - internal class BazelDefinitionBuilder - { - private readonly CsProjectFileDefinition _definition; - private readonly string _nugetWorkspace; - private string _visibility = BazelDefinition.DefaultVisibility; - - public BazelDefinitionBuilder(CsProjectFileDefinition definition, string nugetWorkspace) - { - _definition = definition; - _nugetWorkspace = nugetWorkspace; - } - - public BazelDefinition Build() - { - return new BazelDefinition( - _definition, - Path.GetFileNameWithoutExtension(_definition.RelativeFilePath), - GetRuleType(_definition), - $"{Path.GetFileNameWithoutExtension(_definition.RelativeFilePath)}.dll", - BuildSrcPatterns().ToArray(), - GetDependencies().ToArray(), - GetResources(), - GetResx(), - _definition.CopyToOutput, - _definition.BazelData, - _visibility, - _definition.TestOnly - ); - } - - private IEnumerable GetDependencies() => - BuildExternalDependencies().Concat(BuildInternalDependencies()); - - private (IReadOnlyCollection, IReadOnlyCollection)? GetResources() - { - var includes = _definition.EmbeddedResources.Where(e => e.Type == EmbeddedResourceType.Include).Select(e => e.GetNormalizedValue()).ToArray(); - var excludes = _definition.EmbeddedResources.Where(e => e.Type == EmbeddedResourceType.Remove).Select(e => e.GetNormalizedValue()).ToArray(); - - if(!includes.Any()) - { - return null; - } - - return (includes, excludes); - } - - private IReadOnlyCollection GetResx() - { - return _definition.EmbeddedResources.Where(e => e.Type == EmbeddedResourceType.Update && e.Value.EndsWith(".resx")).Select(e => e.GetNormalizedValue()).ToArray(); - } - - private IEnumerable BuildInternalDependencies() - { - foreach(var projectReference in _definition.ProjectReference.Distinct(StringComparer.OrdinalIgnoreCase)) - { - yield return $"{projectReference}"; - } - } - - private IEnumerable BuildSrcPatterns() - { - // { GetLabel(_definition.RelativeFilePath)}/ - yield return $@"glob([""**/*.cs""], exclude = [""**/obj/**"", ""**/bin/**""])"; - } - - private IEnumerable BuildExternalDependencies() - { - foreach(var reference in _definition.PackageReferences) - { - yield return $"@{_nugetWorkspace}//{reference.ToLower()}"; - } - } - - private string GetLabel(string relativeFilePath) - { - return relativeFilePath - // remove file name - .Replace(Path.GetFileName(relativeFilePath), string.Empty, StringComparison.OrdinalIgnoreCase) - // Fix slashes - .Replace('\\', '/') - .TrimEnd('/'); - } - - private string GetRuleType(CsProjectFileDefinition definition) - { - switch(definition.Type) - { - case ProjectType.Binary: - return "core_binary"; - case ProjectType.Test: - return "core_nunit3_test"; - case ProjectType.Library: - return "core_library"; - default: - throw new NotSupportedException($"{definition.Type} is not a supported project type"); - } - } - - public BazelDefinitionBuilder Visibility(string target) - { - _visibility = target; - return this; - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/CsProjBuildFileGenerator.cs b/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/CsProjBuildFileGenerator.cs deleted file mode 100644 index 5b2eee76..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/CsProjBuildFileGenerator.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Afas.BazelDotnet.Project -{ - public class CsProjBuildFileGenerator - { - private readonly string _workspace; - private readonly string _nugetWorkspace; - private readonly IReadOnlyDictionary _importLabels; - private readonly string _appendString; - private readonly IReadOnlyDictionary _visibilityOptions; - - public CsProjBuildFileGenerator(string workspace, string nugetWorkspace, IReadOnlyDictionary imports, string appendString, - Dictionary visibilityOptions) - { - _workspace = workspace; - _nugetWorkspace = nugetWorkspace; - _importLabels = imports; - _appendString = appendString; - _visibilityOptions = visibilityOptions; - } - - private static void WriteFileIfChanged(string path, string newContents) - { - using var buildFileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); - using var reader = new StreamReader(buildFileStream); - - // only write to the file when we have changes so we do not introduce git diff's - if(!string.Equals(newContents, reader.ReadToEnd(), StringComparison.OrdinalIgnoreCase)) - { - buildFileStream.SetLength(0); - using var writer = new StreamWriter(buildFileStream); - writer.Write(newContents); - } - } - - public async Task GlobAllProjects(IReadOnlyCollection searchFolders = null, string extension = "csproj", string exportsFileName = null) - { - var filesEnum = searchFolders?.Any() == true - ? searchFolders - .Select(f => f.Replace('/', '\\')) - .SelectMany(f => Directory.EnumerateFiles(Path.Combine(_workspace, f), $"*.{extension}", SearchOption.AllDirectories)) - : Directory.EnumerateFiles(_workspace, $"*.{extension}", SearchOption.AllDirectories); - - var files = filesEnum - // exclude bazel (tmp) folders - .Where(p => !p.Contains("bazel-")) - .ToArray(); - - files = await Task.WhenAll(files.Select(projectFile => Task.Run(() => - { - var definition = FindAndParseProjectFile(_workspace, projectFile); - - if(definition.ReadPropertyValue("TargetFramework")?.Contains("netstandard") == true) - { - return null; - } - - // only write to the file when we have changes so we do not introduce git diff's - WriteFileIfChanged( - Path.Combine(Path.GetDirectoryName(projectFile), "BUILD"), - new BazelDefinitionBuilder(definition, _nugetWorkspace) - .Visibility(GetVisibility(projectFile)) - .Build() - .Serialize(_appendString)); - - return projectFile; - }))).ConfigureAwait(false); - - if(!string.IsNullOrEmpty(exportsFileName)) - { - var values = files - .Where(f => !string.IsNullOrEmpty(f)) - .ToDictionary(Path.GetFileNameWithoutExtension, ToLabel, StringComparer.OrdinalIgnoreCase) - .Select(l => $"{l.Key}={l.Value}"); - File.WriteAllText(exportsFileName, $"{string.Join("\n", values)}"); - } - } - - private string GetVisibility(string projectFile) - { - foreach(var (pattern, visibilities) in _visibilityOptions) - { - // Currently not supporting actual glob - var p = pattern.EndsWith("**") ? Path.GetDirectoryName(pattern) : pattern; - var prefix = $".\\{p}"; - if(projectFile.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) - { - return string.Join(@""", """, visibilities.Select(ReplaceWildcards)); - - string ReplaceWildcards(string label) - { - var index = label.IndexOf('*'); - if(index < 0) - { - return label; - } - - int pindex = 0; - int i = 0; - var substitutions = projectFile.Substring(prefix.Length + 1).Split('\\'); - var sb = new StringBuilder(); - while(index >= 0) - { - sb.Append(label.Substring(pindex, index - pindex)); - sb.Append(substitutions[i++]); - pindex = index + 1; - index = label.IndexOf('*', pindex); - } - sb.Append(label.Substring(pindex, label.Length - pindex)); - return sb.ToString(); - } - } - } - - return BazelDefinition.DefaultVisibility; - } - - private string ToLabel(string csprojFilePath) - { - var name = Path.GetDirectoryName( - Path.GetRelativePath(_workspace, csprojFilePath)) - .Replace('\\', '/'); - - return $"//{name}:{Path.GetFileNameWithoutExtension(csprojFilePath)}"; - } - - private CsProjectFileDefinition FindAndParseProjectFile(string solutionBasePath, string projectFilePath) - { - var definition = new CsProjectFileDefinition(projectFilePath, solutionBasePath); - return definition.Deserialize(ToLabel, _importLabels, projectFilePath); - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/CsProjectFileDefinition.cs b/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/CsProjectFileDefinition.cs deleted file mode 100644 index f72e5eb7..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/CsProjectFileDefinition.cs +++ /dev/null @@ -1,156 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml.Linq; - -namespace Afas.BazelDotnet.Project -{ - internal class CsProjectFileDefinition - { - private XDocument _document; - - public CsProjectFileDefinition(string projectFilePath, string slnBasePath) - { - RelativeFilePath = Path.GetRelativePath(slnBasePath, projectFilePath); - PackageReferences = new List - { - "Microsoft.NETCore.App.Ref", - }; - ProjectReference = new List(); - BazelData = new List(); - EmbeddedResources = new List(); - CopyToOutput = new List(); - } - - public string RelativeFilePath { get; } - - public ProjectType Type { get; private set; } - - public List PackageReferences { get; } - - public List ProjectReference { get; } - - public List BazelData { get; } - - public List EmbeddedResources { get; } - - public List CopyToOutput { get; } - - public bool TestOnly { get; private set; } - - public string ReadPropertyValue(string name) => _document.Descendants(name).LastOrDefault()?.Value; - - public bool IsWebSdk => string.Equals(_document.Root?.Attribute("Sdk")?.Value, "Microsoft.NET.Sdk.Web"); - - public CsProjectFileDefinition Deserialize(Func csprojToLabel, - IReadOnlyDictionary importLabels, string projectFilePath) - { - _document = XDocument.Load(projectFilePath); - var projectFileDir = Path.GetDirectoryName(projectFilePath); - - Type = GetProjectType(_document); - - foreach(var reference in _document.Descendants("PackageReference")) - { - var name = reference.Attribute("Include").Value; - - if(importLabels.ContainsKey(name)) - { - ProjectReference.Add(importLabels[name]); - } - else - { - if(name.Equals("microsoft.net.test.sdk", StringComparison.OrdinalIgnoreCase)) - { - PackageReferences.Add("microsoft.testplatform.testhost"); - PackageReferences.Add("microsoft.codecoverage"); - } - else - { - PackageReferences.Add(name); - } - } - } - - foreach(var frameworkReference in _document.Descendants("FrameworkReference")) - { - // TODO naming .Ref? - var name = frameworkReference.Attribute("Include").Value; - PackageReferences.Add($"{name}.Ref"); - } - - foreach(var descendant in _document.Descendants("ProjectReference")) - { - var include = descendant.Attribute("Include").Value; - var name = Path.GetFileNameWithoutExtension(include); - - if(importLabels.ContainsKey(name)) - { - ProjectReference.Add(importLabels[name]); - } - else - { - ProjectReference.Add(csprojToLabel(Path.Combine(projectFileDir, include))); - } - } - - foreach(var bazelDataArray in _document.Descendants("BazelData")) - { - BazelData.AddRange(bazelDataArray.Value.Split(';')); - } - - foreach(var resource in _document.Descendants("EmbeddedResource")) - { - var include = resource.Attribute("Include")?.Value; - var remove = resource.Attribute("Remove")?.Value; - var update = resource.Attribute("Update")?.Value; - - if(include != null) - { - EmbeddedResources.Add(new EmbeddedResourceDefinition(EmbeddedResourceType.Include, include)); - } - if(remove != null) - { - EmbeddedResources.Add(new EmbeddedResourceDefinition(EmbeddedResourceType.Remove, remove)); - } - if(update != null) - { - EmbeddedResources.Add(new EmbeddedResourceDefinition(EmbeddedResourceType.Update, update)); - } - } - - foreach(var copyNode in _document.Descendants("CopyToOutputDirectory")) - { - // PreserveNewest ? - - var include = copyNode.Parent?.Attribute("Include")?.Value - ?? copyNode.Parent?.Attribute("Update")?.Value; - if(include != null) - { - CopyToOutput.Add(include.Replace("\\", "/")); - } - } - - TestOnly = string.Equals(_document.Descendants("BazelTestOnly").LastOrDefault()?.Value, "true", StringComparison.OrdinalIgnoreCase); - - return this; - } - - private ProjectType GetProjectType(XDocument document) - { - var outputType = document.Descendants("OutputType").FirstOrDefault(); - if(outputType != null && outputType.Value.Equals("Exe", StringComparison.OrdinalIgnoreCase)) - { - return ProjectType.Binary; - } - - if(RelativeFilePath.EndsWith("Test.csproj") || RelativeFilePath.EndsWith("Tests.csproj")) - { - return ProjectType.Test; - } - - return ProjectType.Library; - } - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/EmbeddedResourceDefinition.cs b/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/EmbeddedResourceDefinition.cs deleted file mode 100644 index 9b4e7385..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/EmbeddedResourceDefinition.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Afas.BazelDotnet.Project -{ - internal class EmbeddedResourceDefinition - { - public EmbeddedResourceDefinition(EmbeddedResourceType type, string value) - { - Type = type; - Value = value; - } - - public EmbeddedResourceType Type { get; } - - public string Value { get; } - - public string GetNormalizedValue() => Value.Replace("\\", "/"); - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/EmbeddedResourceType.cs b/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/EmbeddedResourceType.cs deleted file mode 100644 index e99ed50f..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/EmbeddedResourceType.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Afas.BazelDotnet.Project -{ - internal enum EmbeddedResourceType - { - Include, - Remove, - Update, - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/_enums.cs b/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/_enums.cs deleted file mode 100644 index 7a93ad2d..00000000 --- a/tools/nuget/src/Afas.BazelDotnet.Project/BazelDotnet.Project/_enums.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Afas.BazelDotnet.Project -{ - internal enum ProjectType - { - Unknown = 0, - Library, - Binary, - Test - } -} \ No newline at end of file diff --git a/tools/nuget/src/Afas.BazelDotnet/Afas.BazelDotnet.csproj b/tools/nuget/src/Afas.BazelDotnet/Afas.BazelDotnet.csproj deleted file mode 100644 index fc08cb97..00000000 --- a/tools/nuget/src/Afas.BazelDotnet/Afas.BazelDotnet.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net5.0 - Exe - false - true - true - AFAS Software B.V. - AFAS Software B.V. - Profit Focus - Afas - - - - - - - - - - - - - - - - - - diff --git a/tools/nuget/src/Afas.BazelDotnet/BUILD.bazel b/tools/nuget/src/Afas.BazelDotnet/BUILD.bazel deleted file mode 100644 index e3dd0a2a..00000000 --- a/tools/nuget/src/Afas.BazelDotnet/BUILD.bazel +++ /dev/null @@ -1,23 +0,0 @@ -load("//dotnet:defs.bzl", "csharp_binary") - -csharp_binary( - name = "Afas.BazelDotnet", - srcs = glob( - ["**/*.cs"], - exclude = [ - "**/obj/**", - "**/bin/**", - ], - ), - target_frameworks = ["net6.0"], - targeting_packs = [ - "@paket.rules_dotnet_nuget_packages//microsoft.netcore.app.ref", - ], - visibility = ["//visibility:public"], - deps = [ - #Adding built-in .Net libs - "@paket.rules_dotnet_nuget_packages//mcmaster.extensions.commandlineutils", - "//tools/nuget/src/Afas.BazelDotnet.Nuget", - "//tools/nuget/src/Afas.BazelDotnet.Project", - ], -) diff --git a/tools/nuget/src/Afas.BazelDotnet/BazelDotnet/Program.cs b/tools/nuget/src/Afas.BazelDotnet/BazelDotnet/Program.cs deleted file mode 100644 index 12aa373a..00000000 --- a/tools/nuget/src/Afas.BazelDotnet/BazelDotnet/Program.cs +++ /dev/null @@ -1,229 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using System.Xml.Linq; -using Afas.BazelDotnet.Nuget; -using Afas.BazelDotnet.Project; -using McMaster.Extensions.CommandLineUtils; - -namespace Afas.BazelDotnet -{ - public class Program - { - public static void Main(string[] args) - { - var app = new CommandLineApplication - { - Name = "BazelDotnet", - Description = "Bazel file generator for .NET Core projects", - }; - - app.HelpOption("-?|-h|--help"); - - // set the WorkingDir! - // repository C:/Anta/platform/nuget.config -p C:/Anta/platform/Packages.Props - app.Command("repository", repoCmd => - { - var nugetConfig = repoCmd.Argument("nugetConfig", "The path to the Packages.Props file"); - var tfmOption = repoCmd.Option("-t|--tfm", "The target framework to restore", CommandOptionType.SingleOrNoValue); - var packageProps = repoCmd.Option("-p|--package", "Packages.Props files", CommandOptionType.MultipleValue); - var importsOption = repoCmd.Option("-i|--imports", "Import files with dictionary of imported project labels (PackageName=Label)", CommandOptionType.MultipleValue); - - repoCmd.OnExecuteAsync(async _ => - { - var packagePropsFilePaths = packageProps.Values.Select(v => Path.Combine(Directory.GetCurrentDirectory(), v)).ToArray(); - var nugetConfigFilePath = Path.Combine(Directory.GetCurrentDirectory(), nugetConfig.Value); - var tfm = tfmOption.HasValue() ? tfmOption.Value() : "net5.0"; - await WriteRepository(tfm, packagePropsFilePaths, nugetConfigFilePath, importsOption.Values).ConfigureAwait(false); - return 0; - }); - }); - - // set the WorkingDir! - // repository C:/Anta/platform/nuget.config -p C:/Anta/platform/Packages.Props - app.Command("repository2", repoCmd => - { - var nugetConfig = repoCmd.Argument("nugetConfig", "The path to the Packages.Props file"); - var tfmOption = repoCmd.Option("-t|--tfm", "The target framework to restore", CommandOptionType.SingleOrNoValue); - var packageProps = repoCmd.Option("-p|--package", "Packages.Props files", CommandOptionType.MultipleValue); - - repoCmd.OnExecuteAsync(async _ => - { - var packagePropsFilePaths = packageProps.Values.Select(v => Path.Combine(Directory.GetCurrentDirectory(), v)).ToArray(); - var nugetConfigFilePath = Path.Combine(Directory.GetCurrentDirectory(), nugetConfig.Value); - var tfm = tfmOption.HasValue() ? tfmOption.Value() : "net5.0"; - await WriteRepository2(tfm, packagePropsFilePaths, nugetConfigFilePath).ConfigureAwait(false); - return 0; - }); - }); - - // projects --path=C:/Anta/platform --search=generator --workspace=nuget - app.Command("projects", repoCmd => - { - var pathOption = repoCmd.Option("-p|--path", "The path to the workspace root", CommandOptionType.SingleOrNoValue); - var workspaceOption = repoCmd.Option("-w|--workspace", "The workspace to load nugets from", CommandOptionType.SingleOrNoValue); - var exportsOption = repoCmd.Option("-e|--exports", "Exports file with dictionary of provided project labels (PackageName=Label)", CommandOptionType.SingleOrNoValue); - var importsOption = repoCmd.Option("-i|--imports", "Import files with dictionary of imported project labels (PackageName=Label)", CommandOptionType.MultipleValue); - var searchOption = repoCmd.Option("--search", "Specify folders to search", CommandOptionType.MultipleValue); - var appendOption = repoCmd.Option("--append", "Specify a file which contents should be appended to each BUILD file.", CommandOptionType.MultipleValue); - var visibilityOption = repoCmd.Option("-v|--visibility", "Specify {glob}={label} to define visibility for a set of generated BUILD files.", CommandOptionType.MultipleValue); - - repoCmd.HelpOption("-?|-h|--help"); - repoCmd.OnExecuteAsync(async _ => - { - string path; - - if(pathOption.HasValue()) - { - path = pathOption.Value(); - } - else - { - path = Environment.GetEnvironmentVariable("BUILD_WORKSPACE_DIRECTORY"); - - if(string.IsNullOrEmpty(path)) - { - throw new ArgumentException("Environment variable BUILD_WORKSPACE_DIRECTORY is missing"); - } - } - - await GenerateBuildFiles(path, workspaceOption.Value(), exportsOption.Value(), - importsOption.Values, searchOption.Values, appendOption.Values, visibilityOption.Values).ConfigureAwait(false); - return 0; - }); - }); - - if(!args.Any()) - { - app.ShowHelp(); - throw new Exception("No arguments provided"); - } - - app.Execute(args); - } - - private static (string, string)[] ResolvePackages(string packageProps) - { - if(File.Exists(packageProps)) - { - var packagesProps = XElement.Load(packageProps); - - return packagesProps - .Element("ItemGroup") - .Elements("PackageReference") - .Select(el => (el.Attribute("Update")?.Value, el.Attribute("Version")?.Value)) - .Where(Included) - // This one is upgrade due to the FrameworkReference in Afas.Cqrs - .Append(("microsoft.aspnetcore.http.features", "3.1.0")) - .ToArray(); - } - - return Directory.EnumerateFiles(packageProps, "*.csproj", SearchOption.AllDirectories) - .Select(XDocument.Load) - .SelectMany(f => f.Descendants("PackageReference")) - .Select(p => (p.Attribute("Include")?.Value, p.Attribute("Version")?.Value)) - .Where(t => t.Item1 != null && t.Item2 != null) - .Distinct() - .ToArray(); - - bool Included((string update, string version) arg) => - !string.IsNullOrEmpty(arg.update) && - !string.IsNullOrEmpty(arg.version) && - !arg.version.EndsWith("-local-dev", StringComparison.OrdinalIgnoreCase); - } - - private static async Task WriteRepository(string tfm, IEnumerable packagePropsFiles, string nugetConfig, IReadOnlyCollection importMappings = null) - { - // Note: no conlict resolution. Maybe we can add them in the dep graph. For now multiple Packages.Props is not really a use case anymore - (string, string)[] deps = packagePropsFiles - .SelectMany(ResolvePackages) - .Distinct() - .ToArray(); - - var imports = ParseImports(importMappings) - .ToLookup(i => i.project, i => (i.target, i.configSetting), StringComparer.OrdinalIgnoreCase); - - await new NugetRepositoryGenerator(nugetConfig, tfm, "win-x64", imports) - .WriteRepository(deps) - .ConfigureAwait(false); - } - - - private static async Task WriteRepository2(string tfm, IEnumerable packagePropsFiles, string nugetConfig) - { - // Note: no conlict resolution. Maybe we can add them in the dep graph. For now multiple Packages.Props is not really a use case anymore - (string, string)[] deps = packagePropsFiles - .SelectMany(ResolvePackages) - .Distinct() - .ToArray(); - - await new ZipArchiveRepositoryGenerator(nugetConfig, tfm, "win-x64") - .Write(deps) - .ConfigureAwait(false); - } - - private static Task GenerateBuildFiles(string workspace, string nugetWorkspace, string exportsFileName, - IReadOnlyCollection importMappings, IReadOnlyCollection searchFolders, - IReadOnlyCollection appendOptionValues, IReadOnlyCollection visibilityOptionValues) - { - var imports = ParseImports(importMappings) - .ToDictionary(i => i.project, i => i.target); - - var appendString = appendOptionValues?.Any() != true ? null : - string.Join("\r\n", appendOptionValues.Select(File.ReadAllText)); - - var visibilityOptions = visibilityOptionValues - .Select(o => o.Split('=')) - .ToDictionary(o => o[0].Replace('/', '\\'), o => o[1].Split(','), StringComparer.OrdinalIgnoreCase); - - return new CsProjBuildFileGenerator(workspace, nugetWorkspace, imports, appendString, visibilityOptions) - .GlobAllProjects(searchFolders, exportsFileName: exportsFileName); - } - - private static IEnumerable<(string project, string target, string configSetting)> ParseImports(IReadOnlyCollection importMappings = null) - { - if(importMappings == null) - { - yield break; - } - - // parse import cli arguments {reponame}={exports_file}(={conditional_config_setting}) - foreach(var importMapping in importMappings) - { - var split = importMapping.Split("="); // @projects=C:/bazel/external/projects/.exports - var repoOrTarget = split[0]; // @backend//src/Afas.Cqrs:Afas.Cqrs.Definitions==@platform//:use_local_backend - var file = split[1]; - string configSetting = split.Length > 2 ? split[2] : null; // @backend=C:/bazel/external/backend/.exports=@platform//:use_local_backend - - if(string.IsNullOrEmpty(file)) - { - if(!repoOrTarget.Contains(":")) - { - throw new Exception("Received an import without a targetname or mapping file"); - } - - yield return (repoOrTarget.Split(":")[1], repoOrTarget, configSetting); - } - else - { - var lines = File.ReadAllLines(file) - .Select(l => l.Trim()) - .Where(l => !string.IsNullOrEmpty(l)); - - // parse exports_file lines {project_name}={local_target_name} - foreach(var line in lines) - { - var splitLine = line.Split("="); // Project=//src/Project:Project - var project = splitLine[0]; - var target = splitLine[1]; - - // return mapping for project to global_target_name (with repo prefix) - yield return (project, $"{repoOrTarget}{target}", configSetting); // (Project, @projects//src/Project:Project) - } - } - } - } - } -} diff --git a/tools/nuget/src/Afas.BazelDotnet/assets/bazel_dotnet.BUILD b/tools/nuget/src/Afas.BazelDotnet/assets/bazel_dotnet.BUILD deleted file mode 100644 index 498da5c7..00000000 --- a/tools/nuget/src/Afas.BazelDotnet/assets/bazel_dotnet.BUILD +++ /dev/null @@ -1,4 +0,0 @@ -exports_files([ - "Afas.BazelDotnet.exe", - "Afas.BazelDotnet.dll", -]) diff --git a/tools/nuget/src/Afas.BazelDotnet/assets/bazel_dotnet.WORKSPACE b/tools/nuget/src/Afas.BazelDotnet/assets/bazel_dotnet.WORKSPACE deleted file mode 100644 index 82289c05..00000000 --- a/tools/nuget/src/Afas.BazelDotnet/assets/bazel_dotnet.WORKSPACE +++ /dev/null @@ -1 +0,0 @@ -workspace(name = "bazel_dotnet")