├── .editorconfig ├── .gitattributes ├── .github └── workflows │ ├── main.yml │ └── windows-installer.yml ├── .gitignore ├── LICENSE ├── QPM ├── Commands │ ├── CacheCommand.cs │ ├── ClearCommand.cs │ ├── CollapseCommand.cs │ ├── CollectCommand.cs │ ├── ConfigCommand.cs │ ├── DependencyCommand.cs │ ├── PackageCommand.cs │ ├── PublishCommand.cs │ ├── RestoreCommand.cs │ ├── SupportedPropertiesCommand.cs │ └── VersionCommand.cs ├── Data │ ├── AndroidMk.cs │ ├── BmbfMod.cs │ ├── CppProperties.cs │ ├── Module.cs │ └── QPMConfig.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Providers │ ├── AndroidMkProvider.cs │ ├── BmbfModProvider.cs │ ├── CppPropertiesProvider.cs │ ├── LocalConfigProvider.cs │ └── RemoteQPMDependencyResolver.cs ├── PublishHandler.cs ├── QPM.csproj ├── QPMApi.cs ├── SymLinker │ ├── Abstracts │ │ └── ISymLinkCreator.cs │ ├── LinkCreators │ │ ├── LinuxSymLinkCreator.cs │ │ ├── OSXSymLinkCreator.cs │ │ └── WindowsSymLinkCreator.cs │ ├── Linker.cs │ └── SymLinker.Linker.csproj └── Utils.cs ├── QuestPackageManager.Tests ├── PackageHandlerTests │ ├── ChangeVersionTests.cs │ └── CreatePackageTests.cs ├── QuestPackageManager.Tests.csproj ├── RestoreHandlerTests │ ├── CollapseDependenciesTests.cs │ └── CollectDependenciesTests.cs └── Utils.cs ├── QuestPackageManager.sln ├── QuestPackageManager ├── Data │ ├── Config.cs │ ├── ConfigException.cs │ ├── Dependency.cs │ ├── IConfigProvider.cs │ ├── PackageInfo.cs │ ├── SemVerConverter.cs │ └── SharedConfig.cs ├── DependencyException.cs ├── Handlers │ ├── DependencyHandler.cs │ ├── IDependencyResolver.cs │ ├── PackageHandler.cs │ └── RestoreHandler.cs ├── QuestPackageManager.csproj ├── Resources.Designer.cs └── Resources.resx ├── README.md └── installer ├── information.txt └── installer.iss /.editorconfig: -------------------------------------------------------------------------------- 1 | # Remove the line below if you want to inherit .editorconfig settings from higher directories 2 | root = true 3 | 4 | # C# files 5 | [*.cs] 6 | 7 | #### Core EditorConfig Options #### 8 | 9 | # Indentation and spacing 10 | indent_size = 4 11 | indent_style = space 12 | tab_width = 4 13 | 14 | # New line preferences 15 | end_of_line = crlf 16 | insert_final_newline = false 17 | 18 | #### .NET Coding Conventions #### 19 | 20 | # Organize usings 21 | dotnet_separate_import_directive_groups = false 22 | dotnet_sort_system_directives_first = false 23 | file_header_template = unset 24 | 25 | # this. and Me. preferences 26 | dotnet_style_qualification_for_event = false:silent 27 | dotnet_style_qualification_for_field = false:silent 28 | dotnet_style_qualification_for_method = false:warning 29 | dotnet_style_qualification_for_property = false:warning 30 | 31 | # Language keywords vs BCL types preferences 32 | dotnet_style_predefined_type_for_locals_parameters_members = true:warning 33 | dotnet_style_predefined_type_for_member_access = true:silent 34 | 35 | # Parentheses preferences 36 | dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent 37 | dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent 38 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent 39 | dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent 40 | 41 | # Modifier preferences 42 | dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent 43 | 44 | # Expression-level preferences 45 | dotnet_style_coalesce_expression = true:warning 46 | dotnet_style_collection_initializer = true:suggestion 47 | dotnet_style_explicit_tuple_names = true:warning 48 | dotnet_style_null_propagation = true:suggestion 49 | dotnet_style_object_initializer = true:suggestion 50 | dotnet_style_operator_placement_when_wrapping = beginning_of_line 51 | dotnet_style_prefer_auto_properties = true:warning 52 | dotnet_style_prefer_compound_assignment = true:warning 53 | dotnet_style_prefer_conditional_expression_over_assignment = true:warning 54 | dotnet_style_prefer_conditional_expression_over_return = true:silent 55 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning 56 | dotnet_style_prefer_inferred_tuple_names = true:warning 57 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning 58 | dotnet_style_prefer_simplified_boolean_expressions = true:suggestion 59 | dotnet_style_prefer_simplified_interpolation = true:suggestion 60 | 61 | # Field preferences 62 | dotnet_style_readonly_field = true:suggestion 63 | 64 | # Parameter preferences 65 | dotnet_code_quality_unused_parameters = all:warning 66 | 67 | #### C# Coding Conventions #### 68 | 69 | # var preferences 70 | csharp_style_var_elsewhere = false:silent 71 | csharp_style_var_for_built_in_types = false:silent 72 | csharp_style_var_when_type_is_apparent = false:silent 73 | 74 | # Expression-bodied members 75 | csharp_style_expression_bodied_accessors = true:silent 76 | csharp_style_expression_bodied_constructors = false:silent 77 | csharp_style_expression_bodied_indexers = true:silent 78 | csharp_style_expression_bodied_lambdas = true:warning 79 | csharp_style_expression_bodied_local_functions = false:silent 80 | csharp_style_expression_bodied_methods = when_on_single_line:warning 81 | csharp_style_expression_bodied_operators = false:silent 82 | csharp_style_expression_bodied_properties = true:warning 83 | 84 | # Pattern matching preferences 85 | csharp_style_pattern_matching_over_as_with_null_check = true:warning 86 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion 87 | csharp_style_prefer_switch_expression = true:warning 88 | 89 | # Null-checking preferences 90 | csharp_style_conditional_delegate_call = true:suggestion 91 | 92 | # Modifier preferences 93 | csharp_prefer_static_local_function = true:suggestion 94 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent 95 | 96 | # Code-block preferences 97 | csharp_prefer_braces = when_multiline:silent 98 | csharp_prefer_simple_using_statement = true:suggestion 99 | 100 | # Expression-level preferences 101 | csharp_prefer_simple_default_expression = true:suggestion 102 | csharp_style_deconstructed_variable_declaration = true:warning 103 | csharp_style_inlined_variable_declaration = true:warning 104 | csharp_style_pattern_local_over_anonymous_function = true:suggestion 105 | csharp_style_prefer_index_operator = true:suggestion 106 | csharp_style_prefer_range_operator = true:suggestion 107 | csharp_style_throw_expression = true:suggestion 108 | csharp_style_unused_value_assignment_preference = discard_variable:warning 109 | csharp_style_unused_value_expression_statement_preference = discard_variable:silent 110 | 111 | # 'using' directive preferences 112 | csharp_using_directive_placement = outside_namespace:warning 113 | 114 | #### C# Formatting Rules #### 115 | 116 | # New line preferences 117 | csharp_new_line_before_catch = true 118 | csharp_new_line_before_else = true 119 | csharp_new_line_before_finally = true 120 | csharp_new_line_before_members_in_anonymous_types = true 121 | csharp_new_line_before_members_in_object_initializers = true 122 | csharp_new_line_before_open_brace = all 123 | csharp_new_line_between_query_expression_clauses = true 124 | 125 | # Indentation preferences 126 | csharp_indent_block_contents = true 127 | csharp_indent_braces = false 128 | csharp_indent_case_contents = true 129 | csharp_indent_case_contents_when_block = true 130 | csharp_indent_labels = one_less_than_current 131 | csharp_indent_switch_labels = true 132 | 133 | # Space preferences 134 | csharp_space_after_cast = false 135 | csharp_space_after_colon_in_inheritance_clause = true 136 | csharp_space_after_comma = true 137 | csharp_space_after_dot = false 138 | csharp_space_after_keywords_in_control_flow_statements = true 139 | csharp_space_after_semicolon_in_for_statement = true 140 | csharp_space_around_binary_operators = before_and_after 141 | csharp_space_around_declaration_statements = false 142 | csharp_space_before_colon_in_inheritance_clause = true 143 | csharp_space_before_comma = false 144 | csharp_space_before_dot = false 145 | csharp_space_before_open_square_brackets = false 146 | csharp_space_before_semicolon_in_for_statement = false 147 | csharp_space_between_empty_square_brackets = false 148 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 149 | csharp_space_between_method_call_name_and_opening_parenthesis = false 150 | csharp_space_between_method_call_parameter_list_parentheses = false 151 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 152 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 153 | csharp_space_between_method_declaration_parameter_list_parentheses = false 154 | csharp_space_between_parentheses = false 155 | csharp_space_between_square_brackets = false 156 | 157 | # Wrapping preferences 158 | csharp_preserve_single_line_blocks = true 159 | csharp_preserve_single_line_statements = true 160 | 161 | #### Naming styles #### 162 | 163 | # Naming rules 164 | 165 | dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion 166 | dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface 167 | dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i 168 | 169 | dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion 170 | dotnet_naming_rule.types_should_be_pascal_case.symbols = types 171 | dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case 172 | 173 | dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion 174 | dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members 175 | dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case 176 | 177 | # Symbol specifications 178 | 179 | dotnet_naming_symbols.interface.applicable_kinds = interface 180 | dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 181 | dotnet_naming_symbols.interface.required_modifiers = 182 | 183 | dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum 184 | dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 185 | dotnet_naming_symbols.types.required_modifiers = 186 | 187 | dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method 188 | dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 189 | dotnet_naming_symbols.non_field_members.required_modifiers = 190 | 191 | # Naming styles 192 | 193 | dotnet_naming_style.pascal_case.required_prefix = 194 | dotnet_naming_style.pascal_case.required_suffix = 195 | dotnet_naming_style.pascal_case.word_separator = 196 | dotnet_naming_style.pascal_case.capitalization = pascal_case 197 | 198 | dotnet_naming_style.begins_with_i.required_prefix = I 199 | dotnet_naming_style.begins_with_i.required_suffix = 200 | dotnet_naming_style.begins_with_i.word_separator = 201 | dotnet_naming_style.begins_with_i.capitalization = pascal_case 202 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | on: [push, pull_request] 3 | 4 | env: 5 | DOTNET_VERSION: '5.0.x' 6 | 7 | jobs: 8 | build: 9 | runs-on: ${{ matrix.os }} 10 | strategy: 11 | matrix: 12 | runtime: ['ubuntu-x64', 'win-x64', 'osx-x64'] 13 | include: 14 | - runtime: win-x64 15 | os: windows-latest 16 | - runtime: ubuntu-x64 17 | os: ubuntu-latest 18 | - runtime: osx-x64 19 | os: macos-latest 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - uses: actions/cache@v2 24 | with: 25 | path: ~/.nuget/packages 26 | key: nuget-${{ hashFiles('**/packages.lock.json') }} 27 | restore-keys: | 28 | nuget- 29 | - name: Setup .NET Core 30 | uses: actions/setup-dotnet@v1 31 | with: 32 | dotnet-version: ${{ env.DOTNET_VERSION }} 33 | - name: Install dependencies 34 | working-directory: ./QPM 35 | run: dotnet restore 36 | - name: Build ${{ matrix.runtime }} 37 | working-directory: ./QPM 38 | run: dotnet publish -r ${{ matrix.runtime }} -c Release -p:PublishReadyToRun=true 39 | - name: Artifact Upload ${{ matrix.runtime }} 40 | uses: actions/upload-artifact@v2 41 | with: 42 | name: QPM-${{ matrix.runtime }} 43 | path: QPM/bin/Release/net5.0/${{ matrix.runtime }}/publish/ 44 | 45 | checks: 46 | runs-on: ubuntu-latest 47 | 48 | steps: 49 | - uses: actions/checkout@v2 50 | - uses: actions/cache@v2 51 | with: 52 | path: ~/.nuget/packages 53 | key: nuget-${{ hashFiles('**/packages.lock.json') }} 54 | restore-keys: | 55 | nuget- 56 | - name: Setup .NET Core 57 | uses: actions/setup-dotnet@v1 58 | with: 59 | dotnet-version: ${{ env.DOTNET_VERSION }} 60 | - name: Install dependencies 61 | run: dotnet restore 62 | - name: Build 63 | run: dotnet build --configuration Release --no-restore 64 | - name: Test 65 | run: dotnet test --no-restore --verbosity normal 66 | -------------------------------------------------------------------------------- /.github/workflows/windows-installer.yml: -------------------------------------------------------------------------------- 1 | name: Windows Installer 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | name: Build installer on windows 8 | runs-on: windows-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Setup .NET Core 13 | uses: actions/setup-dotnet@v1 14 | with: 15 | dotnet-version: 5.0.102 16 | - name: Download Inno Setup 17 | uses: suisei-cn/actions-download-file@v1 18 | with: 19 | url: https://jrsoftware.org/download.php/is.exe 20 | target: ../ 21 | - name: Install Inno Setup 22 | run: '../is.exe /VERYSILENT /NORESTART /ALLUSERS' 23 | - name: Build QPM 24 | run: dotnet publish -c Release -r win-x64 25 | - name: Compile Installer 26 | run: '& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" /f installer/installer.iss' 27 | - name: Artifact Upload 28 | uses: actions/upload-artifact@v2 29 | with: 30 | name: QPM-installer.exe 31 | path: ./installer/QPM-installer.exe -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb 341 | 342 | # Built Installer files 343 | inno/ 344 | windows-installer.exe -------------------------------------------------------------------------------- /QPM/Commands/CacheCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace QPM.Commands 9 | { 10 | [Command("cache", Description = "Cache control")] 11 | [Subcommand(typeof(CacheClear))] 12 | internal class CacheCommand 13 | { 14 | [Command("clear", Description = "Clear the cache")] 15 | internal class CacheClear 16 | { 17 | private void OnExecute() 18 | { 19 | Utils.DeleteTempDir(); 20 | Utils.WriteSuccess(); 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /QPM/Commands/ClearCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace QPM.Commands 10 | { 11 | [Command("clear", Description = "Clear all resolved dependencies by clearing the lock file")] 12 | internal class ClearCommand 13 | { 14 | private void OnExecute() 15 | { 16 | var fname = Path.Combine(Environment.CurrentDirectory, Program.LocalFileName); 17 | if (File.Exists(fname)) 18 | File.Delete(fname); 19 | // Also delete config.DependenciesDir 20 | var cfg = Program.configProvider.GetConfig(false); 21 | if (cfg is null) 22 | throw new Exception("Cannot clear because there is no valid package in this directory! Have you called 'qpm package create'?"); 23 | Utils.DeleteDirectory(Path.Combine(Environment.CurrentDirectory, cfg.DependenciesDir)); 24 | Utils.WriteSuccess(); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /QPM/Commands/CollapseCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using QuestPackageManager; 3 | using QuestPackageManager.Data; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace QPM.Commands 11 | { 12 | [Command("collapse", Description = "Collect and collapse dependencies and print them to console")] 13 | internal class CollapseCommand 14 | { 15 | private string PrintRestoredDependency(RestoredDependencyPair pair) => $"{pair.Dependency.Id}: ({pair.Dependency.VersionRange}) --> {pair.Version}"; 16 | 17 | private void PrintDependencies(string indent, SharedConfig config) 18 | { 19 | foreach (var p in config.RestoredDependencies) 20 | { 21 | Console.WriteLine(indent + PrintRestoredDependency(p)); 22 | // TODO: Recurse down this properly 23 | } 24 | } 25 | 26 | private async Task OnExecute() 27 | { 28 | var outp = await Program.RestoreHandler.CollectDependencies().ConfigureAwait(false); 29 | var collapsed = RestoreHandler.CollapseDependencies(outp); 30 | foreach (var pair in collapsed) 31 | { 32 | Console.WriteLine($"{PrintRestoredDependency(pair.Key)} (config: {pair.Value.Config.Info.Version}, {pair.Value.RestoredDependencies.Count} restored dependencies)"); 33 | PrintDependencies("- ", pair.Value); 34 | } 35 | Utils.WriteSuccess(); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /QPM/Commands/CollectCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using QuestPackageManager.Data; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace QPM.Commands 10 | { 11 | [Command("collect", Description = "Collect dependencies and print them to console")] 12 | internal class CollectCommand 13 | { 14 | private string PrintRestoredDependency(RestoredDependencyPair pair) => $"{pair.Dependency.Id}: ({pair.Dependency.VersionRange}) --> {pair.Version}"; 15 | 16 | private void PrintDependencies(string indent, SharedConfig config) 17 | { 18 | foreach (var p in config.RestoredDependencies) 19 | { 20 | Console.WriteLine(indent + PrintRestoredDependency(p)); 21 | // TODO: Recurse down this properly 22 | } 23 | } 24 | 25 | private async Task OnExecute() 26 | { 27 | var outp = await Program.RestoreHandler.CollectDependencies().ConfigureAwait(false); 28 | foreach (var pair in outp) 29 | { 30 | Console.WriteLine($"{PrintRestoredDependency(pair.Key)} (config: {pair.Value.Config.Info.Version}, {pair.Value.RestoredDependencies.Count} restored dependencies)"); 31 | PrintDependencies("- ", pair.Value); 32 | } 33 | Utils.WriteSuccess(); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /QPM/Commands/ConfigCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using System; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Threading.Tasks; 5 | 6 | namespace QPM.Commands 7 | { 8 | [Command("config", Description = "Config control")] 9 | [Subcommand(typeof(ConfigCache), typeof(ConfigTimeout), typeof(ConfigSymlinks))] 10 | internal class ConfigCommand 11 | { 12 | [Command("cache", Description = "Get or set the cache path")] 13 | internal class ConfigCache 14 | { 15 | [Argument(0, "path", Description = "Path to place the QPM Cache")] 16 | public string? Path { get; } = null; 17 | 18 | private async Task OnExecute() 19 | { 20 | if (string.IsNullOrEmpty(Path)) 21 | { 22 | Console.WriteLine(Program.Config.CachePath); 23 | } 24 | else 25 | { 26 | Program.Config.CachePath = Path; 27 | await Program.SaveConfig().ConfigureAwait(false); 28 | } 29 | } 30 | } 31 | 32 | [Command("timeout", Description = "Get or set the timeout for web requests")] 33 | internal class ConfigTimeout 34 | { 35 | [Argument(0, "timeout", Description = "Timeout (in seconds) for downloads from QPM API and links provided in qpm configurations")] 36 | public double? Timeout { get; } = null; 37 | 38 | private async Task OnExecute() 39 | { 40 | if (Timeout is null) 41 | { 42 | Console.WriteLine(Program.Config.DependencyTimeoutSeconds); 43 | } 44 | else 45 | { 46 | Program.Config.DependencyTimeoutSeconds = Timeout.Value; 47 | await Program.SaveConfig().ConfigureAwait(false); 48 | } 49 | } 50 | } 51 | 52 | [Command("symlink", Description = "Enable or disable symlink usage")] 53 | [Subcommand(typeof(ConfigSymlinksEnable), typeof(ConfigSymlinksDisable))] 54 | internal class ConfigSymlinks 55 | { 56 | [Command("enable", Description = "Enable symlink usage")] 57 | internal class ConfigSymlinksEnable 58 | { 59 | private async Task OnExecute() 60 | { 61 | Program.Config.UseSymlinks = true; 62 | await Program.SaveConfig().ConfigureAwait(false); 63 | } 64 | } 65 | 66 | [Command("disable", Description = "Disable symlink usage")] 67 | internal class ConfigSymlinksDisable 68 | { 69 | private async Task OnExecute() 70 | { 71 | Program.Config.UseSymlinks = true; 72 | await Program.SaveConfig().ConfigureAwait(false); 73 | } 74 | } 75 | 76 | private void OnExecute() => Console.WriteLine(Program.Config.UseSymlinks ? "enabled" : "disabled"); 77 | } 78 | 79 | private void OnExecute(CommandLineApplication app) => app.ShowHelp(); 80 | } 81 | } -------------------------------------------------------------------------------- /QPM/Commands/DependencyCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using QuestPackageManager.Data; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.ComponentModel.DataAnnotations; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Text.Json; 9 | using System.Threading.Tasks; 10 | 11 | namespace QPM.Commands 12 | { 13 | [Command("dependency", Description = "Dependency control")] 14 | [Subcommand(typeof(DependencyAdd), typeof(DependencyRemove))] 15 | internal class DependencyCommand 16 | { 17 | [Command("add", Description = "Add a new dependency")] 18 | internal class DependencyAdd 19 | { 20 | [Argument(0, "id", Description = "Id of the dependency")] 21 | [Required] 22 | public string Id { get; } 23 | 24 | [Option("-v|--version", CommandOptionType.SingleValue, Description = "Version range to use for the dependency. Defaults to \"*\"")] 25 | public string Version { get; } 26 | 27 | [Argument(2, "additional info", Description = "Additional information for the dependency (as a valid json object)")] 28 | public string AdditionalInfo { get; } 29 | 30 | private void OnExecute() 31 | { 32 | if (string.IsNullOrEmpty(Id)) 33 | throw new ArgumentException("Id for 'dependency add' cannot be null or empty!"); 34 | // Create range for dependency 35 | // Will throw on failure 36 | var range = new SemVer.Range(string.IsNullOrEmpty(Version) ? "*" : Version); 37 | var dep = new Dependency(Id, range); 38 | // Populate AdditionalInfo 39 | if (AdditionalInfo != null) 40 | { 41 | using var doc = JsonDocument.Parse(AdditionalInfo); 42 | if (doc.RootElement.ValueKind != JsonValueKind.Object) 43 | throw new ArgumentException("AdditionalData must be a JSON object!"); 44 | foreach (var p in doc.RootElement.EnumerateObject()) 45 | dep.AdditionalData.Add(p.Name, p.Value); 46 | } 47 | // Call dependency handler add 48 | Program.DependencyHandler.AddDependency(dep); 49 | Console.WriteLine($"Added dependency: {Id} ok!"); 50 | Utils.WriteSuccess(); 51 | } 52 | } 53 | 54 | [Command("remove", Description = "Remove an existing dependency")] 55 | internal class DependencyRemove 56 | { 57 | [Argument(0, "id", Description = "Id to remove")] 58 | [Required] 59 | public string Id { get; } 60 | 61 | private void OnExecute() 62 | { 63 | if (string.IsNullOrEmpty(Id)) 64 | throw new ArgumentException("Id for 'dependency remove' cannot be null or empty!"); 65 | // Call dependency handler remove 66 | if (!Program.DependencyHandler.RemoveDependency(Id)) 67 | throw new InvalidOperationException($"Cannot remove id: {Id} because it is not a dependency!"); 68 | Console.WriteLine($"Removed dependency: {Id} ok!"); 69 | Utils.WriteSuccess(); 70 | } 71 | } 72 | 73 | private void OnExecute(CommandLineApplication app) => app.ShowHelp(); 74 | } 75 | } -------------------------------------------------------------------------------- /QPM/Commands/PackageCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using QuestPackageManager.Data; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.ComponentModel.DataAnnotations; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Text.Json; 9 | using System.Threading.Tasks; 10 | 11 | namespace QPM.Commands 12 | { 13 | [Command("package", Description = "Package control")] 14 | [Subcommand(typeof(PackageCreate), typeof(PackageEdit), typeof(PackageEditExtra))] 15 | internal class PackageCommand 16 | { 17 | [Command("create", Description = "Create a package")] 18 | internal class PackageCreate 19 | { 20 | [Argument(0, "id", "Id of the package to create")] 21 | [Required] 22 | public string Id { get; } 23 | 24 | [Argument(1, "version", "Version of the package to create")] 25 | [Required] 26 | public string Version { get; } 27 | 28 | [Option("-n|--name", CommandOptionType.SingleValue, Description = "Name of the package to create, defaults to id")] 29 | public string Name { get; } 30 | 31 | [Option("-u|--url", CommandOptionType.SingleValue, Description = "Url of the package to create, defaults to empty")] 32 | public string Url { get; } 33 | 34 | [Argument(2, "additional info", Description = "Additional information for the package (as a valid json object)")] 35 | public string AdditionalInfo { get; } 36 | 37 | // This will throw if it fails to do anything (ex: on invalid name and whatnot) 38 | // We may want to make this a bit clearer 39 | private void OnExecute() 40 | { 41 | if (string.IsNullOrEmpty(Id)) 42 | throw new ArgumentException("Id for 'package create' cannot be null or empty!"); 43 | // Create PackageInfo 44 | // Throws on failure to create version 45 | var info = new PackageInfo(string.IsNullOrEmpty(Name) ? Id : Name, Id, new SemVer.Version(Version)); 46 | if (!string.IsNullOrEmpty(Url)) 47 | // Throws on failure to create valid Uri 48 | info.Url = new Uri(Url); 49 | // Populate AdditionalInfo 50 | if (AdditionalInfo != null) 51 | { 52 | // TODO: Figure out this 53 | Console.WriteLine(AdditionalInfo); 54 | using var doc = JsonDocument.Parse(AdditionalInfo); 55 | if (doc.RootElement.ValueKind != JsonValueKind.Object) 56 | throw new ArgumentException("AdditionalData must be a JSON object!"); 57 | foreach (var p in doc.RootElement.EnumerateObject()) 58 | info.AdditionalData.Add(p.Name, p.Value); 59 | } 60 | // Call package handler create 61 | Program.PackageHandler.CreatePackage(info); 62 | Console.WriteLine($"Created package: {Id} name: {info.Name} ok!"); 63 | Utils.WriteSuccess(); 64 | } 65 | } 66 | 67 | [Command("edit", Description = "Edit various properties of the package")] 68 | [Subcommand(typeof(PackageEditId), typeof(PackageEditName), typeof(PackageEditUrl), typeof(PackageEditVersion))] 69 | internal class PackageEdit 70 | { 71 | [Command("version", Description = "Edit the version property of the package")] 72 | internal class PackageEditVersion 73 | { 74 | [Argument(0, "version", Description = "Version to set the package version to")] 75 | [Required] 76 | public string Version { get; } 77 | 78 | private void OnExecute() 79 | { 80 | // Create updated version 81 | // Throws on failure 82 | var newVersion = new SemVer.Version(Version); 83 | // Call package handler change version 84 | Program.PackageHandler.ChangeVersion(newVersion); 85 | Console.WriteLine($"Changed version of package to: {newVersion} ok!"); 86 | Utils.WriteSuccess(); 87 | } 88 | } 89 | 90 | [Command("id", Description = "Edit the id property of the package")] 91 | internal class PackageEditId 92 | { 93 | [Argument(0, "id", Description = "Id to set the package id to")] 94 | [Required] 95 | public string Id { get; } 96 | 97 | private void OnExecute() 98 | { 99 | if (string.IsNullOrEmpty(Id)) 100 | throw new ArgumentException("Id for 'package edit id' cannot be null or empty!"); 101 | Program.PackageHandler.ChangeId(Id); 102 | Console.WriteLine($"Changed id of package to: {Id} ok!"); 103 | Utils.WriteSuccess(); 104 | } 105 | } 106 | 107 | [Command("url", Description = "Edit the url property of the package")] 108 | internal class PackageEditUrl 109 | { 110 | [Argument(0, "url", Description = "Url to set the package url to")] 111 | [Required] 112 | public string Url { get; } 113 | 114 | private void OnExecute() 115 | { 116 | // Create updated url 117 | // Throws on failure 118 | var newUrl = new Uri(Url); 119 | // Call package handler change url 120 | Program.PackageHandler.ChangeUrl(newUrl); 121 | Console.WriteLine($"Changed url of package to: {newUrl} ok!"); 122 | Utils.WriteSuccess(); 123 | } 124 | } 125 | 126 | [Command("name", Description = "Edit the name property of the package")] 127 | internal class PackageEditName 128 | { 129 | [Argument(0, "name", Description = "Name to set the package name to")] 130 | [Required] 131 | public string Name { get; } 132 | 133 | private void OnExecute() 134 | { 135 | if (string.IsNullOrEmpty(Name)) 136 | throw new ArgumentException("Id for 'package edit name' cannot be null or empty!"); 137 | Program.PackageHandler.ChangeName(Name); 138 | Console.WriteLine($"Changed name of package to: {Name} ok!"); 139 | Utils.WriteSuccess(); 140 | } 141 | } 142 | 143 | private void OnExecute(CommandLineApplication app) => app.ShowHelp(); 144 | } 145 | 146 | [Command("edit-extra", Description = "Edit extra supported properties of the package")] 147 | internal class PackageEditExtra 148 | { 149 | [Argument(0, "id", Description = "ID of the property to modify")] 150 | [Required] 151 | public string Id { get; } 152 | 153 | [Argument(1, "value", Description = "Value to set the property to")] 154 | [Required] 155 | public string Value { get; } 156 | 157 | private void OnExecute() 158 | { 159 | if (string.IsNullOrEmpty(Id)) 160 | throw new ArgumentException("Id for 'package edit-extra' cannot be null or empty!"); 161 | var cfg = Program.configProvider.GetConfig(); 162 | var sharedCfg = Program.configProvider.GetSharedConfig(); 163 | var createdDoc = JsonDocument.Parse($"\"{Value}\""); 164 | var elem = createdDoc.RootElement; 165 | cfg.Info.AdditionalData[Id] = elem; 166 | sharedCfg.Config.Info.AdditionalData[Id] = elem; 167 | Program.configProvider.Commit(); 168 | Console.WriteLine($"Changed package additional info: {Id} to: {Value}"); 169 | Utils.WriteSuccess(); 170 | } 171 | } 172 | 173 | private void OnExecute(CommandLineApplication app) => app.ShowHelp(); 174 | } 175 | } -------------------------------------------------------------------------------- /QPM/Commands/PublishCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace QPM.Commands 9 | { 10 | [Command("publish", Description = "Publish package")] 11 | internal class PublishCommand 12 | { 13 | private async Task OnExecute() 14 | { 15 | var res = await Program.PublishHandler.Publish().ConfigureAwait(false); 16 | if (res.IsSuccessStatusCode) 17 | Utils.WriteSuccess(); 18 | else 19 | Utils.WriteFail($"Failed! Status code: {res.StatusCode} ({(int)res.StatusCode})"); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /QPM/Commands/RestoreCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using QuestPackageManager; 3 | using QuestPackageManager.Data; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace QPM.Commands 12 | { 13 | [Command("restore", Description = "Restore and resolve all dependencies from the package")] 14 | internal class RestoreCommand 15 | { 16 | private async Task OnExecute() 17 | { 18 | var config = Program.configProvider.GetConfig(); 19 | if (config is null) 20 | throw new ConfigException("Cannot restore without a valid QPM package! Try 'qpm package create' first."); 21 | var sharedConfig = Program.configProvider.GetSharedConfig(); 22 | Utils.CreateDirectory(Path.Combine(Environment.CurrentDirectory, config.SharedDir)); 23 | Utils.CreateDirectory(Path.Combine(Environment.CurrentDirectory, config.DependenciesDir)); 24 | // We want to delete any existing libs that we no longer need 25 | var deps = await Program.RestoreHandler.CollectDependencies().ConfigureAwait(false); 26 | // Holds all .so files that have been mapped to. False indicates the file should be deleted. 27 | var existingDeps = Directory.EnumerateFiles(config.DependenciesDir).ToDictionary(s => s, s => false); 28 | foreach (var d in deps) 29 | { 30 | var name = d.Value.Config.Info.GetSoName(out var overrodenName); 31 | if (name != null) 32 | { 33 | var path = Path.Combine(config.DependenciesDir, name); 34 | if (File.Exists(path)) 35 | { 36 | // If it's overroden, do nothing, it gets deleted by itself. 37 | // Actually, if it's an overriden name, we should check qpm.shared.json 38 | // If we find that we already have a match, we don't need to remove it 39 | if (sharedConfig != null) 40 | { 41 | var found = sharedConfig.RestoredDependencies.Find(rdp => rdp.Dependency.Id.Equals(d.Value.Config.Info.Id, StringComparison.OrdinalIgnoreCase) && rdp.Version == d.Value.Config.Info.Version); 42 | if (found != null) 43 | { 44 | // If we have a match of the same version, we are chillin 45 | // Otherwise, we need to delete this. 46 | existingDeps[path] = true; 47 | } 48 | } 49 | // If it isn't, set the flag to true 50 | if (existingDeps.ContainsKey(path)) 51 | { 52 | existingDeps[path] = true; 53 | } 54 | } 55 | } 56 | } 57 | foreach (var p in existingDeps) 58 | { 59 | // Delete each pair with a false value 60 | if (!p.Value) 61 | File.Delete(p.Key); 62 | } 63 | await Program.RestoreHandler.Restore().ConfigureAwait(false); 64 | // Write Android.mk 65 | Utils.WriteSuccess(); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /QPM/Commands/SupportedPropertiesCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | using System.Text.Json; 8 | using System.Threading.Tasks; 9 | 10 | namespace QPM.Commands 11 | { 12 | [Command("properties-list", Description = "List all properties that are currently supported by QPM")] 13 | internal class SupportedPropertiesCommand 14 | { 15 | [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] 16 | internal sealed class PropertyAttribute : Attribute 17 | { 18 | public string[] SupportedTypes { get; set; } 19 | public string HelpText { get; set; } 20 | public Type Type { get; set; } = typeof(string); 21 | 22 | public PropertyAttribute(string helpText, params string[] types) 23 | { 24 | HelpText = helpText; 25 | SupportedTypes = types; 26 | } 27 | } 28 | 29 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] 30 | internal sealed class PropertyCollectionAttribute : Attribute 31 | { 32 | } 33 | 34 | [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] 35 | internal sealed class PropertyDescriptorAttribute : Attribute 36 | { 37 | public string HelpText { get; set; } 38 | public bool Required { get; set; } = false; 39 | public PropertyDescriptorAttribute(string help) 40 | { 41 | HelpText = help; 42 | } 43 | } 44 | 45 | [PropertyCollection] 46 | internal class StyleProperty 47 | { 48 | [PropertyDescriptor("The name of the style.", Required = true)] 49 | public string? Name { get; set; } 50 | [PropertyDescriptor("The release downloadable so link for this style. Must exist if being used as release.", Required = false)] 51 | public string? SoLink { get; set; } 52 | [PropertyDescriptor("The debug downloadable so link for this style. Must exist if being used as debug.", Required = false)] 53 | public string? DebugSoLink { get; set; } 54 | } 55 | 56 | [PropertyCollection] 57 | internal class CompileOptionsProperty 58 | { 59 | [PropertyDescriptor("Additional include paths to add, relative to the extern directory.")] 60 | public string[] IncludePaths { get; set; } = Array.Empty(); 61 | [PropertyDescriptor("Additional system include paths to add, relative to the extern directory.")] 62 | public string[] SystemIncludes { get; set; } = Array.Empty(); 63 | [PropertyDescriptor("Additional C++ features to add.")] 64 | public string[] CppFeatures { get; set; } = Array.Empty(); 65 | [PropertyDescriptor("Additional C++ flags to add.")] 66 | public string[] CppFlags { get; set; } = Array.Empty(); 67 | [PropertyDescriptor("Additional C flags to add.")] 68 | public string[] CFlags { get; set; } = Array.Empty(); 69 | } 70 | 71 | [Property("Branch name of a Github repo. Only used when a valid github url is provided", "package", "dependency")] 72 | public const string BranchName = "branchName"; 73 | 74 | [Property("Specify that this package is headers only and does not contain a .so or .a file", "package", Type = typeof(bool))] 75 | public const string HeadersOnly = "headersOnly"; 76 | 77 | [Property("Specify that this package is static linking", "package", Type = typeof(bool))] 78 | public const string StaticLinking = "staticLinking"; 79 | 80 | [Property("Specify the download link for a release .so or .a file", "package")] 81 | public const string ReleaseSoLink = "soLink"; 82 | 83 | [Property("Specify any additional files to be downloaded", "package", "dependency", Type = typeof(string[]))] 84 | public const string AdditionalFiles = "extraFiles"; 85 | 86 | [Property("Copy a dependency from a location that is local to this root path instead of from a remote url", "dependency")] 87 | public const string LocalPath = "localPath"; 88 | 89 | [Property("Specify the download link for a debug .so or .a files (usually from the obj folder)", "package")] 90 | public const string DebugSoLink = "debugSoLink"; 91 | 92 | [Property("Specify if a dependency should download a release .so or .a file. Defaults to false", "dependency", Type = typeof(bool))] 93 | public const string UseReleaseSo = "useRelease"; 94 | 95 | [Property("Override the downloaded .so or .a filename with this name instead.", "package")] 96 | public const string OverrideSoName = "overrideSoName"; 97 | 98 | [Property("Provide various download links of differing styles. Styles are appended to module names.", "package", Type = typeof(StyleProperty[]))] 99 | public const string Styles = "styles"; 100 | 101 | [Property("Specify the style to use.", "dependency")] 102 | public const string StyleToUse = "style"; 103 | 104 | [Property("Subfolder for this particular package in the provided repository, relative to root of the repo.", "package")] 105 | public const string Subfolder = "subfolder"; 106 | 107 | [Property("Additional options for compilation and edits to compilation related files.", "package", Type = typeof(CompileOptionsProperty))] 108 | public const string CompileOptions = "compileOptions"; 109 | //[Property("Explicit include paths to add for this particular package to all dependents, relative to workspace root.", "package", Type = "array[string]")] 110 | //public const string IncludePaths = "includePaths"; 111 | 112 | //[Property("Explicit system include paths to add for this particular package to all dependents, relative to workspace root.", "package", Type = "array[string]")] 113 | //public const string SystemIncludes = "systemIncludes"; 114 | 115 | private const string Header = "Supported Additional Properties:"; 116 | 117 | private const int typeIndent = 2; 118 | 119 | private void OnExecute() 120 | { 121 | // Aggregate const fields 122 | var fields = typeof(SupportedPropertiesCommand).GetFields(BindingFlags.Public | BindingFlags.Static); 123 | var sb = new StringBuilder(Header); 124 | sb.AppendLine(); 125 | sb.AppendLine(); 126 | var toWrite = new List(); 127 | foreach (var f in fields) 128 | { 129 | var attr = f.GetCustomAttribute(false); 130 | if (attr is null) 131 | continue; 132 | if (f.GetRawConstantValue() is string val) 133 | { 134 | sb.AppendFormat("- {0} ({1}): {2} - Supported in: {3}", val, attr.Type, attr.HelpText, string.Join(", ", attr.SupportedTypes)); 135 | sb.AppendLine(); 136 | } 137 | if (attr.Type.GetCustomAttribute() is not null) 138 | toWrite.Add(attr.Type); 139 | else if (attr.Type.GetElementType()?.GetCustomAttribute() is not null) 140 | toWrite.Add(attr.Type.GetElementType()!); 141 | } 142 | void WriteType(StringBuilder sb, Type type) 143 | { 144 | sb.Append("Type: "); 145 | sb.AppendLine(type.ToString()); 146 | var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); 147 | foreach (var prop in props) 148 | { 149 | // Indent 150 | for (int i = 0; i < typeIndent; i++) 151 | { 152 | sb.Append(' '); 153 | } 154 | sb.Append("- "); 155 | sb.Append(char.ToLowerInvariant(prop.Name[0])); 156 | var attr = prop.GetCustomAttribute(); 157 | if (attr is not null) 158 | { 159 | sb.AppendFormat("{0} - {1} ({2}): {3}", prop.Name[1..], attr.Required ? "REQUIRED" : "OPTIONAL", prop.PropertyType, attr.HelpText); 160 | } else 161 | { 162 | sb.AppendFormat("{0} ({1})", prop.Name[1..], prop.PropertyType); 163 | } 164 | sb.AppendLine(); 165 | if (prop.PropertyType.GetCustomAttribute() is not null) 166 | toWrite.Add(prop.PropertyType); 167 | else if (prop.PropertyType.GetElementType()?.GetCustomAttribute() is not null) 168 | toWrite.Add(prop.PropertyType.GetElementType()!); 169 | } 170 | } 171 | for (int i = 0; i < toWrite.Count; i++) 172 | { 173 | // If the type we are has an attribute attached (or the element type) then we need to perform a type writeout 174 | WriteType(sb, toWrite[i]); 175 | } 176 | Console.WriteLine(sb.ToString()); 177 | } 178 | 179 | private static readonly JsonSerializerOptions options = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, AllowTrailingCommas = true }; 180 | 181 | internal static T? Convert(JsonElement elem) => JsonSerializer.Deserialize(elem.GetRawText(), options); 182 | } 183 | } -------------------------------------------------------------------------------- /QPM/Commands/VersionCommand.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace QPM.Commands 10 | { 11 | [Command("version", Description = "List the current version of QPM")] 12 | internal class VersionCommand 13 | { 14 | private void OnExecute() => Console.WriteLine("Quest Package Manager (QPM) Version: v" + Assembly.GetExecutingAssembly().GetName().Version!.ToString(3)); 15 | } 16 | } -------------------------------------------------------------------------------- /QPM/Data/AndroidMk.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace QPM.Data 8 | { 9 | public class AndroidMk 10 | { 11 | public List Prefix { get; } = new List(); 12 | public List Modules { get; } = new List(); 13 | public List Suffix { get; } = new List(); 14 | } 15 | } -------------------------------------------------------------------------------- /QPM/Data/BmbfMod.cs: -------------------------------------------------------------------------------- 1 | using QuestPackageManager.Data; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Text.Json.Serialization; 7 | using System.Threading.Tasks; 8 | 9 | namespace QPM.Data 10 | { 11 | public class BmbfMod 12 | { 13 | [JsonPropertyName("id")] 14 | public string Id { get; set; } 15 | 16 | [JsonPropertyName("name")] 17 | public string Name { get; set; } 18 | 19 | [JsonPropertyName("version")] 20 | [JsonConverter(typeof(SemVerConverter))] 21 | public SemVer.Version Version { get; set; } 22 | 23 | [JsonExtensionData] 24 | public Dictionary ExtensionData { get; set; } 25 | 26 | public void UpdateId(string id) 27 | { 28 | if (!string.IsNullOrEmpty(id)) 29 | Id = id; 30 | } 31 | 32 | public void UpdateName(string name) 33 | { 34 | if (!string.IsNullOrEmpty(name)) 35 | Name = name; 36 | } 37 | 38 | public void UpdateVersion(SemVer.Version version) 39 | { 40 | if (version != null) 41 | Version = version; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /QPM/Data/CppProperties.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.Json.Serialization; 6 | using System.Threading.Tasks; 7 | 8 | namespace QPM.Data 9 | { 10 | public class Configuration 11 | { 12 | [JsonPropertyName("defines")] 13 | public List Defines { get; set; } 14 | 15 | [JsonPropertyName("includePath")] 16 | public List IncludePath { get; set; } = new List(); 17 | 18 | [JsonExtensionData] 19 | public Dictionary ExtensionData { get; set; } 20 | } 21 | 22 | public class CppProperties 23 | { 24 | [JsonPropertyName("configurations")] 25 | public List Configurations { get; set; } 26 | 27 | [JsonExtensionData] 28 | public Dictionary ExtensionData { get; set; } 29 | 30 | private const string IdDefine = "ID"; 31 | private const string VersionDefine = "VERSION"; 32 | 33 | public CppProperties() 34 | { 35 | } 36 | 37 | public void AddIncludePath(string toAdd) 38 | { 39 | var config = Configurations.FirstOrDefault(); 40 | if (config is null) 41 | return; 42 | var existing = config.IncludePath.FindIndex(s => s == toAdd); 43 | if (existing == -1) 44 | config.IncludePath.Add(toAdd); 45 | } 46 | 47 | public void UpdateId(string id) 48 | { 49 | var config = Configurations.FirstOrDefault(); 50 | if (config is null) 51 | return; 52 | var idDef = config.Defines.FindIndex(d => d.StartsWith(IdDefine)); 53 | var toAdd = IdDefine + $"=\"{id}\""; 54 | if (idDef != -1) 55 | config.Defines[idDef] = toAdd; 56 | else 57 | config.Defines.Add(toAdd); 58 | } 59 | 60 | public void UpdateVersion(SemVer.Version version) 61 | { 62 | var config = Configurations.FirstOrDefault(); 63 | if (config is null) 64 | return; 65 | var versionDef = config.Defines.FindIndex(d => d.StartsWith(VersionDefine)); 66 | var toAdd = VersionDefine + $"=\"{version}\""; 67 | if (versionDef != -1) 68 | config.Defines[versionDef] = toAdd; 69 | else 70 | config.Defines.Add(toAdd); 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /QPM/Data/Module.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace QPM.Data 8 | { 9 | public class Module 10 | { 11 | public List PrefixLines { get; set; } = new List(); 12 | public string? Id { get; set; } 13 | public List Src { get; set; } = new List(); 14 | public List ExportIncludes { get; set; } = new(); 15 | public List StaticLibs { get; set; } = new List(); 16 | public List SharedLibs { get; set; } = new List(); 17 | public List LdLibs { get; set; } = new List(); 18 | public List CFlags { get; set; } = new List(); 19 | public List ExportCFlags { get; set; } = new List(); 20 | public List ExportCppFlags { get; set; } = new(); 21 | public List CppFlags { get; set; } = new List(); 22 | public List CIncludes { get; set; } = new List(); 23 | public List CppFeatures { get; set; } = new List(); 24 | public List ExtraLines { get; set; } = new List(); 25 | public string? BuildLine { get; set; } 26 | 27 | public void AddDefine(string id, string value) 28 | { 29 | // TODO: Support more types of -D 30 | var idIndex = CFlags.FindIndex(c => c.StartsWith("-D" + id) || c.StartsWith("-D'" + id)); 31 | var s = $"-D{id}='\"{value}\"'"; 32 | if (idIndex != -1) 33 | CFlags[idIndex] = s; 34 | else 35 | CFlags.Add(s); 36 | } 37 | 38 | public void AddIncludePath(string includePath) 39 | { 40 | var include = "-I'" + includePath + "'"; 41 | if (!CFlags.Contains(include)) 42 | CFlags.Add(include); 43 | } 44 | 45 | public void AddSystemInclude(string includePath, bool export = false) 46 | { 47 | var include = "-isystem'" + includePath + "'"; 48 | var lst = export ? ExportCFlags : CFlags; 49 | if (!lst.Contains(include)) 50 | lst.Add(include); 51 | } 52 | 53 | public void AddExportCppFeature(string feature) 54 | { 55 | var f = "-f" + feature; 56 | if (!ExportCppFlags.Contains(f)) 57 | ExportCppFlags.Add(f); 58 | } 59 | 60 | public void EnsureIdIs(string id, SemVer.Version version) => Id = id + "_" + version.ToString().Replace('.', '_'); 61 | 62 | public void RemoveLibrary(string id) 63 | { 64 | SharedLibs.RemoveAll(l => l.Equals(id, StringComparison.OrdinalIgnoreCase)); 65 | StaticLibs.RemoveAll(l => l.Equals(id, StringComparison.OrdinalIgnoreCase)); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /QPM/Data/QPMConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | 5 | namespace QPM.Data 6 | { 7 | /// 8 | /// A type that holds the configuration for QPM. 9 | /// Loaded from QPM executable directory on startup. 10 | /// 11 | public class QPMConfig 12 | { 13 | public double DependencyTimeoutSeconds { get; set; } = 300; 14 | public string CachePath { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Assembly.GetExecutingAssembly().GetName().Name + "_Temp"); 15 | public bool UseSymlinks { get; set; } = true; 16 | } 17 | } -------------------------------------------------------------------------------- /QPM/Program.cs: -------------------------------------------------------------------------------- 1 | using McMaster.Extensions.CommandLineUtils; 2 | using Microsoft.Extensions.Configuration; 3 | using QPM.Commands; 4 | using QPM.Data; 5 | using QPM.Providers; 6 | using QuestPackageManager; 7 | using QuestPackageManager.Data; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.IO; 11 | using System.Linq; 12 | using System.Net; 13 | using System.Reflection; 14 | using System.Runtime.CompilerServices; 15 | using System.Runtime.Versioning; 16 | using System.Text.Json; 17 | using System.Threading.Tasks; 18 | 19 | namespace QPM 20 | { 21 | [Command("qpm", Description = "Quest package manager")] 22 | [Subcommand(typeof(PackageCommand), 23 | typeof(DependencyCommand), 24 | typeof(RestoreCommand), 25 | typeof(CollectCommand), 26 | typeof(CollapseCommand), 27 | typeof(PublishCommand), 28 | typeof(SupportedPropertiesCommand), 29 | typeof(CacheCommand), 30 | typeof(ClearCommand), 31 | typeof(VersionCommand), 32 | typeof(ConfigCommand) 33 | )] 34 | internal class Program 35 | { 36 | internal const string PackageFileName = "qpm.json"; 37 | internal const string LocalFileName = "qpm.shared.json"; 38 | internal static DependencyHandler DependencyHandler { get; private set; } 39 | internal static PackageHandler PackageHandler { get; private set; } 40 | internal static RestoreHandler RestoreHandler { get; private set; } 41 | internal static PublishHandler PublishHandler { get; private set; } 42 | internal static QPMConfig Config { get; private set; } = new QPMConfig(); 43 | 44 | internal static IConfigProvider configProvider; 45 | private static IDependencyResolver resolver; 46 | private static CppPropertiesProvider propertiesProvider; 47 | private static BmbfModProvider bmbfmodProvider; 48 | private static AndroidMkProvider androidMkProvider; 49 | private static QPMApi api; 50 | 51 | private static readonly string configPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "appsettings.json"); 52 | 53 | // TODO: Local config should be DIFFERENT than global config. 54 | // Both should also be accessible, as in, they should not share the same instance. 55 | private const string qpmLocalConfig = "qpm.config.json"; 56 | 57 | internal static bool isLocal = false; 58 | private static readonly JsonSerializerOptions options = new() { WriteIndented = true }; 59 | 60 | private static void LoadConfig() 61 | { 62 | try 63 | { 64 | if (File.Exists(qpmLocalConfig)) 65 | { 66 | // Load local config if it exists 67 | Console.WriteLine($"Found local config at: {qpmLocalConfig}"); 68 | var tmp = JsonSerializer.Deserialize(File.ReadAllText(qpmLocalConfig)); 69 | if (tmp is not null) 70 | Config = tmp; 71 | isLocal = true; 72 | return; 73 | } 74 | if (!File.Exists(configPath)) 75 | { 76 | Console.WriteLine($"Creating config at: {configPath}"); 77 | // Write default settings always 78 | File.WriteAllText(configPath, JsonSerializer.Serialize(Config, options)); 79 | } 80 | else 81 | { 82 | Console.WriteLine($"Found config at: {configPath}"); 83 | var tmp = JsonSerializer.Deserialize(File.ReadAllText(configPath)); 84 | if (tmp is not null) 85 | Config = tmp; 86 | } 87 | } 88 | catch 89 | { 90 | // If we can't access the config for any reason, whatever dude. 91 | Console.WriteLine($"Configuration could not be loaded!"); 92 | } 93 | } 94 | 95 | internal static async Task SaveConfig() 96 | { 97 | if (!isLocal) 98 | { 99 | await File.WriteAllTextAsync(configPath, JsonSerializer.Serialize(Config, options)).ConfigureAwait(false); 100 | } 101 | else 102 | { 103 | await File.WriteAllTextAsync(qpmLocalConfig, JsonSerializer.Serialize(Config, options)).ConfigureAwait(false); 104 | } 105 | } 106 | 107 | public static int Main(string[] args) 108 | { 109 | LoadConfig(); 110 | // Create config provider 111 | configProvider = new LocalConfigProvider(Environment.CurrentDirectory, PackageFileName, LocalFileName); 112 | api = new QPMApi(configProvider, Config.DependencyTimeoutSeconds); 113 | androidMkProvider = new AndroidMkProvider(Path.Combine(Environment.CurrentDirectory, "Android.mk")); 114 | resolver = new RemoteQPMDependencyResolver(api, androidMkProvider); 115 | propertiesProvider = new CppPropertiesProvider(Path.Combine(Environment.CurrentDirectory, ".vscode", "c_cpp_properties.json")); 116 | bmbfmodProvider = new BmbfModProvider(Path.Combine(Environment.CurrentDirectory, "bmbfmod.json")); 117 | // Create handlers 118 | PackageHandler = new PackageHandler(configProvider); 119 | DependencyHandler = new DependencyHandler(configProvider); 120 | RestoreHandler = new RestoreHandler(configProvider, resolver); 121 | PublishHandler = new PublishHandler(configProvider, api); 122 | // Register callbacks 123 | PackageHandler.OnPackageCreated += PackageHandler_OnPackageCreated; 124 | PackageHandler.OnIdChanged += PackageHandler_OnIdChanged; 125 | PackageHandler.OnVersionChanged += PackageHandler_OnVersionChanged; 126 | PackageHandler.OnNameChanged += PackageHandler_OnNameChanged; 127 | DependencyHandler.OnDependencyRemoved += DependencyHandler_OnDependencyRemoved; 128 | // TODO: AKLJSHFJKGHDKJ 129 | RestoreHandler.OnRestore += (resolver as RemoteQPMDependencyResolver)!.OnRestore; 130 | 131 | // Create configuration/load it if it exists 132 | 133 | try 134 | { 135 | return CommandLineApplication.Execute(args); 136 | } 137 | catch (Exception e) 138 | { 139 | Console.WriteLine(e.Message); 140 | Console.WriteLine(); 141 | Console.WriteLine(e); 142 | Utils.WriteFail(); 143 | } 144 | return -1; 145 | } 146 | 147 | private static void DependencyHandler_OnDependencyRemoved(DependencyHandler handler, Dependency dependency) 148 | { 149 | // Handle deletion of the dependency in question 150 | // That would include removing it from the config.SharedDir, removing it from Android.mk, removing it from bmbfmod.json 151 | if (dependency.Id is null) 152 | throw new DependencyException("Cannot remove a dependency that does not have a valid Id!"); 153 | var mk = androidMkProvider.GetFile(); 154 | if (mk != null) 155 | { 156 | // Remove module, don't remove null ids, though they shouldn't exist. 157 | mk.Modules.RemoveAll(m => m.Id?.Equals(dependency.Id, StringComparison.OrdinalIgnoreCase) ?? false); 158 | // Main module, remove shared library 159 | var module = mk.Modules.LastOrDefault(); 160 | if (module != null) 161 | { 162 | module.RemoveLibrary(dependency.Id); 163 | } 164 | } 165 | // TODO: Remove from bmbfmod.json 166 | var cfg = configProvider.GetConfig(); 167 | // If we have it in our met dependencies 168 | if (cfg != null) 169 | resolver.RemoveDependency(cfg, dependency); 170 | } 171 | 172 | private static void PackageHandler_OnNameChanged(PackageHandler handler, string name) 173 | { 174 | // Perform bmbfmod.json edits to name 175 | var mod = bmbfmodProvider.GetMod(); 176 | if (mod != null) 177 | { 178 | mod.UpdateName(name); 179 | bmbfmodProvider.SerializeMod(mod); 180 | } 181 | } 182 | 183 | private static void PackageHandler_OnVersionChanged(PackageHandler handler, SemVer.Version version) 184 | { 185 | // Perform Android.mk, c_cpp_properties.json, bmbfmod.json edits to version 186 | var props = propertiesProvider.GetProperties(); 187 | if (props != null) 188 | { 189 | props.UpdateVersion(version); 190 | propertiesProvider.SerializeProperties(props); 191 | } 192 | var mod = bmbfmodProvider.GetMod(); 193 | if (mod != null) 194 | { 195 | mod.UpdateVersion(version); 196 | bmbfmodProvider.SerializeMod(mod); 197 | } 198 | var conf = configProvider.GetConfig(); 199 | if (conf is null) 200 | throw new ConfigException("Config is null!"); 201 | if (conf.Info is null) 202 | throw new ConfigException("Config info is null!"); 203 | if (conf.Info.Id is null) 204 | throw new ConfigException("Config ID is null!"); 205 | bool overrodeName = conf.Info.AdditionalData.TryGetValue(SupportedPropertiesCommand.OverrideSoName, out var overridenName); 206 | var mk = androidMkProvider.GetFile(); 207 | if (mk != null) 208 | { 209 | var module = mk.Modules.LastOrDefault(); 210 | if (module != null) 211 | { 212 | module.AddDefine("VERSION", version.ToString()); 213 | if (overrodeName) 214 | module.Id = overridenName.GetString()!.ReplaceFirst("lib", "").ReplaceLast(".so", "").ReplaceLast(".a", ""); 215 | else 216 | module.EnsureIdIs(conf.Info.Id, version); 217 | androidMkProvider.SerializeFile(mk); 218 | } 219 | } 220 | } 221 | 222 | private static void PackageHandler_OnPackageCreated(PackageHandler handler, PackageInfo info) 223 | { 224 | // Perform Android.mk, c_cpp_properties.json, bmbfmod.json edits to ID, version, name, other info (?) 225 | var cfg = configProvider.GetConfig(); 226 | string depDir; 227 | string shared; 228 | if (cfg != null) 229 | { 230 | shared = cfg.SharedDir; 231 | depDir = cfg.DependenciesDir; 232 | var actualShared = Path.Combine(Environment.CurrentDirectory, cfg.SharedDir); 233 | var actualDeps = Path.Combine(Environment.CurrentDirectory, cfg.DependenciesDir); 234 | if (!Directory.Exists(actualShared)) 235 | Directory.CreateDirectory(actualShared); 236 | if (!Directory.Exists(actualDeps)) 237 | Directory.CreateDirectory(actualDeps); 238 | } 239 | else 240 | { 241 | throw new InvalidOperationException("Config that has just been created cannot possibly be null!"); 242 | } 243 | var props = propertiesProvider.GetProperties(); 244 | if (props != null) 245 | { 246 | props.UpdateVersion(info.Version); 247 | props.UpdateId(info.Id); 248 | if (cfg != null) 249 | { 250 | props.AddIncludePath("${workspaceFolder}/" + shared); 251 | props.AddIncludePath("${workspaceFolder}/" + depDir); 252 | } 253 | propertiesProvider.SerializeProperties(props); 254 | } 255 | var mod = bmbfmodProvider.GetMod(); 256 | if (mod != null) 257 | { 258 | mod.UpdateVersion(info.Version); 259 | mod.UpdateId(info.Id); 260 | bmbfmodProvider.SerializeMod(mod); 261 | } 262 | var mk = androidMkProvider.GetFile(); 263 | if (mk != null) 264 | { 265 | var module = mk.Modules.LastOrDefault(); 266 | if (module != null) 267 | { 268 | module.AddDefine("ID", info.Id); 269 | module.AddDefine("VERSION", info.Version.ToString()); 270 | // Also add includePath for myConfig 271 | if (cfg != null) 272 | { 273 | if (cfg.Info!.AdditionalData.TryGetValue(SupportedPropertiesCommand.OverrideSoName, out var overridenName)) 274 | { 275 | module.Id = overridenName.GetString()!.ReplaceFirst("lib", "").ReplaceLast(".so", "").ReplaceLast(".a", ""); 276 | } 277 | else 278 | module.EnsureIdIs(info.Id, info.Version); 279 | module.AddIncludePath("./" + shared); 280 | module.AddIncludePath("./" + depDir); 281 | } 282 | androidMkProvider.SerializeFile(mk); 283 | } 284 | } 285 | } 286 | 287 | private static void PackageHandler_OnIdChanged(PackageHandler handler, string id) 288 | { 289 | // Perform Android.mk, c_cpp_properties.json, bmbfmod.json edits to ID 290 | var props = propertiesProvider.GetProperties(); 291 | if (props != null) 292 | { 293 | props.UpdateId(id); 294 | propertiesProvider.SerializeProperties(props); 295 | } 296 | var mod = bmbfmodProvider.GetMod(); 297 | if (mod != null) 298 | { 299 | mod.UpdateId(id); 300 | bmbfmodProvider.SerializeMod(mod); 301 | } 302 | var conf = configProvider.GetConfig(); 303 | if (conf is null) 304 | throw new ConfigException("Config is null!"); 305 | if (conf.Info is null) 306 | throw new ConfigException("Config info is null!"); 307 | if (conf.Info.Version is null) 308 | throw new ConfigException("Config ID is null!"); 309 | var mk = androidMkProvider.GetFile(); 310 | if (mk != null) 311 | { 312 | var module = mk.Modules.LastOrDefault(); 313 | if (module != null) 314 | { 315 | module.AddDefine("ID", id); 316 | if (conf.Info.AdditionalData.TryGetValue(SupportedPropertiesCommand.OverrideSoName, out var overridenName)) 317 | module.Id = overridenName.GetString()!.Replace("lib", "").Replace(".so", "").ReplaceLast(".a", ""); 318 | else 319 | module.EnsureIdIs(id, conf.Info.Version); 320 | androidMkProvider.SerializeFile(mk); 321 | } 322 | } 323 | } 324 | 325 | private void OnExecute(CommandLineApplication app) => app.ShowHelp(); 326 | } 327 | } -------------------------------------------------------------------------------- /QPM/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "QPM": { 4 | "commandName": "Project", 5 | "commandLineArgs": "publish", 6 | "workingDirectory": "C:\\Users\\Sc2ad\\Desktop\\Code\\BeatSaberMods\\TypePatching" 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /QPM/Providers/AndroidMkProvider.cs: -------------------------------------------------------------------------------- 1 | using QPM.Data; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace QPM.Providers 10 | { 11 | public class AndroidMkProvider 12 | { 13 | private enum Concat 14 | { 15 | None, 16 | Set, 17 | Add 18 | } 19 | 20 | private readonly string path; 21 | 22 | public AndroidMkProvider(string path) 23 | { 24 | this.path = path; 25 | } 26 | 27 | private static string? BreakString(string line, out Concat type) 28 | { 29 | var ind = line.IndexOf('='); 30 | if (ind != -1) 31 | { 32 | type = (line[ind - 1]) switch 33 | { 34 | '+' => Concat.Add, 35 | ':' => Concat.Set, 36 | _ => Concat.None, 37 | }; 38 | return line.Substring(ind + 1).TrimStart(); 39 | } 40 | type = Concat.None; 41 | return null; 42 | } 43 | 44 | private static IEnumerable ParseLine(string line) 45 | { 46 | var lst = new List(); 47 | string temp = string.Empty; 48 | bool wildcard = false; 49 | bool escapedParenth = false; 50 | bool escapedSingle = false; 51 | bool escapedDouble = false; 52 | bool escapeNext = false; 53 | foreach (var c in line) 54 | { 55 | if (escapeNext) 56 | { 57 | escapeNext = false; 58 | temp += c; 59 | continue; 60 | } 61 | if (wildcard && c == '(') 62 | escapedParenth = true; 63 | wildcard = false; 64 | 65 | if (c == '$') 66 | wildcard = true; 67 | else if (c == '\\') 68 | escapeNext = true; 69 | else if (c == '\'') 70 | escapedSingle = !escapedSingle; 71 | else if (c == '\"') 72 | escapedDouble = !escapedDouble; 73 | else if (c == ')') 74 | escapedParenth = false; 75 | else if (c == ' ' && !escapedSingle && !escapedDouble && !escapedParenth) 76 | { 77 | lst.Add(temp); 78 | temp = string.Empty; 79 | continue; 80 | } 81 | temp += c; 82 | } 83 | // Always add at least one 84 | lst.Add(temp); 85 | return lst; 86 | } 87 | 88 | public AndroidMk? GetFile() 89 | { 90 | var mk = new AndroidMk(); 91 | try 92 | { 93 | var lines = File.ReadAllLines(path); 94 | bool inModule = false; 95 | bool firstModuleFound = false; 96 | var module = new Module(); 97 | 98 | foreach (var line in lines) 99 | { 100 | if (!firstModuleFound) 101 | mk.Prefix.Add(line); 102 | else if (!inModule) 103 | module.PrefixLines.Add(line); 104 | else 105 | { 106 | // Check if mod end 107 | if (line.StartsWith("include $(") || line.StartsWith("rwildcard=$") || line.StartsWith("LOCAL_PATH") || line.StartsWith("TARGET_ARCH_ABI")) 108 | { 109 | module.BuildLine = line; 110 | mk.Modules.Add(module); 111 | // Exit module with build statement 112 | inModule = false; 113 | // Create new module to populate prefix for 114 | module = new Module(); 115 | continue; 116 | } 117 | // Parse line 118 | var parsed = BreakString(line, out var type); 119 | if (parsed is null) 120 | // If line can't be parsed, skip 121 | continue; 122 | if (line.StartsWith("LOCAL_MODULE")) 123 | module.Id = parsed; 124 | else if (line.StartsWith("LOCAL_SRC_FILES")) 125 | { 126 | if (type == Concat.Set) 127 | module.Src.Clear(); 128 | module.Src.AddRange(ParseLine(parsed)); 129 | } 130 | else if (line.StartsWith("LOCAL_EXPORT_C_INCLUDES")) 131 | { 132 | if (type == Concat.Set) 133 | module.ExportIncludes.Clear(); 134 | module.ExportIncludes.AddRange(ParseLine(parsed)); 135 | } 136 | else if (line.StartsWith("LOCAL_EXPORT_CFLAGS")) 137 | { 138 | if (type == Concat.Set) 139 | module.ExportCFlags.Clear(); 140 | module.ExportCFlags.AddRange(ParseLine(parsed)); 141 | } 142 | else if (line.StartsWith("LOCAL_EXPORT_CPPFLAGS")) 143 | { 144 | if (type == Concat.Set) 145 | module.ExportCppFlags.Clear(); 146 | module.ExportCppFlags.AddRange(ParseLine(parsed)); 147 | } 148 | else if (line.StartsWith("LOCAL_SHARED_LIBRARIES")) 149 | { 150 | if (type == Concat.Set) 151 | module.SharedLibs.Clear(); 152 | module.SharedLibs.AddRange(ParseLine(parsed)); 153 | } 154 | else if (line.StartsWith("LOCAL_STATIC_LIBRARIES")) 155 | { 156 | if (type == Concat.Set) 157 | module.StaticLibs.Clear(); 158 | module.StaticLibs.AddRange(ParseLine(parsed)); 159 | } 160 | else if (line.StartsWith("LOCAL_LDLIBS")) 161 | { 162 | if (type == Concat.Set) 163 | module.LdLibs.Clear(); 164 | module.LdLibs.AddRange(ParseLine(parsed)); 165 | } 166 | else if (line.StartsWith("LOCAL_CFLAGS")) 167 | { 168 | if (type == Concat.Set) 169 | module.CFlags.Clear(); 170 | module.CFlags.AddRange(ParseLine(parsed)); 171 | } 172 | else if (line.StartsWith("LOCAL_CPPFLAGS")) 173 | { 174 | if (type == Concat.Set) 175 | module.CppFlags.Clear(); 176 | module.CppFlags.AddRange(ParseLine(parsed)); 177 | } 178 | else if (line.StartsWith("LOCAL_C_INCLUDES")) 179 | { 180 | if (type == Concat.Set) 181 | module.CIncludes.Clear(); 182 | module.CIncludes.AddRange(ParseLine(parsed)); 183 | } 184 | else if (line.StartsWith("LOCAL_CPP_FEATURES")) 185 | { 186 | if (type == Concat.Set) 187 | module.CppFeatures.Clear(); 188 | module.CppFeatures.AddRange(ParseLine(parsed)); 189 | } 190 | else 191 | { 192 | module.ExtraLines.Add(line); 193 | } 194 | } 195 | if (line.StartsWith("include $(CLEAR_VARS)")) 196 | { 197 | if (!firstModuleFound) 198 | { 199 | int size = mk.Prefix.Count; 200 | if(size > 0) 201 | { 202 | int index = size - 2; 203 | if (mk.Prefix[index].StartsWith("#")) 204 | { 205 | module.PrefixLines.Add(mk.Prefix[index]); 206 | mk.Prefix.RemoveAt(index); 207 | } 208 | size = mk.Prefix.Count; 209 | index = size - 1; 210 | if (mk.Prefix[index].StartsWith("include $(CLEAR_VARS)")) 211 | { 212 | module.PrefixLines.Add(mk.Prefix[index]); 213 | mk.Prefix.RemoveAt(index); 214 | } 215 | } 216 | } 217 | 218 | // Enter module 219 | inModule = true; 220 | firstModuleFound = true; 221 | } 222 | } 223 | 224 | // Add last portion of module prefix to suffix of mk 225 | mk.Suffix.AddRange(module.PrefixLines); 226 | return mk; 227 | } 228 | catch 229 | { 230 | return null; 231 | } 232 | } 233 | 234 | public void SerializeFile(AndroidMk mk) 235 | { 236 | if (!File.Exists(path + ".backup")) 237 | File.Copy(path, path + ".backup"); 238 | var sb = new StringBuilder(); 239 | foreach (var l in mk.Prefix) 240 | sb.AppendLine(l); 241 | foreach (var m in mk.Modules) 242 | { 243 | foreach (var p in m.PrefixLines) 244 | sb.AppendLine(p); 245 | sb.AppendLine("LOCAL_MODULE := " + m.Id); 246 | if (m.ExportIncludes.Any()) 247 | sb.AppendLine("LOCAL_EXPORT_C_INCLUDES := " + string.Join(' ', m.ExportIncludes)); 248 | if (m.ExportCFlags.Any()) 249 | sb.AppendLine("LOCAL_EXPORT_CFLAGS := " + string.Join(' ', m.ExportCFlags)); 250 | if (m.ExportCppFlags.Any()) 251 | sb.AppendLine("LOCAL_EXPORT_CPPFLAGS := " + string.Join(' ', m.ExportCppFlags)); 252 | if (m.Src.Count == 1) 253 | sb.AppendLine("LOCAL_SRC_FILES := " + m.Src.First()); 254 | else 255 | foreach (var src in m.Src) 256 | sb.AppendLine("LOCAL_SRC_FILES += " + src); 257 | if (m.SharedLibs.Any()) 258 | foreach (var lib in m.SharedLibs) 259 | sb.AppendLine("LOCAL_SHARED_LIBRARIES += " + lib); 260 | if (m.StaticLibs.Any()) 261 | foreach (var lib in m.StaticLibs) 262 | sb.AppendLine("LOCAL_STATIC_LIBRARIES += " + lib); 263 | if (m.LdLibs.Any()) 264 | sb.AppendLine("LOCAL_LDLIBS += " + string.Join(' ', m.LdLibs)); 265 | if (m.CFlags.Any()) 266 | sb.AppendLine("LOCAL_CFLAGS += " + string.Join(' ', m.CFlags)); 267 | if (m.CppFlags.Any()) 268 | sb.AppendLine("LOCAL_CPPFLAGS += " + string.Join(' ', m.CppFlags)); 269 | if (m.CIncludes.Any()) 270 | sb.AppendLine("LOCAL_C_INCLUDES += " + string.Join(' ', m.CIncludes)); 271 | if (m.CppFeatures.Any()) 272 | sb.AppendLine("LOCAL_CPP_FEATURES += " + string.Join(' ', m.CppFeatures)); 273 | // Suffix all unknown lines, hopefully this is good enough 274 | foreach (var e in m.ExtraLines) 275 | sb.AppendLine(e); 276 | sb.AppendLine(m.BuildLine); 277 | } 278 | 279 | foreach (var s in mk.Suffix) 280 | sb.AppendLine(s); 281 | 282 | // Throws 283 | File.WriteAllText(path, sb.ToString()); 284 | } 285 | } 286 | } -------------------------------------------------------------------------------- /QPM/Providers/BmbfModProvider.cs: -------------------------------------------------------------------------------- 1 | using QPM.Data; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Text.Encodings.Web; 8 | using System.Text.Json; 9 | using System.Threading.Tasks; 10 | 11 | namespace QPM.Providers 12 | { 13 | public class BmbfModProvider 14 | { 15 | private readonly string path; 16 | 17 | public BmbfModProvider(string path) 18 | { 19 | this.path = path; 20 | } 21 | 22 | public void SerializeMod(BmbfMod mod) 23 | { 24 | // Throws 25 | var data = JsonSerializer.Serialize(mod, new JsonSerializerOptions 26 | { 27 | WriteIndented = true, 28 | Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping 29 | }); 30 | // Throws 31 | File.WriteAllText(path, data); 32 | } 33 | 34 | public BmbfMod GetMod() 35 | { 36 | try 37 | { 38 | var data = File.ReadAllText(path); 39 | return JsonSerializer.Deserialize(data); 40 | } 41 | catch 42 | { 43 | // On failure to read properties, return null or throw 44 | return null; 45 | } 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /QPM/Providers/CppPropertiesProvider.cs: -------------------------------------------------------------------------------- 1 | using QPM.Data; 2 | using QuestPackageManager.Data; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Text.Encodings.Web; 9 | using System.Text.Json; 10 | using System.Text.Json.Serialization; 11 | using System.Threading.Tasks; 12 | 13 | namespace QPM.Providers 14 | { 15 | public class CppPropertiesProvider 16 | { 17 | private readonly string path; 18 | 19 | public CppPropertiesProvider(string path) 20 | { 21 | this.path = path; 22 | } 23 | 24 | public void SerializeProperties(CppProperties props) 25 | { 26 | // Throws 27 | var data = JsonSerializer.Serialize(props, new JsonSerializerOptions 28 | { 29 | WriteIndented = true, 30 | Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping 31 | }); 32 | // Throws 33 | File.WriteAllText(path, data); 34 | } 35 | 36 | public CppProperties GetProperties() 37 | { 38 | try 39 | { 40 | var data = File.ReadAllText(path); 41 | return JsonSerializer.Deserialize(data); 42 | } 43 | catch 44 | { 45 | // On failure to read properties, return null or throw 46 | return null; 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /QPM/Providers/LocalConfigProvider.cs: -------------------------------------------------------------------------------- 1 | using QuestPackageManager.Data; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Text.Encodings.Web; 8 | using System.Text.Json; 9 | using System.Threading.Tasks; 10 | 11 | namespace QPM.Providers 12 | { 13 | internal class LocalConfigProvider : IConfigProvider 14 | { 15 | private readonly string configPath; 16 | private readonly string localConfigPath; 17 | 18 | private Config config; 19 | private SharedConfig localConfig; 20 | private bool configGotten; 21 | private bool localConfigGotten; 22 | 23 | private JsonSerializerOptions options; 24 | 25 | public LocalConfigProvider(string dir, string configFileName, string localFileName) 26 | { 27 | configPath = Path.Combine(dir, configFileName); 28 | localConfigPath = Path.Combine(dir, localFileName); 29 | options = new JsonSerializerOptions 30 | { 31 | WriteIndented = true, 32 | PropertyNameCaseInsensitive = true, 33 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, 34 | Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping 35 | }; 36 | } 37 | 38 | public string ToString(SharedConfig config) 39 | { 40 | try 41 | { 42 | return JsonSerializer.Serialize(config, options); 43 | } 44 | catch 45 | { 46 | return null; 47 | } 48 | } 49 | 50 | public SharedConfig From(string data) 51 | { 52 | try 53 | { 54 | return JsonSerializer.Deserialize(data, options); 55 | } 56 | catch 57 | { 58 | return null; 59 | } 60 | } 61 | 62 | public void Commit() 63 | { 64 | if (config is null && localConfig is null) 65 | throw new InvalidOperationException("Cannot commit config or localConfig when both are null!"); 66 | if (config != null) 67 | { 68 | var str = JsonSerializer.Serialize(config, options); 69 | File.WriteAllText(configPath, str); 70 | } 71 | if (localConfig != null) 72 | { 73 | var str = JsonSerializer.Serialize(localConfig, options); 74 | File.WriteAllText(localConfigPath, str); 75 | } 76 | } 77 | 78 | public SharedConfig GetSharedConfig(bool createOnFail = false) 79 | { 80 | if (localConfigGotten) 81 | return localConfig; 82 | // We only set this flag once we create it. This basically allows us to continue checking to see if it exists over multiple calls. 83 | localConfig = null; 84 | if (!File.Exists(localConfigPath)) 85 | { 86 | if (createOnFail) 87 | { 88 | // localConfig has a reference to config 89 | var config = GetConfig(); 90 | if (config is null) 91 | return localConfig; 92 | localConfig = new SharedConfig { Config = config }; 93 | Console.WriteLine("Creating new local config at: " + localConfigPath); 94 | // Commit the created config when we explicitly want to create on failure 95 | localConfigGotten = true; 96 | Commit(); 97 | } 98 | } 99 | else 100 | { 101 | // These will throw as needed to the caller on failure 102 | // TODO: If we can solve the issue by recreating the JSON, we can try that here 103 | var json = File.ReadAllText(localConfigPath); 104 | localConfig = JsonSerializer.Deserialize(json, options); 105 | localConfigGotten = true; 106 | } 107 | return localConfig; 108 | } 109 | 110 | public Config GetConfig(bool createOnFail = false) 111 | { 112 | if (configGotten) 113 | return config; 114 | // We only set this flag once we create it. This basically allows us to continue checking to see if it exists over multiple calls. 115 | config = null; 116 | if (!File.Exists(configPath)) 117 | { 118 | if (createOnFail) 119 | { 120 | config = new Config(); 121 | Console.WriteLine("Creating new config at: " + configPath); 122 | // Commit the created config when we explicitly want to create on failure 123 | Commit(); 124 | configGotten = true; 125 | } 126 | } 127 | else 128 | { 129 | // These will throw as needed to the caller on failure 130 | // TODO: If we can solve the issue by recreating the JSON, we can try that here 131 | var json = File.ReadAllText(configPath); 132 | config = JsonSerializer.Deserialize(json, options); 133 | configGotten = true; 134 | } 135 | return config; 136 | } 137 | } 138 | } -------------------------------------------------------------------------------- /QPM/PublishHandler.cs: -------------------------------------------------------------------------------- 1 | using QPM.Commands; 2 | using QuestPackageManager; 3 | using QuestPackageManager.Data; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Net.Http; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace QPM 12 | { 13 | public class PublishHandler 14 | { 15 | private readonly IConfigProvider configProvider; 16 | private readonly QPMApi api; 17 | 18 | public PublishHandler(IConfigProvider configProvider, QPMApi api) 19 | { 20 | this.configProvider = configProvider; 21 | this.api = api; 22 | } 23 | 24 | public async Task Publish() 25 | { 26 | // Ensure the config is valid 27 | var sharedConfig = configProvider.GetSharedConfig(); 28 | if (sharedConfig is null) 29 | throw new ConfigException("Config does not exist!"); 30 | 31 | // All ids in config.Dependencies must be covered in localConfig.IncludedDependencies 32 | if (sharedConfig.Config.Dependencies.Any()) 33 | { 34 | foreach (var d in sharedConfig.Config.Dependencies) 35 | { 36 | if (!sharedConfig.RestoredDependencies.Exists(p => p.Dependency!.Id.Equals(d.Id!, StringComparison.OrdinalIgnoreCase) && d.VersionRange.IsSatisfied(p.Version))) 37 | throw new DependencyException($"Not all dependencies are restored or of correct versions! Restore before attempting to publish! Missing or mismatch dependency: {d.Id} with range: {d.VersionRange}"); 38 | } 39 | } 40 | // My shared folder should have includes that don't use .. 41 | // My config should have both a Url and a soUrl 42 | if (sharedConfig.Config.Info.Url is null) 43 | throw new DependencyException("Config url does not exist!"); 44 | if (!sharedConfig.Config.Info.AdditionalData.ContainsKey(SupportedPropertiesCommand.ReleaseSoLink) && (!sharedConfig.Config.Info.AdditionalData.TryGetValue(SupportedPropertiesCommand.HeadersOnly, out var header) || !header.GetBoolean())) 45 | throw new DependencyException($"Config {SupportedPropertiesCommand.ReleaseSoLink} does not exist! Try using {SupportedPropertiesCommand.HeadersOnly} if you do not need a .so file. See 'properties-list' for more info"); 46 | 47 | // Push it to the server 48 | return await api.Push(sharedConfig).ConfigureAwait(false); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /QPM/QPM.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | AnyCPU;x64 7 | enable 8 | 0.3.2 9 | 0.3.2.0 10 | 0.3.2.0 11 | Quest Package Manager 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /QPM/QPMApi.cs: -------------------------------------------------------------------------------- 1 | using QuestPackageManager.Data; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Net.Http; 7 | using System.Net.Http.Headers; 8 | using System.Reflection; 9 | using System.Text; 10 | using System.Text.Json; 11 | using System.Text.Json.Serialization; 12 | using System.Threading.Tasks; 13 | 14 | namespace QPM 15 | { 16 | public class ModPair 17 | { 18 | [JsonPropertyName("id")] 19 | public string Id { get; set; } 20 | 21 | [JsonPropertyName("version")] 22 | [JsonConverter(typeof(SemVerConverter))] 23 | public SemVer.Version Version { get; set; } 24 | } 25 | 26 | public sealed class QPMApi 27 | { 28 | private readonly IConfigProvider configProvider; 29 | private const string ApiUrl = "https://qpackages.com"; 30 | private const string AuthorizationHeader = "not that i can come up with"; 31 | 32 | private readonly HttpClient client; 33 | 34 | public QPMApi(IConfigProvider configProvider, double secondsTimeout) 35 | { 36 | this.configProvider = configProvider; 37 | client = new HttpClient 38 | { 39 | BaseAddress = new Uri(ApiUrl), 40 | Timeout = TimeSpan.FromSeconds(secondsTimeout) 41 | }; 42 | client.DefaultRequestHeaders.Add("User-Agent", "QPM_" + Assembly.GetCallingAssembly().GetName().Version?.ToString()); 43 | } 44 | 45 | public async Task?> GetAllPackages() 46 | { 47 | var s = await client.GetStringAsync("/").ConfigureAwait(false); 48 | return JsonSerializer.Deserialize>(s); 49 | } 50 | 51 | public async Task?> GetAll(string id, uint limit = 0) 52 | { 53 | if (string.IsNullOrEmpty(id)) 54 | return null; 55 | if (limit == 1) 56 | limit = 0; 57 | var s = await client.GetStringAsync($"/{id}/?req=*&limit={limit}").ConfigureAwait(false); 58 | return JsonSerializer.Deserialize>(s); 59 | } 60 | 61 | public async Task GetLatest(string id, SemVer.Range? range = null) 62 | { 63 | if (range is null) 64 | range = new SemVer.Range("*"); 65 | if (string.IsNullOrEmpty(id)) 66 | return null; 67 | // We need to perform a double check to make sure we format this string properly for the backend. 68 | // It's horrible and sad, but it must be done. 69 | 70 | var rangeStr = range.ToString(); 71 | var ind = rangeStr.IndexOf('<'); 72 | if (ind > 1) 73 | { 74 | rangeStr = rangeStr.Substring(0, ind) + "," + rangeStr[ind..]; 75 | } 76 | else 77 | { 78 | ind = rangeStr.IndexOf('>'); 79 | if (ind > 1) 80 | { 81 | rangeStr = rangeStr.Substring(0, ind) + "," + rangeStr[ind..]; 82 | } 83 | } 84 | var s = await client.GetStringAsync($"/{id}?req={rangeStr}").ConfigureAwait(false); 85 | return JsonSerializer.Deserialize(s); 86 | } 87 | 88 | public async Task GetLatest(Dependency d, SemVer.Version? specific = null) => specific != null ? await GetLatest(d.Id!, new SemVer.Range("=" + specific)).ConfigureAwait(false) : await GetLatest(d.Id!, d.VersionRange).ConfigureAwait(false); 89 | 90 | public async Task GetLatestConfig(Dependency d, SemVer.Version? specific = null) 91 | { 92 | var pair = await GetLatest(d, specific).ConfigureAwait(false); 93 | if (pair is null) 94 | return null; 95 | return await GetConfig(pair.Id, pair.Version).ConfigureAwait(false); 96 | } 97 | 98 | public async Task GetConfig(string id, SemVer.Version version) 99 | { 100 | if (string.IsNullOrEmpty(id)) 101 | return null; 102 | if (version is null) 103 | return null; 104 | var s = await client.GetStringAsync($"/{id}/{version}").ConfigureAwait(false); 105 | return configProvider.From(s); 106 | } 107 | 108 | public async Task Push(SharedConfig config) 109 | { 110 | if (config is null) 111 | throw new ArgumentNullException(nameof(config)); 112 | // We don't perform any validity here, simply ship it away 113 | var s = configProvider.ToString(config); 114 | var request = new HttpRequestMessage(HttpMethod.Post, $"/{config.Config!.Info!.Id}/{config.Config.Info.Version}") 115 | { 116 | Content = new StringContent(s) 117 | }; 118 | request.Headers.Add("Authorization", AuthorizationHeader); 119 | 120 | return await client.SendAsync(request).ConfigureAwait(false); 121 | } 122 | } 123 | } -------------------------------------------------------------------------------- /QPM/SymLinker/Abstracts/ISymLinkCreator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace SymLinker 6 | { 7 | interface ISymLinkCreator 8 | { 9 | bool CreateSymLink(string linkPath, string targetPath, bool file); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /QPM/SymLinker/LinkCreators/LinuxSymLinkCreator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Runtime.InteropServices; 5 | using System.Text; 6 | 7 | namespace SymLinker.LinkCreators 8 | { 9 | internal class LinuxSymLinkCreator : ISymLinkCreator 10 | { 11 | private const string LIBC = "libc"; 12 | 13 | [DllImport(LIBC)] 14 | private static extern int symlink( 15 | string path1, 16 | string path2 17 | ); 18 | 19 | public bool CreateSymLink(string linkPath, string targetPath, bool file) 20 | { 21 | // Will this delete the symlink or target? We'll find out soon 22 | if (File.Exists(targetPath)) 23 | File.Delete(targetPath); 24 | 25 | if (Directory.Exists(targetPath)) 26 | Directory.Delete(targetPath); 27 | 28 | return symlink(linkPath, targetPath) == 0; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /QPM/SymLinker/LinkCreators/OSXSymLinkCreator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace SymLinker.LinkCreators 6 | { 7 | internal class OSXSymLinkCreator : ISymLinkCreator 8 | { 9 | internal OSXSymLinkCreator() => throw new NotImplementedException("OSXSymLinkCreator"); 10 | 11 | public bool CreateSymLink(string linkPath, string targetPath, bool file) => throw new NotImplementedException("OSXSymLinkCreator"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /QPM/SymLinker/LinkCreators/WindowsSymLinkCreator.cs: -------------------------------------------------------------------------------- 1 | using SymLinker; 2 | using System; 3 | using System.IO; 4 | using System.Runtime.InteropServices; 5 | 6 | namespace SymLinker.LinkCreators 7 | { 8 | internal class WindowsSymLinkCreator : ISymLinkCreator 9 | { 10 | [DllImport("Kernel32.dll", CharSet = CharSet.Unicode )] 11 | static extern bool CreateHardLink( 12 | string lpFileName, 13 | string lpExistingFileName, 14 | IntPtr lpSecurityAttributes 15 | ); 16 | 17 | [DllImport("Kernel32.dll", CharSet = CharSet.Unicode )] 18 | static extern bool CreateSymbolicLink( 19 | string lpFileName, 20 | string lpExistingFileName, 21 | IntPtr lpSecurityAttributes 22 | ); 23 | 24 | public bool CreateSymLink(string source, string dest, bool file) 25 | { 26 | var symbolicLinkType = file ? SymbolicLink.File : SymbolicLink.Directory; 27 | switch (symbolicLinkType) 28 | { 29 | case SymbolicLink.File: 30 | return CreateHardLink(dest, source, IntPtr.Zero); 31 | // TODO: This doesn't work, we'll need to work on it 32 | case SymbolicLink.Directory: 33 | return CreateSymbolicLink(dest, source, (IntPtr) symbolicLinkType); 34 | } 35 | 36 | return false; 37 | } 38 | 39 | private enum SymbolicLink 40 | { 41 | File = 0, 42 | Directory = 1 43 | } 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /QPM/SymLinker/Linker.cs: -------------------------------------------------------------------------------- 1 | using SymLinker.LinkCreators; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Reflection; 6 | using System.Runtime.InteropServices; 7 | using System.Text; 8 | 9 | // Stolen from https://github.com/huffSamuel/SymLinker 10 | // Cleaned up by Fern, because the old code was horrible 11 | namespace SymLinker 12 | { 13 | public class Linker 14 | { 15 | private readonly ISymLinkCreator? _linker; 16 | 17 | /// 18 | /// Creates a new Symbolic Link Creator 19 | /// 20 | public Linker() 21 | { 22 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) 23 | { 24 | _linker = new WindowsSymLinkCreator(); 25 | } 26 | else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) 27 | { 28 | _linker = new LinuxSymLinkCreator(); 29 | } 30 | // TODO: Implement 31 | // else 32 | // { 33 | // _linker = new OSXSymLinkCreator(); 34 | // } 35 | } 36 | 37 | public bool IsValid() => _linker is not null; 38 | 39 | /// 40 | /// Creates a symbolic link from to 41 | /// 42 | /// Source file 43 | /// Destination directory 44 | /// 45 | /// Returns true if the system was able to create the SymLink 46 | /// 47 | public string? CreateLink(string source, string dest) 48 | { 49 | if (!IsValid()) 50 | { 51 | return "Platform does not support symlinking or hard linking yet"; 52 | } 53 | 54 | var error = CheckLinkReadiness(source, dest); 55 | 56 | if (error != null) 57 | { 58 | return error; 59 | } 60 | 61 | try 62 | { 63 | var linkMade = _linker!.CreateSymLink(source, dest, Path.HasExtension(source)); 64 | 65 | return linkMade && (Directory.Exists(dest) || File.Exists(dest)) ? null : "Failed to create link"; 66 | } 67 | catch (Exception e) 68 | { 69 | return e.Message; 70 | } 71 | } 72 | 73 | /// 74 | /// Checks for readiness of a drive to perform a SymLink creation. Expects absolute path 75 | /// 76 | /// Source file path 77 | /// Destination directory path 78 | /// 79 | /// Returns true if the system is ready to perform a SymLink 80 | /// 81 | private string? CheckLinkReadiness(string source, string dest) 82 | { 83 | // Check existance 84 | if (!File.Exists(source) && !Directory.Exists(source)) 85 | return "File source not found"; 86 | 87 | 88 | 89 | if ( 90 | Path.GetPathRoot(dest) != Path.GetPathRoot(source) // Check if on different drives 91 | && RuntimeInformation.IsOSPlatform(OSPlatform.Windows) // Check if Windows 92 | && Path.HasExtension(dest) // If file on Windows, it's hard link. 93 | ) 94 | return 95 | "Hardlink for file will not work on different drives on Windows. Move QPM temp or project to the same drive."; 96 | 97 | 98 | // Escape file to directory 99 | if (Path.HasExtension(dest)) 100 | { 101 | if (!Directory.Exists(dest)) 102 | dest = Path.GetDirectoryName(dest) ?? string.Empty; 103 | } 104 | else 105 | { 106 | try 107 | { 108 | dest = Directory.GetParent(dest)!.FullName; 109 | } 110 | catch (Exception e) 111 | { 112 | return e.Message; 113 | } 114 | } 115 | 116 | return !Directory.Exists(dest) ? $"Folder destination {dest} not found" : null; 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /QPM/SymLinker/SymLinker.Linker.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /QPM/Utils.cs: -------------------------------------------------------------------------------- 1 | using QPM.Commands; 2 | using QuestPackageManager.Data; 3 | using SymLinker; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Reflection; 10 | using System.Runtime.InteropServices; 11 | using System.Security.Cryptography; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | 15 | namespace QPM 16 | { 17 | public static class Utils 18 | { 19 | private static readonly Linker linker = new(); 20 | 21 | public static void WriteMessage(string message, ConsoleColor color) 22 | { 23 | var oldColor = Console.ForegroundColor; 24 | Console.ForegroundColor = color; 25 | Console.WriteLine(message); 26 | Console.ForegroundColor = oldColor; 27 | } 28 | 29 | public static void WriteSuccess(string message = "Success!") => WriteMessage(message, ConsoleColor.Green); 30 | 31 | public static void WriteFail(string message = "Failed!") => WriteMessage(message, ConsoleColor.Red); 32 | 33 | public static void DirectoryPermissions(string absPath) 34 | { 35 | ProcessStartInfo startInfo = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) 36 | ? new ProcessStartInfo 37 | { 38 | FileName = "cmd.exe", 39 | Arguments = "/C chmod +rw --recursive \"" + absPath + "\"", 40 | UseShellExecute = false, 41 | CreateNoWindow = true, 42 | } 43 | : new ProcessStartInfo 44 | { 45 | FileName = "/bin/bash", 46 | Arguments = "-c \"chmod -R +rw '" + absPath + "'\"", 47 | UseShellExecute = false, 48 | CreateNoWindow = true 49 | }; 50 | var proc = Process.Start(startInfo); 51 | proc?.WaitForExit(1000); 52 | } 53 | 54 | public static void CreateDirectory(string path) 55 | { 56 | var info = Directory.CreateDirectory(path); 57 | if (info.Attributes.HasFlag(FileAttributes.ReadOnly)) 58 | info.Attributes &= ~FileAttributes.ReadOnly; 59 | } 60 | 61 | public static byte[]? FolderHash(string path) 62 | { 63 | var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).OrderBy(p => p).ToList(); 64 | 65 | using var md5 = MD5.Create(); 66 | 67 | for (int i = 0; i < files.Count; i++) 68 | { 69 | string file = files[i]; 70 | 71 | // hash path 72 | string relativePath = file[(path.Length + 1)..]; 73 | byte[] pathBytes = Encoding.UTF8.GetBytes(relativePath.ToLower()); 74 | md5.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0); 75 | 76 | // hash contents 77 | byte[] contentBytes = File.ReadAllBytes(file); 78 | if (i == files.Count - 1) 79 | md5.TransformFinalBlock(contentBytes, 0, contentBytes.Length); 80 | else 81 | md5.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0); 82 | } 83 | 84 | return md5.Hash; 85 | } 86 | 87 | public static byte[] FileHash(string path) 88 | { 89 | MD5 md5 = MD5.Create(); 90 | 91 | return md5.ComputeHash(File.ReadAllBytes(path)); 92 | } 93 | 94 | public static void DeleteDirectory(string path) 95 | { 96 | if (new DirectoryInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint)) 97 | { 98 | // Does not recurse through reparse point 99 | Directory.Delete(path, true); 100 | return; 101 | } 102 | foreach (string directory in Directory.GetDirectories(path)) 103 | DeleteDirectory(directory); 104 | foreach (string file in Directory.GetFiles(path)) 105 | { 106 | File.SetAttributes(file, FileAttributes.Normal); 107 | File.Delete(file); 108 | } 109 | _ = new DirectoryInfo(path) 110 | { 111 | Attributes = FileAttributes.Normal 112 | }; 113 | try 114 | { 115 | Directory.Delete(path); 116 | } 117 | catch (IOException) 118 | { 119 | Directory.Delete(path); 120 | } 121 | catch (UnauthorizedAccessException) 122 | { 123 | Directory.Delete(path); 124 | } 125 | } 126 | 127 | /// 128 | /// 129 | /// 130 | /// 131 | /// 132 | /// true if symlinked false if copied 133 | public static bool SymlinkOrCopyFile(string source, string dest) 134 | { 135 | if (File.Exists(dest)) 136 | File.Delete(dest); 137 | if (!Program.Config.UseSymlinks) 138 | { 139 | File.Copy(source, dest); 140 | return false; 141 | } 142 | 143 | if (!linker.IsValid()) 144 | { 145 | Console.Error.WriteLine($"Unable to use symlinks on {RuntimeInformation.OSDescription}, falling back to copy"); 146 | File.Copy(source, dest); 147 | return false; 148 | } 149 | 150 | // Attempt to make symlinks to avoid unnecessary copy 151 | var error = linker.CreateLink(Path.GetFullPath(source), Path.GetFullPath(dest)); 152 | 153 | if (error is null) 154 | { 155 | Console.WriteLine($"Created symlink from {source} to {dest}"); 156 | return true; 157 | } 158 | 159 | Console.WriteLine($"Unable to create symlink due to: \"{error}\" on {RuntimeInformation.OSDescription}, falling back to copy"); 160 | 161 | File.Copy(source, dest); 162 | return false; 163 | } 164 | 165 | /// 166 | /// 167 | /// 168 | /// 169 | /// 170 | /// 171 | /// 172 | /// true if symlinked false if copied 173 | public static bool SymLinkOrCopyDirectory(string source, string dst, bool recurse = true, 174 | Action? onFileCopied = null) 175 | { 176 | if (!Program.Config.UseSymlinks) 177 | { 178 | if (Directory.Exists(dst)) 179 | DeleteDirectory(dst); 180 | CopyDirectory(source, dst, recurse, onFileCopied); 181 | return false; 182 | } 183 | if (!linker.IsValid()) 184 | { 185 | Console.Error.WriteLine($"Unable to use symlinks on {RuntimeInformation.OSDescription}, falling back to copy"); 186 | CopyDirectory(source, dst, recurse, onFileCopied); 187 | return false; 188 | } 189 | 190 | if (Directory.Exists(dst)) 191 | DeleteDirectory(dst); 192 | 193 | // Attempt to make symlinks to avoid unnecessary copy 194 | var error = linker.CreateLink(Path.GetFullPath(source), Path.GetFullPath(dst)); 195 | 196 | if (error == null) 197 | { 198 | // Ensure the copied directory has permissions 199 | DirectoryPermissions(dst); 200 | Console.WriteLine($"Created symlink from {source} to {dst}"); 201 | return true; 202 | } 203 | 204 | Console.WriteLine($"Unable to create symlink due to: \"{error}\" on {RuntimeInformation.OSDescription}, falling back to copy"); 205 | CopyDirectory(source, dst, recurse, onFileCopied); 206 | return false; 207 | } 208 | 209 | public static void CopyDirectory(string source, string dst, bool recurse = true, Action? onFileCopied = null) 210 | { 211 | DirectoryInfo dir = new(source); 212 | if (!Directory.Exists(dst)) 213 | Directory.CreateDirectory(dst); 214 | 215 | foreach (var f in dir.GetFiles()) 216 | { 217 | if (!f.Exists) 218 | continue; 219 | var path = Path.Combine(dst, f.Name); 220 | f.CopyTo(path); 221 | onFileCopied?.Invoke(path); 222 | } 223 | 224 | if (recurse) 225 | foreach (var d in dir.GetDirectories()) 226 | { 227 | if (d.Exists && d.Attributes.HasFlag(FileAttributes.Directory)) 228 | CopyDirectory(d.FullName, Path.Combine(dst, d.Name), recurse); 229 | } 230 | // Ensure the copied directory has permissions 231 | DirectoryPermissions(dst); 232 | } 233 | 234 | public static string GetSubdir(string path) 235 | { 236 | var actualRoot = path; 237 | var dirs = Directory.GetDirectories(actualRoot); 238 | while (dirs.Length == 1 && Directory.GetFiles(actualRoot).Length == 0) 239 | { 240 | // If we have only one folder and no files, chances are we have to go one level deeper 241 | actualRoot = dirs[0]; 242 | dirs = Directory.GetDirectories(actualRoot); 243 | } 244 | return actualRoot; 245 | } 246 | 247 | private static readonly string oldTempDir1 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, Assembly.GetExecutingAssembly().GetName().Name + "_Temp"); 248 | private static readonly string oldTempDir2 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, Assembly.GetExecutingAssembly().GetName().Name + "_Tempv2"); 249 | private static readonly string newTempDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Assembly.GetExecutingAssembly().GetName().Name + "_Temp"); 250 | 251 | public static void DeleteTempDir() 252 | { 253 | if (Directory.Exists(oldTempDir1)) 254 | DeleteDirectory(oldTempDir1); 255 | 256 | if (Directory.Exists(oldTempDir2)) 257 | DeleteDirectory(oldTempDir2); 258 | 259 | if (Directory.Exists(newTempDir)) 260 | DeleteDirectory(newTempDir); 261 | 262 | if (Directory.Exists(Program.Config.CachePath)) 263 | DeleteDirectory(Program.Config.CachePath); 264 | } 265 | 266 | // Conversion from PackageInfo to Id/version directory under cache directory. 267 | private static string GetCachedConfig(PackageInfo packageInfo) => Path.Combine(GetTempDir(), packageInfo.Id, packageInfo.Version.ToString()); 268 | 269 | private const string libsFolder = "libs"; 270 | private const string sourceLocation = "src"; 271 | 272 | /// 273 | /// Returns the provided library path from the and the library name. 274 | /// 275 | /// 276 | /// 277 | public static string GetLibrary(PackageInfo packageInfo, string libName) => Path.Combine(GetCachedConfig(packageInfo), libsFolder, libName); 278 | 279 | /// 280 | /// Returns the path to the source location for the provided . 281 | /// 282 | /// 283 | /// 284 | public static string GetSource(PackageInfo packageInfo) => Path.Combine(GetCachedConfig(packageInfo), sourceLocation); 285 | 286 | // TODO: Make this configurable, QPM would have a config file that would be writable via `qpm cache set` or something similar 287 | private static string GetTempDir() 288 | { 289 | CreateDirectory(Program.Config.CachePath); 290 | DirectoryPermissions(Program.Config.CachePath); 291 | return Program.Config.CachePath; 292 | } 293 | 294 | public static string ReplaceFirst(this string str, string toFind, string toReplace) 295 | { 296 | var loc = str.IndexOf(toFind); 297 | if (loc < 0) 298 | return str; 299 | return str.Substring(0, loc) + toReplace + str.Substring(loc + toFind.Length); 300 | } 301 | 302 | public static string ReplaceLast(this string str, string toFind, string toReplace) 303 | { 304 | var loc = str.LastIndexOf(toFind); 305 | if (loc < 0) 306 | return str; 307 | return str.Substring(0, loc) + toReplace + str.Substring(loc + toFind.Length); 308 | } 309 | 310 | /// 311 | /// Returns the .so name of the provided PackageInfo, or null if it is headerOnly. 312 | /// 313 | /// 314 | /// 315 | public static string? GetSoName(this PackageInfo info, out bool overriden) 316 | { 317 | overriden = false; 318 | if (info.AdditionalData.TryGetValue(SupportedPropertiesCommand.HeadersOnly, out var elem) && elem.GetBoolean()) 319 | return null; 320 | if (info.AdditionalData.TryGetValue(SupportedPropertiesCommand.OverrideSoName, out var name)) 321 | { 322 | overriden = true; 323 | return name.GetString(); 324 | } 325 | 326 | string ext = IsStaticLinking(info) ? ".a" : ".so"; 327 | 328 | return "lib" + (info.Id + "_" + info.Version.ToString()).Replace('.', '_') + ext; 329 | } 330 | 331 | public static bool IsStaticLinking(this PackageInfo info) => info.AdditionalData.TryGetValue(SupportedPropertiesCommand.StaticLinking, out var elem) && elem.GetBoolean(); 332 | } 333 | } -------------------------------------------------------------------------------- /QuestPackageManager.Tests/PackageHandlerTests/ChangeVersionTests.cs: -------------------------------------------------------------------------------- 1 | using Moq; 2 | using QuestPackageManager.Data; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Xunit; 9 | 10 | namespace QuestPackageManager.Tests.PackageHandlerTests 11 | { 12 | public class ChangeVersionTests 13 | { 14 | [Fact] 15 | public void ChangeVersionExceptions() 16 | { 17 | // Callbacks 18 | bool configCalled = false; 19 | void Handler_OnConfigVersionChanged(PackageHandler arg1, Config config, SemVer.Version arg2) 20 | { 21 | configCalled = true; 22 | } 23 | bool called = false; 24 | void Handler_OnVersionChanged(PackageHandler arg1, SemVer.Version arg2) 25 | { 26 | called = true; 27 | } 28 | 29 | var config = new Config { Info = new PackageInfo("N", "ID", new SemVer.Version("0.0.1")) }; 30 | var configProvider = Utils.GetConfigProvider(config, failToGet: true); 31 | 32 | var handler = new PackageHandler(configProvider.Object); 33 | handler.OnConfigVersionChanged += Handler_OnConfigVersionChanged; 34 | handler.OnVersionChanged += Handler_OnVersionChanged; 35 | 36 | // Should throw an ANE for a null version 37 | Assert.Throws(() => handler.ChangeVersion(null)); 38 | 39 | // Should throw a failure if the config could not be found 40 | var newVersion = new SemVer.Version("0.1.0"); 41 | Assert.Throws(() => handler.ChangeVersion(newVersion)); 42 | // Config should never have been committed or changed 43 | configProvider.Verify(mocks => mocks.Commit(), Times.Never); 44 | Assert.False(config.Info.Version == newVersion); 45 | // Callbacks should never have been called 46 | Assert.False(configCalled); 47 | Assert.False(called); 48 | 49 | config = new Config(); 50 | configProvider = Utils.GetConfigProvider(config); 51 | handler = new PackageHandler(configProvider.Object); 52 | handler.OnConfigVersionChanged += Handler_OnConfigVersionChanged; 53 | handler.OnVersionChanged += Handler_OnVersionChanged; 54 | 55 | // Should throw a failure if the config.Info property is null 56 | Assert.Throws(() => handler.ChangeVersion(newVersion)); 57 | 58 | // Config should never have been committed 59 | configProvider.Verify(mocks => mocks.Commit(), Times.Never); 60 | // Callbacks should never have been called 61 | Assert.False(configCalled); 62 | Assert.False(called); 63 | } 64 | 65 | [Fact] 66 | public void ChangeVersionStandard() 67 | { 68 | // Callbacks 69 | bool configCalled = false; 70 | void Handler_OnConfigVersionChanged(PackageHandler arg1, Config config, SemVer.Version arg2) 71 | { 72 | configCalled = true; 73 | } 74 | bool called = false; 75 | void Handler_OnVersionChanged(PackageHandler arg1, SemVer.Version arg2) 76 | { 77 | called = true; 78 | } 79 | 80 | var config = new Config { Info = new PackageInfo("N", "ID", new SemVer.Version("0.0.1")) }; 81 | var configProvider = Utils.GetConfigProvider(config); 82 | 83 | var handler = new PackageHandler(configProvider.Object); 84 | handler.OnConfigVersionChanged += Handler_OnConfigVersionChanged; 85 | handler.OnVersionChanged += Handler_OnVersionChanged; 86 | 87 | var newVersion = new SemVer.Version("0.1.0"); 88 | handler.ChangeVersion(newVersion); 89 | 90 | // Ensure config was committed 91 | configProvider.Verify(m => m.Commit()); 92 | // Ensure config has changed to match info 93 | Assert.True(config.Info.Version == newVersion); 94 | // Ensure callbacks were triggered 95 | Assert.True(configCalled); 96 | Assert.True(called); 97 | } 98 | 99 | [Fact] 100 | public void ChangeVersionPluginException() 101 | { 102 | static void Handler_OnConfigVersionChanged(PackageHandler arg1, Config config, SemVer.Version arg2) 103 | { 104 | throw new ArgumentOutOfRangeException(); 105 | } 106 | var config = new Config { Info = new PackageInfo("N", "ID", new SemVer.Version("0.0.1")) }; 107 | var configProvider = Utils.GetConfigProvider(config); 108 | 109 | var handler = new PackageHandler(configProvider.Object); 110 | handler.OnConfigVersionChanged += Handler_OnConfigVersionChanged; 111 | 112 | var newVersion = new SemVer.Version("0.1.0"); 113 | 114 | // Should throw plugin exception 115 | Assert.Throws(() => handler.ChangeVersion(newVersion)); 116 | // Ensure config has not been committed 117 | configProvider.Verify(mocks => mocks.Commit(), Times.Never); 118 | // Ensure config has not changed 119 | Assert.False(config.Info.Version == newVersion); 120 | } 121 | } 122 | } -------------------------------------------------------------------------------- /QuestPackageManager.Tests/PackageHandlerTests/CreatePackageTests.cs: -------------------------------------------------------------------------------- 1 | using Moq; 2 | using QuestPackageManager.Data; 3 | using System; 4 | using Xunit; 5 | 6 | namespace QuestPackageManager.Tests.PackageHandlerTests 7 | { 8 | public class CreatePackageTests 9 | { 10 | [Fact] 11 | public void CreatePackageStandard() 12 | { 13 | // Callbacks 14 | bool calledConfigured = false; 15 | void Handler_OnPackageConfigured(PackageHandler arg1, Config arg2, PackageInfo arg3) 16 | { 17 | calledConfigured = true; 18 | } 19 | bool calledCreated = false; 20 | void Handler_OnPackageCreated(PackageHandler arg1, PackageInfo arg3) 21 | { 22 | calledCreated = true; 23 | } 24 | 25 | // Start with an empty config 26 | var config = new Config(); 27 | var configProvider = Utils.GetConfigProvider(config); 28 | 29 | var handler = new PackageHandler(configProvider.Object); 30 | 31 | var info = new PackageInfo("CoolName", "CoolId", new SemVer.Version("0.1.0")) { Url = new Uri("http://test.com") }; 32 | handler.OnPackageConfigured += Handler_OnPackageConfigured; 33 | handler.OnPackageCreated += Handler_OnPackageCreated; 34 | handler.CreatePackage(info); 35 | 36 | // Ensure config was created 37 | configProvider.Verify(m => m.GetConfig(true)); 38 | // Ensure config was committed 39 | configProvider.Verify(m => m.Commit()); 40 | // Ensure config has changed to match info 41 | Assert.True(config.Info.Id == info.Id); 42 | Assert.True(config.Info.Name == info.Name); 43 | Assert.True(config.Info.Version == info.Version); 44 | Assert.True(config.Info.Url == info.Url); 45 | // Ensure callbacks were triggered 46 | Assert.True(calledConfigured); 47 | Assert.True(calledCreated); 48 | } 49 | 50 | [Fact] 51 | public void CreatePackageExceptions() 52 | { 53 | // Callbacks 54 | bool calledConfigured = false; 55 | void Handler_OnPackageConfigured(PackageHandler arg1, Config arg2, PackageInfo arg3) 56 | { 57 | calledConfigured = true; 58 | } 59 | bool calledCreated = false; 60 | void Handler_OnPackageCreated(PackageHandler arg1, PackageInfo arg3) 61 | { 62 | calledCreated = true; 63 | } 64 | 65 | var config = new Config(); 66 | var configProvider = Utils.GetConfigProvider(config, true); 67 | 68 | var handler = new PackageHandler(configProvider.Object); 69 | handler.OnPackageConfigured += Handler_OnPackageConfigured; 70 | handler.OnPackageCreated += Handler_OnPackageCreated; 71 | 72 | var info = new PackageInfo("CoolName", "CoolId", new SemVer.Version("0.1.0")) { Url = new Uri("http://test.com") }; 73 | // Ensure a ConfigException is thrown 74 | Assert.Throws(() => handler.CreatePackage(info)); 75 | // Ensure config has not been committed 76 | configProvider.Verify(m => m.Commit(), Times.Never); 77 | // Ensure config has not changed 78 | Assert.True(config.Info is null); 79 | // Ensure callbacks did not happen 80 | Assert.False(calledConfigured); 81 | Assert.False(calledCreated); 82 | // Ensure an ANE is thrown for a null package info 83 | Assert.Throws(() => handler.CreatePackage(null)); 84 | } 85 | 86 | [Fact] 87 | public void CreatePackagePlugin() 88 | { 89 | // Callback which throws 90 | static void Handler_OnPackageConfigured(PackageHandler arg1, Config arg2, PackageInfo arg3) 91 | { 92 | // Modify config 93 | arg2.Info.Name = "Modified Name!"; 94 | } 95 | 96 | var config = new Config(); 97 | var configProvider = Utils.GetConfigProvider(config); 98 | 99 | var handler = new PackageHandler(configProvider.Object); 100 | handler.OnPackageConfigured += Handler_OnPackageConfigured; 101 | 102 | var info = new PackageInfo("CoolName", "CoolId", new SemVer.Version("0.1.0")) { Url = new Uri("http://test.com") }; 103 | handler.CreatePackage(info); 104 | // Ensure config has been committed 105 | configProvider.Verify(mocks => mocks.Commit(), Times.Once); 106 | // Ensure config has changed to match 107 | Assert.True(config.Info != null); 108 | Assert.True(config.Info.Id == info.Id); 109 | Assert.True(config.Info.Name == "Modified Name!"); 110 | Assert.True(config.Info.Version == info.Version); 111 | Assert.True(config.Info.Url == info.Url); 112 | } 113 | 114 | [Fact] 115 | public void CreatePackagePluginException() 116 | { 117 | // Callback which throws 118 | static void Handler_OnPackageConfigured(PackageHandler arg1, Config arg2, PackageInfo arg3) 119 | { 120 | throw new ArgumentOutOfRangeException(); 121 | } 122 | 123 | var config = new Config(); 124 | var configProvider = Utils.GetConfigProvider(config); 125 | 126 | var handler = new PackageHandler(configProvider.Object); 127 | handler.OnPackageConfigured += Handler_OnPackageConfigured; 128 | 129 | var info = new PackageInfo("CoolName", "CoolId", new SemVer.Version("0.1.0")) { Url = new Uri("http://test.com") }; 130 | // Ensure a ArgumentOutOfRangeException is thrown 131 | Assert.Throws(() => handler.CreatePackage(info)); 132 | // Ensure config has not been committed 133 | configProvider.Verify(mocks => mocks.Commit(), Times.Never); 134 | // Ensure config has not changed 135 | Assert.True(config.Info is null); 136 | } 137 | } 138 | } -------------------------------------------------------------------------------- /QuestPackageManager.Tests/QuestPackageManager.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /QuestPackageManager.Tests/Utils.cs: -------------------------------------------------------------------------------- 1 | using Moq; 2 | using QuestPackageManager.Data; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace QuestPackageManager.Tests 10 | { 11 | internal static class Utils 12 | { 13 | internal static Mock GetConfigProvider(Config config, bool failToCreate = false, bool failToGet = false) 14 | { 15 | var mock = new Mock(); 16 | mock.Setup(m => m.Commit()).Verifiable(); 17 | if (failToCreate) 18 | mock.Setup(m => m.GetConfig(true)).Returns(null); 19 | else 20 | mock.Setup(m => m.GetConfig(true)).Returns(config); 21 | if (failToGet) 22 | mock.Setup(m => m.GetConfig(false)).Returns(null); 23 | else 24 | mock.Setup(m => m.GetConfig(false)).Returns(config); 25 | return mock; 26 | } 27 | 28 | internal static Mock GetUriHandler(Dictionary map) 29 | { 30 | var mock = new Mock(); 31 | mock.Setup(m => m.GetSharedConfig(It.IsAny())).Returns(d => Task.FromResult(map[d.Dependency])); 32 | mock.Setup(m => m.ResolveDependency(It.IsAny(), It.IsAny())); 33 | return mock; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /QuestPackageManager.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30128.36 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QuestPackageManager", "QuestPackageManager\QuestPackageManager.csproj", "{0399192E-D041-41C4-A17E-CD68EFF107D7}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{36BA0E01-7754-45BD-B753-2E37235515C3}" 9 | ProjectSection(SolutionItems) = preProject 10 | .editorconfig = .editorconfig 11 | README.md = README.md 12 | EndProjectSection 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QuestPackageManager.Tests", "QuestPackageManager.Tests\QuestPackageManager.Tests.csproj", "{BF769888-71AE-4453-8DB9-1808B4DCAB35}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QPM", "QPM\QPM.csproj", "{E19C9DB6-A81D-4612-81D2-DCF517BDAEAD}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Debug|x64 = Debug|x64 22 | Release|Any CPU = Release|Any CPU 23 | Release|x64 = Release|x64 24 | EndGlobalSection 25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 26 | {0399192E-D041-41C4-A17E-CD68EFF107D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {0399192E-D041-41C4-A17E-CD68EFF107D7}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {0399192E-D041-41C4-A17E-CD68EFF107D7}.Debug|x64.ActiveCfg = Debug|x64 29 | {0399192E-D041-41C4-A17E-CD68EFF107D7}.Debug|x64.Build.0 = Debug|x64 30 | {0399192E-D041-41C4-A17E-CD68EFF107D7}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {0399192E-D041-41C4-A17E-CD68EFF107D7}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {0399192E-D041-41C4-A17E-CD68EFF107D7}.Release|x64.ActiveCfg = Release|x64 33 | {0399192E-D041-41C4-A17E-CD68EFF107D7}.Release|x64.Build.0 = Release|x64 34 | {BF769888-71AE-4453-8DB9-1808B4DCAB35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {BF769888-71AE-4453-8DB9-1808B4DCAB35}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {BF769888-71AE-4453-8DB9-1808B4DCAB35}.Debug|x64.ActiveCfg = Debug|Any CPU 37 | {BF769888-71AE-4453-8DB9-1808B4DCAB35}.Debug|x64.Build.0 = Debug|Any CPU 38 | {BF769888-71AE-4453-8DB9-1808B4DCAB35}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {BF769888-71AE-4453-8DB9-1808B4DCAB35}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {BF769888-71AE-4453-8DB9-1808B4DCAB35}.Release|x64.ActiveCfg = Release|Any CPU 41 | {BF769888-71AE-4453-8DB9-1808B4DCAB35}.Release|x64.Build.0 = Release|Any CPU 42 | {E19C9DB6-A81D-4612-81D2-DCF517BDAEAD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {E19C9DB6-A81D-4612-81D2-DCF517BDAEAD}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {E19C9DB6-A81D-4612-81D2-DCF517BDAEAD}.Debug|x64.ActiveCfg = Debug|x64 45 | {E19C9DB6-A81D-4612-81D2-DCF517BDAEAD}.Debug|x64.Build.0 = Debug|x64 46 | {E19C9DB6-A81D-4612-81D2-DCF517BDAEAD}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {E19C9DB6-A81D-4612-81D2-DCF517BDAEAD}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {E19C9DB6-A81D-4612-81D2-DCF517BDAEAD}.Release|x64.ActiveCfg = Release|x64 49 | {E19C9DB6-A81D-4612-81D2-DCF517BDAEAD}.Release|x64.Build.0 = Release|x64 50 | EndGlobalSection 51 | GlobalSection(SolutionProperties) = preSolution 52 | HideSolutionNode = FALSE 53 | EndGlobalSection 54 | GlobalSection(ExtensibilityGlobals) = postSolution 55 | SolutionGuid = {0528F945-51BF-48A7-B4C8-9A89F490F595} 56 | EndGlobalSection 57 | EndGlobal 58 | -------------------------------------------------------------------------------- /QuestPackageManager/Data/Config.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.Json; 6 | using System.Text.Json.Serialization; 7 | using System.Threading.Tasks; 8 | 9 | namespace QuestPackageManager.Data 10 | { 11 | public class Config 12 | { 13 | public string SharedDir { get; set; } = "shared"; 14 | public string DependenciesDir { get; set; } = "extern"; 15 | public PackageInfo? Info { get; set; } 16 | 17 | [JsonInclude] 18 | public List Dependencies { get; private set; } = new List(); 19 | 20 | [JsonInclude] 21 | public Dictionary AdditionalData { get; private set; } = new Dictionary(); 22 | } 23 | } -------------------------------------------------------------------------------- /QuestPackageManager/Data/ConfigException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace QuestPackageManager.Data 8 | { 9 | public class ConfigException : Exception 10 | { 11 | public ConfigException(string message) : base(message) 12 | { 13 | } 14 | 15 | public ConfigException(string message, Exception innerException) : base(message, innerException) 16 | { 17 | } 18 | 19 | public ConfigException() 20 | { 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /QuestPackageManager/Data/Dependency.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualBasic.CompilerServices; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics.CodeAnalysis; 5 | using System.Linq; 6 | using System.Text.Json; 7 | using System.Text.Json.Serialization; 8 | 9 | namespace QuestPackageManager.Data 10 | { 11 | public class Dependency : IEquatable 12 | { 13 | public string? Id { get; set; } 14 | 15 | [JsonConverter(typeof(SemVerRangeConverter))] 16 | public SemVer.Range? VersionRange { get; set; } 17 | 18 | [JsonInclude] 19 | public Dictionary AdditionalData { get; private set; } = new Dictionary(); 20 | 21 | public Dependency(string id, SemVer.Range versionRange) 22 | { 23 | Id = id; 24 | VersionRange = versionRange; 25 | } 26 | 27 | [JsonConstructor] 28 | private Dependency() 29 | { 30 | } 31 | 32 | public bool Equals([AllowNull] Dependency other) 33 | { 34 | if (other is null) 35 | return false; 36 | return Id == other.Id 37 | && VersionRange == other.VersionRange 38 | && AdditionalData.Count == other.AdditionalData.Count 39 | && !AdditionalData.Keys.Any(k => !other.AdditionalData.ContainsKey(k)) 40 | && !other.AdditionalData.Keys.Any(k => !AdditionalData.ContainsKey(k)); 41 | } 42 | 43 | public static bool operator ==(Dependency? left, Dependency? right) => (left?.Equals(right)) ?? false; 44 | 45 | public static bool operator !=(Dependency? left, Dependency? right) => (left?.Equals(right)) ?? true; 46 | 47 | public override bool Equals(object? obj) => Equals(obj as Dependency); 48 | 49 | public override int GetHashCode() => string.GetHashCode(Id, StringComparison.OrdinalIgnoreCase) * 19 + VersionRange?.GetHashCode() * 59 + AdditionalData.Count ?? 0; 50 | } 51 | } -------------------------------------------------------------------------------- /QuestPackageManager/Data/IConfigProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace QuestPackageManager.Data 8 | { 9 | public interface IConfigProvider 10 | { 11 | string ToString(SharedConfig? config); 12 | 13 | SharedConfig? From(string data); 14 | 15 | SharedConfig? GetSharedConfig(bool createOnFail = false); 16 | 17 | Config? GetConfig(bool createOnFail = false); 18 | 19 | void Commit(); 20 | } 21 | } -------------------------------------------------------------------------------- /QuestPackageManager/Data/PackageInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text.Json; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace QuestPackageManager.Data 7 | { 8 | public class PackageInfo 9 | { 10 | public string Name { get; set; } 11 | public string Id { get; set; } 12 | 13 | [JsonConverter(typeof(SemVerConverter))] 14 | public SemVer.Version Version { get; set; } 15 | 16 | public Uri? Url { get; set; } 17 | 18 | [JsonInclude] 19 | public Dictionary AdditionalData { get; private set; } = new Dictionary(); 20 | 21 | public PackageInfo(string name, string id, SemVer.Version version) 22 | { 23 | Name = name; 24 | Id = id; 25 | Version = version; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /QuestPackageManager/Data/SemVerConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.CodeAnalysis; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Text.Json; 7 | using System.Text.Json.Serialization; 8 | using System.Threading.Tasks; 9 | 10 | namespace QuestPackageManager.Data 11 | { 12 | public class SemVerConverter : JsonConverter 13 | { 14 | [return: MaybeNull] 15 | public override SemVer.Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => new SemVer.Version(reader.GetString()); 16 | 17 | public override void Write(Utf8JsonWriter writer, SemVer.Version value, JsonSerializerOptions options) => writer?.WriteStringValue(value?.ToString()); 18 | } 19 | 20 | public class SemVerRangeConverter : JsonConverter 21 | { 22 | [return: MaybeNull] 23 | public override SemVer.Range Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => new SemVer.Range(reader.GetString()); 24 | 25 | public override void Write(Utf8JsonWriter writer, SemVer.Range value, JsonSerializerOptions options) => writer?.WriteStringValue(value?.ToString()); 26 | } 27 | } -------------------------------------------------------------------------------- /QuestPackageManager/Data/SharedConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.CodeAnalysis; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Text.Json.Serialization; 7 | using System.Threading.Tasks; 8 | 9 | namespace QuestPackageManager.Data 10 | { 11 | /// 12 | /// Config generated after a restore, should be uploaded to qpackages.com 13 | /// This config is necessary for proper dependency resolution of .so files or version specific information. 14 | /// 15 | public class SharedConfig 16 | { 17 | /// 18 | /// Overall configuration object 19 | /// 20 | [JsonInclude] 21 | public Config? Config { get; set; } 22 | 23 | /// 24 | /// Dependencies that were restored, ID, version pairs 25 | /// 26 | [JsonInclude] 27 | public List RestoredDependencies { get; private set; } = new List(); 28 | } 29 | 30 | public class RestoredDependencyPair : IEquatable 31 | { 32 | public Dependency? Dependency { get; set; } 33 | 34 | [JsonConverter(typeof(SemVerConverter))] 35 | public SemVer.Version? Version { get; set; } 36 | 37 | public static bool operator ==(RestoredDependencyPair? left, RestoredDependencyPair? right) => (left?.Equals(right)) ?? false; 38 | 39 | public static bool operator !=(RestoredDependencyPair? left, RestoredDependencyPair? right) => (left?.Equals(right)) ?? true; 40 | 41 | public override bool Equals(object? obj) => obj is RestoredDependencyPair d ? Equals(d) : false; 42 | 43 | public bool Equals([AllowNull] RestoredDependencyPair other) => other?.Dependency == Dependency && other?.Version == Version; 44 | 45 | public override int GetHashCode() => (Dependency?.GetHashCode() + 59 * Version?.GetHashCode()).GetValueOrDefault(); 46 | } 47 | } -------------------------------------------------------------------------------- /QuestPackageManager/DependencyException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace QuestPackageManager 8 | { 9 | public class DependencyException : Exception 10 | { 11 | public DependencyException(string message) : base(message) 12 | { 13 | } 14 | 15 | public DependencyException(string message, Exception innerException) : base(message, innerException) 16 | { 17 | } 18 | 19 | public DependencyException() 20 | { 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /QuestPackageManager/Handlers/DependencyHandler.cs: -------------------------------------------------------------------------------- 1 | using QuestPackageManager.Data; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace QuestPackageManager 9 | { 10 | public class DependencyHandler 11 | { 12 | private readonly IConfigProvider configProvider; 13 | 14 | // bool represents if dependency already existed 15 | public event Action? OnConfigDependencyAdded; 16 | 17 | // bool represents if dependency already existed 18 | public event Action? OnDependencyAdded; 19 | 20 | public event Action? OnConfigDependencyRemoved; 21 | 22 | public event Action? OnDependencyRemoved; 23 | 24 | public DependencyHandler(IConfigProvider configProvider) 25 | { 26 | this.configProvider = configProvider; 27 | } 28 | 29 | public void AddDependency(string id, SemVer.Range range) => AddDependency(new Dependency(id, range)); 30 | 31 | public void AddDependency(Dependency dep) 32 | { 33 | if (dep is null) 34 | throw new ArgumentNullException(nameof(dep), Resources.DependencyNull); 35 | if (dep.Id is null) 36 | throw new ArgumentException(Resources.DependencyIdNull); 37 | // This should be faily straightforward: 38 | // The given dependency should be added to the config, the config should be committed 39 | // Then we should perform (automatically or manually) restore in order to ensure we can obtain this dependency. 40 | // If we are adding a dependency that already exists (by id) we update the version to match this. 41 | var conf = configProvider.GetConfig(); 42 | if (conf is null) 43 | throw new ConfigException(Resources.ConfigNotFound); 44 | if (conf.Info is null) 45 | throw new ConfigException(Resources.ConfigInfoIsNull); 46 | if (conf.Info.Id.Equals(dep.Id, StringComparison.OrdinalIgnoreCase)) 47 | throw new DependencyException($"Recursive dependency! Tried to add dependency: {dep.Id}, but package ID matches!"); 48 | // Ids are not case sensitive 49 | var existing = conf.Dependencies.Find(d => dep.Id.Equals(d.Id, StringComparison.OrdinalIgnoreCase)); 50 | if (existing is null) 51 | { 52 | conf.Dependencies.Add(dep); 53 | } 54 | else 55 | { 56 | existing.VersionRange = dep.VersionRange; 57 | existing.AdditionalData.Clear(); 58 | foreach (var p in dep.AdditionalData) 59 | existing.AdditionalData.Add(p.Key, p.Value); 60 | } 61 | var shared = configProvider.GetSharedConfig(); 62 | if (shared != null) 63 | shared.Config = conf; 64 | OnConfigDependencyAdded?.Invoke(this, conf, dep, existing != null); 65 | configProvider.Commit(); 66 | // Perform additional modification 67 | OnDependencyAdded?.Invoke(this, dep, existing != null); 68 | } 69 | 70 | public bool RemoveDependency(string matchingId) 71 | { 72 | // If the given dependency exists, remove it 73 | // If it doesn't, return false 74 | var conf = configProvider.GetConfig(); 75 | if (conf is null) 76 | throw new ConfigException(Resources.ConfigNotFound); 77 | // Get matching dependency, there should only be one per each id 78 | var matchingDep = conf.Dependencies.FirstOrDefault(d => matchingId.Equals(d.Id, StringComparison.OrdinalIgnoreCase)); 79 | if (matchingDep is null) 80 | return false; 81 | // Ids are not case sensitive 82 | var result = conf.Dependencies.Remove(matchingDep); 83 | if (result) 84 | { 85 | OnConfigDependencyRemoved?.Invoke(this, conf, matchingDep); 86 | // Get local config to remove dependency from IncludedDependencies if it exists 87 | var sharedConf = configProvider.GetSharedConfig(); 88 | if (sharedConf != null) 89 | sharedConf.RestoredDependencies.RemoveAll(p => p.Dependency != null && matchingId.Equals(p.Dependency.Id, StringComparison.OrdinalIgnoreCase)); 90 | // Perform additional modification 91 | OnDependencyRemoved?.Invoke(this, matchingDep); 92 | // This happens only after OnDependencyRemoved occurrs, ensuring that throws will happen properly 93 | // No need to commit unless we actually changed the config with a successful removal 94 | // We commit this change to both our config and shared config objects. 95 | var shared = configProvider.GetSharedConfig(); 96 | if (shared != null) 97 | shared.Config = conf; 98 | configProvider.Commit(); 99 | } 100 | return result; 101 | } 102 | } 103 | } -------------------------------------------------------------------------------- /QuestPackageManager/Handlers/IDependencyResolver.cs: -------------------------------------------------------------------------------- 1 | using QuestPackageManager.Data; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Text.Json; 7 | using System.Threading.Tasks; 8 | 9 | namespace QuestPackageManager 10 | { 11 | public interface IDependencyResolver 12 | { 13 | public Task GetSharedConfig(RestoredDependencyPair pairWithVersion); 14 | 15 | public Task ResolveDependency(Config myConfig, RestoredDependencyPair dependency); 16 | 17 | public Task ResolveUniqueDependency(Config myConfig, KeyValuePair resolved); 18 | 19 | public void RemoveDependency(in Config myConfig, in Dependency dependency); 20 | } 21 | } -------------------------------------------------------------------------------- /QuestPackageManager/Handlers/PackageHandler.cs: -------------------------------------------------------------------------------- 1 | using QuestPackageManager.Data; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace QuestPackageManager 9 | { 10 | public class PackageHandler 11 | { 12 | private readonly IConfigProvider configProvider; 13 | 14 | public event Action? OnPackageConfigured; 15 | 16 | public event Action? OnPackageCreated; 17 | 18 | public event Action? OnConfigIdChanged; 19 | 20 | public event Action? OnIdChanged; 21 | 22 | public event Action? OnConfigVersionChanged; 23 | 24 | public event Action? OnVersionChanged; 25 | 26 | public event Action? OnConfigUrlChanged; 27 | 28 | public event Action? OnUrlChanged; 29 | 30 | public event Action? OnConfigNameChanged; 31 | 32 | public event Action? OnNameChanged; 33 | 34 | public PackageHandler(IConfigProvider configProvider) 35 | { 36 | this.configProvider = configProvider; 37 | } 38 | 39 | public void CreatePackage(PackageInfo info) 40 | { 41 | if (info is null) 42 | throw new ArgumentNullException(Resources.Info); 43 | var conf = configProvider.GetConfig(true); 44 | if (conf is null) 45 | throw new ConfigException(Resources.ConfigNotCreated); 46 | var shared = configProvider.GetSharedConfig(); 47 | var tmp = conf.Info; 48 | conf.Info = info; 49 | if (shared != null && shared.Config != null) 50 | shared.Config.Info = info; 51 | // Call extra modification as necessary 52 | try 53 | { 54 | OnPackageConfigured?.Invoke(this, conf, info); 55 | } 56 | catch 57 | { 58 | conf.Info = tmp; 59 | if (shared != null && shared.Config != null) 60 | shared.Config.Info = tmp; 61 | throw; 62 | } 63 | configProvider.Commit(); 64 | // Perform extra modification 65 | OnPackageCreated?.Invoke(this, info); 66 | // Ex: Android.mk modification 67 | // Grab the config (or create it if it doesn't exist) and put the package info into it 68 | // Package info should contain the ID, version of this, along with a package URL (what repo this exists at) optionally empty. 69 | // Creating a package also ensures your Android.mk has the correct MOD_ID and VERSION set, which SHOULD be used in your main.cpp setup function. 70 | } 71 | 72 | public void ChangeUrl(Uri url) 73 | { 74 | var conf = configProvider.GetConfig(); 75 | if (conf is null) 76 | throw new ConfigException(Resources.ConfigNotFound); 77 | if (conf.Info is null) 78 | throw new ConfigException(Resources.ConfigInfoIsNull); 79 | var shared = configProvider.GetSharedConfig(); 80 | var tmp = conf.Info.Url; 81 | conf.Info.Url = url; 82 | if (shared != null && shared.Config != null && shared.Config.Info != null) 83 | shared.Config.Info.Url = url; 84 | try 85 | { 86 | OnConfigUrlChanged?.Invoke(this, conf, url); 87 | } 88 | catch 89 | { 90 | conf.Info.Url = tmp; 91 | if (shared != null && shared.Config != null && shared.Config.Info != null) 92 | shared.Config.Info.Url = tmp; 93 | throw; 94 | } 95 | configProvider.Commit(); 96 | OnUrlChanged?.Invoke(this, url); 97 | } 98 | 99 | public void ChangeName(string name) 100 | { 101 | var conf = configProvider.GetConfig(); 102 | if (conf is null) 103 | throw new ConfigException(Resources.ConfigNotFound); 104 | if (conf.Info is null) 105 | throw new ConfigException(Resources.ConfigInfoIsNull); 106 | var shared = configProvider.GetSharedConfig(); 107 | var tmp = conf.Info.Name; 108 | conf.Info.Name = name; 109 | if (shared != null && shared.Config != null && shared.Config.Info != null) 110 | shared.Config.Info.Name = name; 111 | try 112 | { 113 | OnConfigNameChanged?.Invoke(this, conf, name); 114 | } 115 | catch 116 | { 117 | conf.Info.Name = tmp; 118 | if (shared != null && shared.Config != null && shared.Config.Info != null) 119 | shared.Config.Info.Name = tmp; 120 | throw; 121 | } 122 | configProvider.Commit(); 123 | OnNameChanged?.Invoke(this, name); 124 | } 125 | 126 | public void ChangeId(string id) 127 | { 128 | if (string.IsNullOrEmpty(id)) 129 | throw new ArgumentNullException(Resources._id); 130 | var conf = configProvider.GetConfig(); 131 | if (conf is null) 132 | throw new ConfigException(Resources.ConfigNotFound); 133 | if (conf.Info is null) 134 | throw new ConfigException(Resources.ConfigInfoIsNull); 135 | var shared = configProvider.GetSharedConfig(); 136 | var tmp = conf.Info.Id; 137 | conf.Info.Id = id; 138 | if (shared != null && shared.Config != null && shared.Config.Info != null) 139 | shared.Config.Info.Id = id; 140 | // Call extra modification as necessary 141 | try 142 | { 143 | OnConfigIdChanged?.Invoke(this, conf, id); 144 | } 145 | catch 146 | { 147 | conf.Info.Id = tmp; 148 | if (shared != null && shared.Config != null && shared.Config.Info != null) 149 | shared.Config.Info.Id = tmp; 150 | throw; 151 | } 152 | configProvider.Commit(); 153 | // Perform extra modification 154 | OnIdChanged?.Invoke(this, id); 155 | // Changes the ID of the package. 156 | // Grabs the config, modifies the ID, commits it 157 | // Changes the ID in Android.mk to match 158 | } 159 | 160 | public void ChangeVersion(SemVer.Version newVersion) 161 | { 162 | if (newVersion is null) 163 | throw new ArgumentNullException(Resources._newVersion); 164 | var conf = configProvider.GetConfig(); 165 | if (conf is null) 166 | throw new ConfigException(Resources.ConfigNotFound); 167 | if (conf.Info is null) 168 | throw new ConfigException(Resources.ConfigInfoIsNull); 169 | var shared = configProvider.GetSharedConfig(); 170 | // Call extra modification to config as necessary 171 | var tmp = conf.Info.Version; 172 | conf.Info.Version = newVersion; 173 | if (shared != null && shared.Config != null && shared.Config.Info != null) 174 | shared.Config.Info.Version = newVersion; 175 | try 176 | { 177 | OnConfigVersionChanged?.Invoke(this, conf, newVersion); 178 | } 179 | catch 180 | { 181 | conf.Info.Version = tmp; 182 | if (shared != null && shared.Config != null && shared.Config.Info != null) 183 | shared.Config.Info.Version = tmp; 184 | throw; 185 | } 186 | configProvider.Commit(); 187 | // Perform extra modification 188 | OnVersionChanged?.Invoke(this, newVersion); 189 | // Changes the version of the package. 190 | // Grabs the config, modifies the version, commits it 191 | // Changes the version in Android.mk to match 192 | } 193 | } 194 | } -------------------------------------------------------------------------------- /QuestPackageManager/Handlers/RestoreHandler.cs: -------------------------------------------------------------------------------- 1 | using QuestPackageManager.Data; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Text.Json; 7 | using System.Threading.Tasks; 8 | 9 | namespace QuestPackageManager 10 | { 11 | /// 12 | /// Restores and resolves dependencies for the given config 13 | /// 14 | public class RestoreHandler 15 | { 16 | private readonly IConfigProvider configProvider; 17 | private readonly IDependencyResolver dependencyResolver; 18 | 19 | public event Action>? OnDependenciesCollected; 20 | 21 | public event Action, Dictionary>? OnRestore; 22 | 23 | public RestoreHandler(IConfigProvider configProvider, IDependencyResolver dependencyResolver) 24 | { 25 | this.configProvider = configProvider; 26 | this.dependencyResolver = dependencyResolver; 27 | } 28 | 29 | private async Task CollectDependencies(string thisId, Dictionary myDependencies, RestoredDependencyPair pair) 30 | { 31 | // pair contains simply a Dependency in most cases, but if it contains a version already, then we map that version to a SharedConfig 32 | // Null assertions 33 | if (pair is null || pair.Dependency is null) 34 | throw new ArgumentNullException(nameof(pair), Resources.DependencyNull); 35 | var d = pair.Dependency!; 36 | if (d.Id is null) 37 | throw new ArgumentException(Resources.DependencyIdNull); 38 | if (d.VersionRange is null) 39 | throw new ArgumentException($"Dependency: {d.Id} {nameof(d.VersionRange)} is null!"); 40 | if (thisId.Equals(d.Id, StringComparison.OrdinalIgnoreCase)) 41 | throw new DependencyException($"Recursive dependency! Tried to get dependency: {d.Id}, but {thisId} matches {d.Id}!"); 42 | // We want to convert our uri into a config file 43 | var depConfig = await dependencyResolver.GetSharedConfig(pair).ConfigureAwait(false); 44 | if (depConfig is null) 45 | throw new ConfigException($"Could not find config for: {d.Id}! Range: {d.VersionRange}"); 46 | // Then we want to check to ensure that the config file we have gotten is within our version 47 | if (depConfig.Config is null) 48 | throw new ConfigException($"Confid is of an invalid format for: {d.Id} - No config!"); 49 | if (depConfig.Config.Info is null) 50 | throw new ConfigException($"Config is of an invalid format for: {d.Id} - No info!"); 51 | if (string.IsNullOrEmpty(depConfig.Config.Info.Id)) 52 | throw new ConfigException($"Config is of an invalid format for: {d.Id} - No Id!"); 53 | // Check to make sure the config's version matches our dependency's version 54 | if (!depConfig.Config.Info.Id.Equals(d.Id, StringComparison.OrdinalIgnoreCase)) 55 | throw new ConfigException($"Dependency and config have different ids! {d.Id} != {depConfig.Config.Info.Id}!"); 56 | if (depConfig.Config.Info.Version is null) 57 | throw new ConfigException($"Config is of an invalid format for: {d.Id} - No Version!"); 58 | // If it isn't, we fail to match our dependencies, exit out. 59 | if (!d.VersionRange.IsSatisfied(depConfig.Config.Info.Version)) 60 | throw new DependencyException($"Dependency unmet! Want: {d.VersionRange} got: {depConfig.Config.Info.Version} for: {d.Id}"); 61 | if (pair.Version != null && pair.Version != depConfig.Config.Info.Version) 62 | throw new ConfigException($"Wanted specific version: {pair.Version} but got: {depConfig.Config.Info.Version} for: {d.Id}"); 63 | var toAdd = new RestoredDependencyPair { Dependency = d, Version = depConfig.Config.Info.Version }; 64 | 65 | // Add to collapsed mapping, if the dep to add/config is not an override name that would be a duplicate 66 | var match = myDependencies.FirstOrDefault(sc => sc.Value.Config!.Info!.AdditionalData.TryGetValue("overrideSoName", out var val) 67 | && depConfig.Config!.Info!.AdditionalData.TryGetValue("overrideSoName", out var rhs) && val.GetString() == rhs.GetString()).Key; 68 | if (match is not null) 69 | { 70 | // If we have a matching overrideSoName, check our config vs. existing config. 71 | // If our config is higher, use that instead. 72 | if (depConfig.Config!.Info!.Version > myDependencies[match].Config!.Info!.Version) 73 | { 74 | myDependencies.Remove(match); 75 | match.Dependency = d; 76 | match.Version = depConfig.Config!.Info!.Version; 77 | myDependencies.Add(match, depConfig); 78 | } 79 | } 80 | else if (!myDependencies.ContainsKey(toAdd)) 81 | { 82 | // We need to double check here, just to make sure we don't accidentally add when we literally have a potential match: 83 | if (myDependencies.Keys.FirstOrDefault(item => toAdd.Dependency.Id.Equals(item.Dependency!.Id, StringComparison.OrdinalIgnoreCase) && toAdd.Version == item.Version) is null) 84 | // If there is no exactly matching key: 85 | // Add our mapping from dependency to config 86 | myDependencies.Add(toAdd, depConfig); 87 | } 88 | // Otherwise, we iterate over all of the config's RESTORED dependencies 89 | // That is, all of the dependencies that we used to actually build this 90 | foreach (var innerD in new List(depConfig.RestoredDependencies)) 91 | { 92 | if (innerD.Dependency is null || innerD.Version is null) 93 | throw new ConfigException($"A restored dependency in config for: {depConfig.Config.Info.Id} version: {depConfig.Config.Info.Version} has a null dependency or version property!"); 94 | 95 | // Skip private dependencies from resolving 96 | if (innerD.Dependency.AdditionalData.TryGetValue("private", out var isPrivate) && 97 | isPrivate.GetBoolean()) 98 | { 99 | // Console.WriteLine($"Skipping {innerD.Dependency.Id}"); 100 | // TODO: Does sc2ad approve of this? 101 | depConfig.RestoredDependencies.Remove(innerD); 102 | continue; 103 | } 104 | 105 | 106 | // For each of the config's dependencies, collect all of the restored dependencies for it, 107 | // if we have no RestoredDependencies that match the ID, VersionRange, and Version already (since those would be the same). 108 | await CollectDependencies(thisId, myDependencies, innerD).ConfigureAwait(false); 109 | // We can actually take it easy here, we only need to COLLECT our dependencies, we don't need to COLLAPSE them. 110 | } 111 | // When we are done, myDependencies should contain a mapping of ALL of our dependencies (recursively) mapped to their SharedConfigs. 112 | } 113 | 114 | public async Task> CollectDependencies() 115 | { 116 | var config = configProvider.GetConfig(); 117 | if (config is null) 118 | throw new ConfigException(Resources.ConfigNotFound); 119 | if (config.Info is null) 120 | throw new ConfigException(Resources.ConfigInfoIsNull); 121 | var myDependencies = new Dictionary(); 122 | foreach (var d in config.Dependencies) 123 | await CollectDependencies(config.Info.Id, myDependencies, new RestoredDependencyPair { Dependency = d }).ConfigureAwait(false); 124 | // Call post dependency resolution code 125 | OnDependenciesCollected?.Invoke(this, myDependencies); 126 | return myDependencies; 127 | } 128 | 129 | /// 130 | /// Collapses a fully saturated mapping of to 131 | /// with one or more objects having the same field. 132 | /// 133 | /// Mapping to collapse 134 | /// A mapping of unique uppercased dependency IDs to 135 | public static Dictionary CollapseDependencies(Dictionary deps) 136 | { 137 | if (deps is null) 138 | throw new ArgumentNullException(nameof(deps)); 139 | var uniqueDeps = new Dictionary>(); 140 | var collapsed = new Dictionary(); 141 | // For each Dependency, we want to find all other dependencies that have the same ID 142 | foreach (var dep in deps) 143 | { 144 | if (dep.Key.Dependency is null || dep.Key.Dependency.Id is null) 145 | continue; 146 | var id = dep.Key.Dependency.Id; 147 | if (uniqueDeps.TryGetValue(id.ToUpperInvariant(), out var matchingDeps)) 148 | matchingDeps.Add((dep.Key, dep.Value)); 149 | else 150 | uniqueDeps.Add(id.ToUpperInvariant(), new List<(RestoredDependencyPair dep, SharedConfig conf)> { (dep.Key, dep.Value) }); 151 | } 152 | foreach (var p in uniqueDeps) 153 | { 154 | if (p.Value.Count == 0) 155 | continue; 156 | var depToAdd = new Dependency(p.Value[0].dep.Dependency!.Id!, p.Value[0].dep.Dependency!.VersionRange!); 157 | foreach (var kvp in p.Value[0].dep.Dependency!.AdditionalData) 158 | depToAdd.AdditionalData.Add(kvp.Key, kvp.Value); 159 | var confToAdd = p.Value[0].conf; 160 | // Also collapse the additional data into a single dependency's additional data 161 | for (int i = 1; i < p.Value.Count; i++) 162 | { 163 | // If we have multiple matching dependencies, intersect across all of them. 164 | var val = p.Value[i].dep.Dependency!; 165 | if (val.VersionRange is null) 166 | throw new ConfigException($"Dependency: {val.Id} has a null {nameof(Dependency.VersionRange)}!"); 167 | var tmp = val.VersionRange.Intersect(depToAdd.VersionRange); 168 | // Now take the intersection, if it is 0.0.0, say "uhoh" 169 | if (tmp.ToString() == "<0.0.0") 170 | throw new DependencyException($"Dependency: {val.Id} needs version range: {val.VersionRange} which does not intersect: {depToAdd.VersionRange}"); 171 | // Now we need to check to see if the current config is of a greater version than the config we want to add 172 | // If it is, set it 173 | // We can assume SharedConfig has no null fields from CollectDependencies 174 | if (p.Value[i].conf.Config?.Info?.Version > confToAdd.Config?.Info?.Version && tmp.IsSatisfied(p.Value[i].conf.Config?.Info?.Version)) 175 | confToAdd = p.Value[i].conf; 176 | // Copy additional data, only if it doesn't already exist. 177 | foreach (var pair in p.Value[i].dep.Dependency!.AdditionalData) 178 | depToAdd.AdditionalData.TryAdd(pair.Key, pair.Value); 179 | depToAdd.VersionRange = tmp; 180 | } 181 | // Add to collapsed mapping 182 | collapsed.Add(new RestoredDependencyPair 183 | { 184 | Dependency = depToAdd, 185 | Version = confToAdd.Config!.Info!.Version 186 | }, confToAdd); 187 | } 188 | return collapsed; 189 | } 190 | 191 | /// 192 | /// 193 | /// 194 | public async Task Restore() 195 | { 196 | var config = configProvider.GetConfig(); 197 | if (config is null) 198 | throw new ConfigException(Resources.ConfigNotFound); 199 | var sharedConfig = configProvider.GetSharedConfig(true); 200 | if (sharedConfig is null) 201 | throw new ConfigException(Resources.LocalConfigNotCreated); 202 | if (config.Info is null) 203 | throw new ConfigException(Resources.ConfigInfoIsNull); 204 | var myDependencies = await CollectDependencies().ConfigureAwait(false); 205 | 206 | // Collapse our dependencies into unique IDs 207 | // This can throw, based off of invalid matches 208 | var collapsed = CollapseDependencies(myDependencies); 209 | // Clear all restored dependencies to prepare, only if we find we have even a SINGLE dependency mismatch 210 | // So, first we check to see if we have everything already met in our shared file 211 | bool perfectMatch = true; 212 | foreach (var d in myDependencies) 213 | { 214 | if (sharedConfig.RestoredDependencies.Find(rvp => rvp.Dependency == d.Key.Dependency && rvp.Version == d.Value.Config?.Info?.Version) is null) 215 | { 216 | // If there is no match, we continue 217 | perfectMatch = false; 218 | break; 219 | } 220 | } 221 | if (perfectMatch) 222 | { 223 | // We have a perfect match, so we are done! 224 | OnRestore?.Invoke(this, myDependencies, collapsed); 225 | return; 226 | } 227 | sharedConfig.RestoredDependencies.Clear(); 228 | 229 | foreach (var kvp in myDependencies) 230 | { 231 | // For each of the (non-unique) dependencies, resolve each one. 232 | // However, we only want to HEADER resolve the unique dependencies 233 | await dependencyResolver.ResolveDependency(config, kvp.Key).ConfigureAwait(false); 234 | sharedConfig.RestoredDependencies.Add(kvp.Key); 235 | } 236 | foreach (var val in collapsed) 237 | await dependencyResolver.ResolveUniqueDependency(config, val).ConfigureAwait(false); 238 | // Perform additional modification here 239 | OnRestore?.Invoke(this, myDependencies, collapsed); 240 | configProvider.Commit(); 241 | 242 | // Collect dependencies and resolve them. 243 | // This should just involve grabbing them from GH or whatever URL is provided, ensuring versions match 244 | // Then, we have to add the headers to our include path (so anything that uses headers should be on include path) 245 | // In addition to modifying Android.mk and c_cpp_properties.json to match this. 246 | // We also need to ensure that our headers are in a .gitignored folder 247 | // And that all of the headers are placed into this folder with a global folder as its ID. 248 | // Therefore, technically only the root folder needs to be in our include path 249 | // Ideally, the include path modifications can be done separately from this action 250 | } 251 | } 252 | } -------------------------------------------------------------------------------- /QuestPackageManager/QuestPackageManager.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | enable 6 | false 7 | en 8 | AnyCPU;x64 9 | 10 | 11 | 12 | true 13 | 14 | 1701;1702 15 | 16 | 17 | 18 | true 19 | 20 | 1701;1702 21 | 22 | 23 | 24 | 25 | all 26 | runtime; build; native; contentfiles; analyzers; buildtransitive 27 | 28 | 29 | 30 | 31 | 32 | 33 | True 34 | True 35 | Resources.resx 36 | 37 | 38 | 39 | 40 | 41 | ResXFileCodeGenerator 42 | Resources.Designer.cs 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /QuestPackageManager/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace QuestPackageManager { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("QuestPackageManager.Resources", typeof(Resources).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | 63 | /// 64 | /// Looks up a localized string similar to id. 65 | /// 66 | internal static string _id { 67 | get { 68 | return ResourceManager.GetString("_id", resourceCulture); 69 | } 70 | } 71 | 72 | /// 73 | /// Looks up a localized string similar to newVersion. 74 | /// 75 | internal static string _newVersion { 76 | get { 77 | return ResourceManager.GetString("_newVersion", resourceCulture); 78 | } 79 | } 80 | 81 | /// 82 | /// Looks up a localized string similar to Config PackageInfo is null!. 83 | /// 84 | internal static string ConfigInfoIsNull { 85 | get { 86 | return ResourceManager.GetString("ConfigInfoIsNull", resourceCulture); 87 | } 88 | } 89 | 90 | /// 91 | /// Looks up a localized string similar to Config could not be found or created!. 92 | /// 93 | internal static string ConfigNotCreated { 94 | get { 95 | return ResourceManager.GetString("ConfigNotCreated", resourceCulture); 96 | } 97 | } 98 | 99 | /// 100 | /// Looks up a localized string similar to Config could not be found!. 101 | /// 102 | internal static string ConfigNotFound { 103 | get { 104 | return ResourceManager.GetString("ConfigNotFound", resourceCulture); 105 | } 106 | } 107 | 108 | /// 109 | /// Looks up a localized string similar to Dependency. 110 | /// 111 | internal static string Dependency { 112 | get { 113 | return ResourceManager.GetString("Dependency", resourceCulture); 114 | } 115 | } 116 | 117 | /// 118 | /// Looks up a localized string similar to Dependency Id is null!. 119 | /// 120 | internal static string DependencyIdNull { 121 | get { 122 | return ResourceManager.GetString("DependencyIdNull", resourceCulture); 123 | } 124 | } 125 | 126 | /// 127 | /// Looks up a localized string similar to Dependency is null!. 128 | /// 129 | internal static string DependencyNull { 130 | get { 131 | return ResourceManager.GetString("DependencyNull", resourceCulture); 132 | } 133 | } 134 | 135 | /// 136 | /// Looks up a localized string similar to Id. 137 | /// 138 | internal static string Id { 139 | get { 140 | return ResourceManager.GetString("Id", resourceCulture); 141 | } 142 | } 143 | 144 | /// 145 | /// Looks up a localized string similar to Info. 146 | /// 147 | internal static string Info { 148 | get { 149 | return ResourceManager.GetString("Info", resourceCulture); 150 | } 151 | } 152 | 153 | /// 154 | /// Looks up a localized string similar to Local config could not be found or created!. 155 | /// 156 | internal static string LocalConfigNotCreated { 157 | get { 158 | return ResourceManager.GetString("LocalConfigNotCreated", resourceCulture); 159 | } 160 | } 161 | 162 | /// 163 | /// Looks up a localized string similar to Name. 164 | /// 165 | internal static string Name { 166 | get { 167 | return ResourceManager.GetString("Name", resourceCulture); 168 | } 169 | } 170 | 171 | /// 172 | /// Looks up a localized string similar to Version. 173 | /// 174 | internal static string Version { 175 | get { 176 | return ResourceManager.GetString("Version", resourceCulture); 177 | } 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /QuestPackageManager/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | Config PackageInfo is null! 122 | 123 | 124 | Config could not be found or created! 125 | 126 | 127 | Config could not be found! 128 | 129 | 130 | Dependency 131 | 132 | 133 | Dependency Id is null! 134 | 135 | 136 | Dependency is null! 137 | 138 | 139 | Id 140 | 141 | 142 | Info 143 | 144 | 145 | Local config could not be found or created! 146 | 147 | 148 | Name 149 | 150 | 151 | Version 152 | 153 | 154 | id 155 | 156 | 157 | newVersion 158 | 159 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Quest Package Manager 2 | 3 | A package manager for making Quest il2cpp mods and libraries. Commonly acronymized as `QPM` or `qpm` 4 | 5 | **NOTE THAT THE CURRENT IMPLEMENTATION OF QPM IS NO LONGER RECOMMENDED FOR WIDESPREAD USE! CONSIDER USING [CLI qpm](https://github.com/QuestPackageManager/QPM.CLI) INSTEAD!** 6 | 7 | This repository will be archived soon and for all intents and purposes should be considered deprecated! 8 | 9 | ## Vocabulary 10 | 11 | - `package`: An application with a single configuration. Can contain dependencies and has some metadata. Must have an id and a version (which must be SemVer). 12 | - `dependency`: A dependency to another package. Must have an id and a version range (SemVer range). 13 | - `sharedDir`: A folder that is exposed to other packages 14 | - `externDir`: A folder that is used for installing dependencies 15 | 16 | ## Simple Guide 17 | 18 | **Note: You can use `qpm`, `qpm -?`, `qpm --help`, or `qpm -h` to view a list of commands.** 19 | 20 | ### Creating a package 21 | 22 | ```bash 23 | qpm package create "PACKAGE ID" "PACKAGE VERSION" 24 | ``` 25 | 26 | Creates a package with id: `PACKAGE ID` and version: `PACKAGE VERSION` (which must be valid SemVer). 27 | 28 | This will create a `qpm.json` folder in your current directory. This is your package configuration file and holds your `package`. 29 | 30 | This will also perform some modifications to your `.vscode/c_cpp_properties.json`, `bmbfmod.json`, and `Android.mk` files, assuming they exist. 31 | 32 | ### Adding a dependency 33 | 34 | A common use case with `qpm` is to add a dependency to a package. 35 | 36 | You must first have a valid `qpm.json` file within your current working directory, then you may call: 37 | 38 | ```bash 39 | qpm dependency add "ID" -v "VERSION RANGE" 40 | ``` 41 | 42 | Which creates a dependency with id: `ID` and version range: `VERSION RANGE`. If `-v` is not specified, version range defaults to `*` (latest available version). 43 | 44 | **NOTE: YOU SHOULD ALMOST NEVER USE A `*` VERSION RANGE! INSTEAD PREFER PROPERLY CONSTRAINED VERSION RANGES!** 45 | 46 | ### Collect Dependencies 47 | 48 | This is primarily a command used to ensure the package's collected dependencies match what you expect. 49 | 50 | ```bash 51 | qpm collect 52 | ``` 53 | 54 | Should print out a listing of dependencies that it resolved. This command does not modify your package at all. 55 | 56 | ### Collapse Dependencies 57 | 58 | This is primarily a command used to ensure the package's collected dependencies are collapsible into something you expect. 59 | 60 | ```bash 61 | qpm collapse 62 | ``` 63 | 64 | Should print out a listing of dependencies similar to [Collect Dependencies](#collect-dependencies), but with identical IDs combined. 65 | 66 | ### Restoring Dependencies 67 | 68 | After adding one or more `dependencies`, you must perform a `restore` to properly obtain them. Dependencies that are added to your `package` must be resolved in order to ensure a proper build. 69 | 70 | Dependencies are resolved using an external domain, `qpackages.com`. For more information on how to interface with this package index, see the publishing section. 71 | 72 | ```bash 73 | qpm restore 74 | ``` 75 | 76 | Which restores all dependencies listed in your package from the package index. 77 | 78 | Restore follows the following process: 79 | 80 | 1. Collects all dependencies 81 | 2. Collapses these dependencies 82 | 3. Iterates over the collected dependencies, obtaining a .so (if needed) for each one. 83 | 4. Iterates over the collapsed dependencies, obtaining header information (if needed) for each one. 84 | 5. Places all restored dependencies into `qpm.shared.json` (which is used for publishing) 85 | 86 | During steps 3 and 4, QPM will modify your `Android.mk`, if it exists, backing it up to `Android.mk.backup` first. 87 | 88 | At this point, you should be able to build! 89 | 90 | ### Publishing 91 | 92 | There are several steps required in order to ensure your package is fit to be published on `qpackages.com`. 93 | 94 | Firstly, you must perform a `qpm restore` (see [Restoring Dependencies](#restoring-dependencies)) 95 | 96 | After, you must ensure you either have the `headersOnly` additional property set to true, or you specify `soLink` and/or `debugSoLink`. 97 | 98 | Then, the url must be set to either a github repository (ex: `https://github.com/sc2ad/QuestPackageManager`) or will be interpretted as a direct download. 99 | 100 | The download specified by this link **MUST** have a `qpm.json` file that matches the version specified in your `qpm.shared.json` that you plan on publishing. 101 | 102 | **YOU MUST TELL `Sc2ad#8836` THAT YOU WISH TO HAVE A PUBLISH KEY AND GIVE HIM THE INFORMATION HE DESIRES!** When he acknowledges, you are safe to: 103 | 104 | ```bash 105 | qpm publish "your publish key here" 106 | ``` 107 | 108 | Note that you should NOT expose this publish key to ANYONE! It should be a secret in your CI runs and it will not be exposed by `qpm-rust` or equivalent tools. 109 | 110 | However, due to the nature of QPM, it is possible to publish invalid packages to QPM, which will cause people trouble. 111 | For this reason, please message `Sc2ad#8836` (you have to do this anyways) before publishing a package to QPM. 112 | 113 | ### Extra Notes 114 | 115 | `qpm package edit-extra` Can be used to add extra data to the `additionalData` property, without manual JSON edits to `qpm.json` and `qpm.shared.json`. 116 | 117 | `qpm properties-list` Can be used to list all supported properties in `additionalData`, as well as what types they are supported in. 118 | 119 | A full list will be available on the wiki, once I get around to making it. 120 | 121 | Full documentation for each command will be fully available on the wiki (once I get around to making it). 122 | A subset of this information can be found by doing `qpm --help`. 123 | 124 | **`qpm.shared.json`, `Android.mk.backup`, and `extern` should never be added to a git project!** 125 | 126 | You should explicitly add: 127 | 128 | ```yml 129 | qpm.shared.json 130 | extern/ 131 | *.backup 132 | ``` 133 | 134 | to your `.gitignore`. 135 | 136 | ### Updating a dependency 137 | 138 | As easy as: 139 | 140 | ```bash 141 | qpm dependency add "" -v "" 142 | ``` 143 | 144 | followed by: 145 | 146 | ```bash 147 | qpm restore 148 | ``` 149 | 150 | ### QPM Cache 151 | 152 | QPM caches all restored dependencies to: `/QPM_Temp/` 153 | 154 | You can forcibly clear the QPM cache by calling: 155 | 156 | ```bash 157 | qpm cache clear 158 | ``` 159 | 160 | ## Beat Saber Development 161 | 162 | QPM was built with Beat Saber Quest development in mind. 163 | This does not mean it does not work on other games, or for other platforms, but it makes Beat Saber development very easy. 164 | 165 | In order to get started, it is recommended you have a VSCode project open, with existing `.vscode/c_cpp_properties.json`, `./Android.mk`, and `./bmbfmod.json` files. 166 | 167 | **NOTE: Using the bsqm template may cause issues, since you will need to delete your `extern` folder and your `.gitmodules` file before continuing!** 168 | 169 | Then, you should start by creating your QPM package. This can be done by calling: 170 | ```bash 171 | qpm package create 172 | ``` 173 | 174 | After this, you should add a dependency to beatsaber-hook. 175 | It is good practice to specify an encompassing version range for your dependencies, so `^x.y.z` where `x.y.z` is the latest `beatsaber-hook` version. 176 | 177 | This can be found by checking the latest published package by visiting this link: [https://qpackages.com/beatsaber-hook/](https://qpackages.com/beatsaber-hook/). 178 | 179 | Once you know the version range you would like, call: 180 | 181 | ```bash 182 | qpm dependency add "beatsaber-hook" -v "" 183 | ``` 184 | 185 | In most cases, this would be all we need to do before calling a `qpm restore` and building our mod. 186 | SADLY, `beatsaber-hook` has an issue which requires us to take one additional step. We need to edit `qpm.json` and edit the dependency from: 187 | 188 | ```json 189 | "dependencies": [ 190 | { 191 | "id": "beatsaber-hook", 192 | "versionRange": "", 193 | "additionalData": {} 194 | } 195 | ] 196 | ``` 197 | 198 | to: 199 | 200 | ```json 201 | "dependencies": [ 202 | { 203 | "id": "beatsaber-hook", 204 | "versionRange": "", 205 | "additionalData": { 206 | "extraFiles": [ 207 | "src/inline-hook" 208 | ] 209 | } 210 | } 211 | ] 212 | ``` 213 | 214 | _NOW_ we can perform a: 215 | 216 | ```bash 217 | qpm restore 218 | ``` 219 | 220 | Finally, we just need to add a few lines to our `Android.mk` and we will be all set! 221 | 222 | For your main module's `LOCAL_CFLAGS` or `LOCAL_CPP_FLAGS`, add the following flag: `-isystem"./extern/libil2cpp/il2cpp/libil2cpp"`. This adds `libil2cpp` from your `extern` folder. 223 | 224 | For the `beatsaber-hook_x_y_z` module's `LOCAL_EXPORT_C_FLAGS`, add the following flags: `-DNEED_UNSAFE_CSHARP -DUNITY_2019` 225 | 226 | Add to your main module the following (assuming you have `wildcard` defined): 227 | 228 | ```mk 229 | LOCAL_SRC_FILES += $(call rwildcard,extern/beatsaber-hook/src/inline-hook,*.cpp) 230 | LOCAL_SRC_FILES += $(call rwildcard,extern/beatsaber-hook/src/inline-hook,*.c) 231 | ``` 232 | 233 | For intellisense, add `${workspaceFolder}/extern/libil2cpp/il2cpp/libil2cpp` to your `.vscode/c_cpp_properties.json`'s `includePath`. 234 | 235 | Now you should be all set to build! (You won't need to make these modifications the next time you perform a `qpm restore`) 236 | 237 | ## Plugins 238 | 239 | Coming soon, QPM will allow for plugins to allow for modifications of additional files, or perform additional actions for all commands. 240 | QPM will also allow plugins to add commands as well. 241 | Literally not for a long time though. 242 | 243 | ## Issues 244 | 245 | DM `Sc2ad#8836` on Discord or something, idk 246 | -------------------------------------------------------------------------------- /installer/information.txt: -------------------------------------------------------------------------------- 1 | QPM is a package manager for quest modding libraries. -------------------------------------------------------------------------------- /installer/installer.iss: -------------------------------------------------------------------------------- 1 | ; Script generated by the Inno Setup Script Wizard. 2 | ; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES! 3 | 4 | #define MyAppName "QPM" 5 | #define MyAppVersion "0.3.1.0" 6 | #define MyAppPublisher "Sc2ad" 7 | #define MyAppURL "https://github.com/sc2ad/QuestPackageManager" 8 | #define MyAppExeName "QPM.exe" 9 | 10 | [Setup] 11 | ; NOTE: The value of AppId uniquely identifies this application. Do not use the same AppId value in installers for other applications. 12 | ; (To generate a new GUID, click Tools | Generate GUID inside the IDE.) 13 | AppId={{6CEE605F-9C59-4E33-A388-6415297B308D} 14 | AppName={#MyAppName} 15 | AppVersion={#MyAppVersion} 16 | ;AppVerName={#MyAppName} {#MyAppVersion} 17 | AppPublisher={#MyAppPublisher} 18 | AppPublisherURL={#MyAppURL} 19 | AppSupportURL={#MyAppURL} 20 | AppUpdatesURL={#MyAppURL} 21 | DefaultDirName={autopf}\{#MyAppName} 22 | DefaultGroupName={#MyAppName} 23 | DisableProgramGroupPage=yes 24 | LicenseFile=..\LICENSE 25 | InfoAfterFile=.\information.txt 26 | ; Uncomment the following line to run in non administrative install mode (install for current user only.) 27 | ;PrivilegesRequired=lowest 28 | PrivilegesRequiredOverridesAllowed=dialog 29 | OutputDir=.\ 30 | OutputBaseFilename=QPM-installer 31 | Compression=lzma 32 | SolidCompression=yes 33 | WizardStyle=modern 34 | ArchitecturesInstallIn64BitMode=x64 35 | 36 | ; Taken from https://stackoverflow.com/a/46609047/11395424. Credit to author Wojciech Mleczek 37 | ; Adds QPM to PATH on installation and remove on uninstallation 38 | [Code] 39 | const SystemEnvironmentKey = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'; 40 | const UserEnvironmentKey = 'Environment'; 41 | 42 | function GetPathValue(var ResultStr: String): Boolean; 43 | begin 44 | if IsAdmin() 45 | then Result := RegQueryStringValue(HKEY_LOCAL_MACHINE, SystemEnvironmentKey, 'Path', ResultStr) 46 | else Result := RegQueryStringValue(HKEY_CURRENT_USER, UserEnvironmentKey, 'Path', ResultStr); 47 | end; 48 | 49 | function SetPathValue(Paths: string): Boolean; 50 | begin 51 | if IsAdmin() 52 | then Result := RegWriteStringValue(HKEY_LOCAL_MACHINE, SystemEnvironmentKey, 'Path', Paths) 53 | else Result := RegWriteStringValue(HKEY_CURRENT_USER, UserEnvironmentKey, 'Path', Paths) 54 | end; 55 | 56 | procedure EnvAddPath(Path: string); 57 | var 58 | Paths: string; 59 | begin 60 | { Retrieve current path (use empty string if entry not exists) } 61 | if not GetPathValue(Paths) 62 | then Paths := ''; 63 | 64 | { Skip if string already found in path } 65 | if Pos(';' + Uppercase(Path) + ';', ';' + Uppercase(Paths) + ';') > 0 then exit; 66 | 67 | { App string to the end of the path variable } 68 | Paths := Paths + ';'+ Path +';' 69 | 70 | { Overwrite (or create if missing) path environment variable } 71 | if SetPathValue(Paths) 72 | then Log(Format('The [%s] added to PATH: [%s]', [Path, Paths])) 73 | else Log(Format('Error while adding the [%s] to PATH: [%s]', [Path, Paths])); 74 | end; 75 | 76 | procedure EnvRemovePath(Path: string); 77 | var 78 | Paths: string; 79 | P: Integer; 80 | begin 81 | { Skip if registry entry not exists } 82 | if not GetPathValue(Paths) then 83 | exit; 84 | 85 | { Skip if string not found in path } 86 | P := Pos(';' + Uppercase(Path) + ';', ';' + Uppercase(Paths) + ';'); 87 | if P = 0 then exit; 88 | 89 | { Update path variable } 90 | Delete(Paths, P - 1, Length(Path) + 1); 91 | 92 | { Overwrite path environment variable } 93 | if SetPathValue(Paths) 94 | then Log(Format('The [%s] removed from PATH: [%s]', [Path, Paths])) 95 | else Log(Format('Error while removing the [%s] from PATH: [%s]', [Path, Paths])); 96 | end; 97 | 98 | procedure CurStepChanged(CurStep: TSetupStep); 99 | begin 100 | if CurStep = ssPostInstall 101 | then EnvAddPath(ExpandConstant('{app}')); 102 | end; 103 | 104 | procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); 105 | begin 106 | if CurUninstallStep = usPostUninstall 107 | then EnvRemovePath(ExpandConstant('{app}')); 108 | end; 109 | 110 | [Languages] 111 | Name: "english"; MessagesFile: "compiler:Default.isl" 112 | 113 | [Files] 114 | Source: "..\QPM\bin\Release\net5.0\win-x64\publish\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion 115 | Source: "..\QPM\bin\Release\net5.0\win-x64\publish\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs 116 | 117 | [UninstallRun] 118 | 119 | [UninstallDelete] 120 | Type: filesandordirs; Name: "{app}" 121 | --------------------------------------------------------------------------------