├── .gitattributes ├── .github └── workflows │ └── publish.yml ├── .gitignore ├── LICENSE ├── LICENSE-header.txt ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main └── java └── net └── minecraftforge └── mergetool ├── AnnotationVersion.java ├── ConsoleMerger.java ├── Merger.java └── Stripper.java /.gitattributes: -------------------------------------------------------------------------------- 1 | * text eol=lf 2 | *.bat text eol=crlf 3 | *.patch text eol=lf 4 | *.java text eol=lf 5 | *.gradle text eol=crlf 6 | *.png binary 7 | *.gif binary 8 | *.exe binary 9 | *.dll binary 10 | *.jar binary 11 | *.lzma binary 12 | *.zip binary 13 | *.pyd binary 14 | *.cfg text eol=lf 15 | *.py text eol=lf 16 | *.tsrg text eol=lf 17 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | 7 | permissions: 8 | contents: read 9 | 10 | jobs: 11 | build: 12 | uses: MinecraftForge/SharedActions/.github/workflows/gradle.yml@main 13 | with: 14 | java: 17 15 | gradle_tasks: "publish" 16 | artifact_name: "mergetool" 17 | secrets: 18 | DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }} 19 | PROMOTE_ARTIFACT_WEBHOOK: ${{ secrets.PROMOTE_ARTIFACT_WEBHOOK }} 20 | PROMOTE_ARTIFACT_USERNAME: ${{ secrets.PROMOTE_ARTIFACT_USERNAME }} 21 | PROMOTE_ARTIFACT_PASSWORD: ${{ secrets.PROMOTE_ARTIFACT_PASSWORD }} 22 | MAVEN_USER: ${{ secrets.MAVEN_USER }} 23 | MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.gradle/ 2 | /.idea/ 3 | /build/ 4 | /repo/ 5 | /.settings/ 6 | /bin/ 7 | .classpath 8 | .project -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | , 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /LICENSE-header.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) Forge Development LLC 2 | SPDX-License-Identifier: LGPL-2.1-only -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar 2 | import net.minecraftforge.gradleutils.PomUtils 3 | 4 | plugins { 5 | id 'java' 6 | id 'eclipse' 7 | id 'maven-publish' 8 | id 'net.minecraftforge.licenser' version '1.0.1' 9 | id 'com.github.johnrengelman.shadow' version '8.1.1' 10 | id 'com.github.ben-manes.versions' version '0.51.0' 11 | id 'net.minecraftforge.gradleutils' version '[2.3,2.4]' 12 | } 13 | 14 | group = 'net.minecraftforge' 15 | version = gradleutils.tagOffsetVersion 16 | println "Version: $version" 17 | 18 | repositories { 19 | mavenCentral() 20 | maven gradleutils.forgeMaven 21 | } 22 | 23 | license { 24 | header = file('LICENSE-header.txt') 25 | newLine = false 26 | } 27 | 28 | java { 29 | toolchain { 30 | languageVersion = JavaLanguageVersion.of(8) 31 | } 32 | withSourcesJar() 33 | } 34 | 35 | tasks.register('copyMarkers', Copy).configure { 36 | from(configurations.markers.collect { zipTree(it) } ) { 37 | into 'markers' 38 | include '**/*.class' 39 | rename { it.replace('.class', '.marker') } 40 | } 41 | includeEmptyDirs = false 42 | into project.layout.buildDirectory.dir('copyMarkers') 43 | } 44 | 45 | tasks.named('jar', Jar).configure { 46 | manifest { 47 | attributes('Main-Class': 'net.minecraftforge.mergetool.ConsoleMerger') 48 | attributes('Implementation-Version': project.version) 49 | } 50 | } 51 | 52 | tasks.named('shadowJar', ShadowJar).configure { 53 | archiveClassifier = 'fatjar' 54 | } 55 | 56 | sourceSets { 57 | main { 58 | resources { 59 | srcDirs += [tasks.named('copyMarkers')] 60 | } 61 | } 62 | } 63 | 64 | configurations { 65 | markers 66 | } 67 | 68 | dependencies { 69 | implementation(libs.bundles.asm) 70 | implementation(libs.jopt.simple) 71 | implementation(libs.srgutils) 72 | 73 | markers 'net.minecraftforge:mergetool-cpw:1.0' 74 | markers 'net.minecraftforge:mergetool-fml:1.0' 75 | markers 'net.minecraftforge:mergetool-api:1.0' 76 | } 77 | 78 | publishing { 79 | publications.register('mavenJava', MavenPublication) { 80 | from components.java 81 | 82 | artifactId = 'mergetool' 83 | 84 | pom { 85 | name = 'MergeTool' 86 | description = 'Merges two jar files together, useful for rebuilding Retroguard stripped jars.' 87 | url = 'https://github.com/MinecraftForge/MergeTool' 88 | 89 | PomUtils.setGitHubDetails(pom, 'MergeTool') 90 | 91 | license PomUtils.Licenses.LGPLv2_1 92 | 93 | developers { 94 | developer PomUtils.Developers.LexManos 95 | } 96 | } 97 | } 98 | 99 | repositories { 100 | maven gradleutils.publishingForgeMaven 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.configureondemand=true 2 | org.gradle.caching=true 3 | org.gradle.parallel=true 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MinecraftForge/MergeTool/c1e21bacb0e82c35b10b7b1df368d6a8325119f5/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command; 206 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 207 | # shell script including quotes and variable substitutions, so put them in 208 | # double quotes to make sure that they get re-expanded; and 209 | # * put everything else in single quotes, so that it's not re-expanded. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | maven { 5 | name = 'MinecraftForge' 6 | url = 'https://maven.minecraftforge.net/' 7 | } 8 | } 9 | } 10 | 11 | plugins { 12 | id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0' 13 | } 14 | 15 | dependencyResolutionManagement { 16 | versionCatalogs { 17 | libs { 18 | library('jopt-simple', 'net.sf.jopt-simple:jopt-simple:6.0-alpha-3') 19 | library('srgutils', 'net.minecraftforge:srgutils:0.5.10') 20 | 21 | version('asm', '9.7') 22 | library('asm', 'org.ow2.asm', 'asm' ).versionRef('asm') 23 | library('asm-commons', 'org.ow2.asm', 'asm-commons').versionRef('asm') 24 | library('asm-tree', 'org.ow2.asm', 'asm-tree' ).versionRef('asm') 25 | library('asm-util', 'org.ow2.asm', 'asm-util' ).versionRef('asm') 26 | bundle('asm', ['asm', 'asm-commons', 'asm-tree', 'asm-util']) 27 | } 28 | } 29 | } 30 | 31 | rootProject.name = 'MergeTool' 32 | -------------------------------------------------------------------------------- /src/main/java/net/minecraftforge/mergetool/AnnotationVersion.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Forge Development LLC 3 | * SPDX-License-Identifier: LGPL-2.1-only 4 | */ 5 | package net.minecraftforge.mergetool; 6 | 7 | import java.util.List; 8 | 9 | import org.objectweb.asm.AnnotationVisitor; 10 | import org.objectweb.asm.ClassVisitor; 11 | import org.objectweb.asm.FieldVisitor; 12 | import org.objectweb.asm.MethodVisitor; 13 | import org.objectweb.asm.Type; 14 | import net.minecraftforge.srgutils.MinecraftVersion; 15 | 16 | public enum AnnotationVersion { 17 | CPW("cpw/mods/fml/relauncher", "SideOnly", "Side", null, null, "CLIENT", "SERVER"), 18 | NMF("net/minecraftforge/fml/relauncher", "SideOnly", "Side", null, null, "CLIENT", "SERVER"), 19 | API("net/minecraftforge/api/distmarker", "OnlyIn", "Dist", "OnlyIns", "_interface", "CLIENT", "DEDICATED_SERVER"); 20 | 21 | private final String holder; 22 | private final String value; 23 | private final String repeatable; 24 | private final String interface_key; 25 | private final String client; 26 | private final String server; 27 | 28 | private static final MinecraftVersion MC_8 = MinecraftVersion.from("14w02a"); 29 | private static final MinecraftVersion MC_13 = MinecraftVersion.from("17w43a"); 30 | 31 | private AnnotationVersion(String pkg, String holder, String value, String repeatable, String interface_key, String client, String server) { 32 | this.holder = 'L' + pkg + '/' + holder + ';'; 33 | this.value = 'L' + pkg + '/' + value + ';'; 34 | this.repeatable = repeatable == null ? null : 'L' + pkg + '/' + repeatable + ';'; 35 | this.interface_key = interface_key; 36 | this.client = client; 37 | this.server = server; 38 | } 39 | 40 | public static AnnotationVersion fromVersion(String v) { 41 | if (v == null) 42 | return AnnotationVersion.NMF; 43 | 44 | try { 45 | MinecraftVersion target = MinecraftVersion.from(v); 46 | if (target.compareTo(MC_8) < 0) 47 | return AnnotationVersion.CPW; 48 | if (target.compareTo(MC_13) < 0) 49 | return AnnotationVersion.NMF; 50 | return AnnotationVersion.API; 51 | } catch (NumberFormatException e) { 52 | return sneak(e); 53 | } 54 | } 55 | 56 | public String[] getClasses() { 57 | if (this.repeatable == null) 58 | return new String[] { Type.getType(holder).getInternalName(), Type.getType(value).getInternalName() }; 59 | else 60 | return new String[] { Type.getType(holder).getInternalName(), Type.getType(value).getInternalName(), Type.getType(repeatable).getInternalName()}; 61 | } 62 | 63 | public void add(ClassVisitor cls, List clientOnly, List serverOnly) { 64 | if (this.repeatable == null || this.interface_key == null) 65 | return; 66 | 67 | if (clientOnly.size() + serverOnly.size() == 1) { 68 | if (clientOnly.size() == 1) 69 | add(cls.visitAnnotation(this.holder, true), true).visit(interface_key, Type.getObjectType(clientOnly.get(0))); 70 | else 71 | add(cls.visitAnnotation(this.holder, true), false).visit(interface_key, Type.getObjectType(serverOnly.get(0))); 72 | } else { 73 | AnnotationVisitor rep = cls.visitAnnotation(this.holder, true).visitArray("value"); 74 | clientOnly.forEach(intf -> add(rep.visitAnnotation(null, this.repeatable), true).visit(interface_key, Type.getObjectType(intf))); 75 | serverOnly.forEach(intf -> add(rep.visitAnnotation(null, this.repeatable), false).visit(interface_key, Type.getObjectType(intf))); 76 | } 77 | } 78 | 79 | public void add(ClassVisitor cls, boolean isClientOnly) { 80 | add(cls.visitAnnotation(this.holder, true), isClientOnly); 81 | } 82 | 83 | public void add(FieldVisitor fld, boolean isClientOnly) { 84 | add(fld.visitAnnotation(this.holder, true), isClientOnly); 85 | } 86 | 87 | public void add(MethodVisitor mtd, boolean isClientOnly) { 88 | add(mtd.visitAnnotation(this.holder, true), isClientOnly); 89 | } 90 | 91 | private AnnotationVisitor add(AnnotationVisitor ann, boolean isClientOnly) { 92 | ann.visitEnum("value", this.value, (isClientOnly ? this.client : this.server)); 93 | return ann; 94 | } 95 | 96 | @SuppressWarnings("unchecked") 97 | private static R sneak(Throwable e) throws E { 98 | throw (E)e; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/net/minecraftforge/mergetool/ConsoleMerger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Forge Development LLC 3 | * SPDX-License-Identifier: LGPL-2.1-only 4 | */ 5 | package net.minecraftforge.mergetool; 6 | 7 | import java.io.File; 8 | import java.io.IOException; 9 | import java.util.ArrayList; 10 | import java.util.HashSet; 11 | import java.util.List; 12 | import java.util.Locale; 13 | import java.util.Set; 14 | import java.util.function.Predicate; 15 | 16 | import joptsimple.OptionException; 17 | import joptsimple.OptionParser; 18 | import joptsimple.OptionSet; 19 | import joptsimple.OptionSpec; 20 | import joptsimple.ValueConverter; 21 | import net.minecraftforge.srgutils.IMappingFile; 22 | import net.minecraftforge.srgutils.IMappingFile.IClass; 23 | 24 | public class ConsoleMerger { 25 | private static enum Tasks { MERGE, STRIP }; 26 | private static final ValueConverter AnnotationReader = new ValueConverter() { 27 | @Override 28 | public AnnotationVersion convert(String value) { 29 | try { 30 | return AnnotationVersion.valueOf(value.toUpperCase(Locale.ENGLISH)); 31 | } catch (IllegalArgumentException e) { //Invalid argument, lets try by version, wish there was a way to know before hand. 32 | return AnnotationVersion.fromVersion(value); 33 | } 34 | } 35 | 36 | @Override 37 | public Class valueType() { 38 | return AnnotationVersion.class; 39 | } 40 | 41 | @Override 42 | public String valuePattern() { 43 | return null; 44 | } 45 | }; 46 | 47 | public static void main(String[] args) { 48 | List extra = new ArrayList<>(); 49 | Tasks task = null; 50 | 51 | for (int x = 0; x < args.length; x++) { 52 | if ("--strip".equals(args[x])) { 53 | if (task != null) 54 | throw new IllegalArgumentException("Only one task supported at a time: " + task); 55 | task = Tasks.STRIP; 56 | } else if ("--merge".equals(args[x])) { 57 | if (task != null) 58 | throw new IllegalArgumentException("Only one task supported at a time: " + task); 59 | task = Tasks.MERGE; 60 | } 61 | else 62 | extra.add(args[x]); 63 | } 64 | 65 | if (task == Tasks.MERGE || task == null) 66 | merge(extra.toArray(new String[extra.size()])); 67 | else if (task == Tasks.STRIP) 68 | strip(extra.toArray(new String[extra.size()])); 69 | } 70 | 71 | private static void merge(String[] args) { 72 | OptionParser parser = new OptionParser(); 73 | OptionSpec client = parser.accepts("client").withRequiredArg().ofType(File.class).required(); 74 | OptionSpec server = parser.accepts("server").withRequiredArg().ofType(File.class).required(); 75 | OptionSpec merged = parser.accepts("output").withRequiredArg().ofType(File.class).required(); 76 | OptionSpec inject = parser.accepts("inject").withOptionalArg().ofType(Boolean.class).defaultsTo(true); 77 | OptionSpec data = parser.accepts("keep-data"); 78 | OptionSpec meta = parser.accepts("keep-meta"); 79 | OptionSpec anno = parser.accepts("ann").withOptionalArg().ofType(AnnotationVersion.class).withValuesConvertedBy(AnnotationReader).defaultsTo(AnnotationVersion.API); 80 | OptionSpec whitelist = parser.accepts("whitelist").withRequiredArg().ofType(String.class); 81 | OptionSpec whitelistPkg = parser.accepts("whitelist-pkg").withRequiredArg().ofType(String.class); 82 | OptionSpec whitelistMap = parser.accepts("whitelist-map").withRequiredArg().ofType(File.class); 83 | OptionSpec blacklist = parser.accepts("blacklist").withRequiredArg().ofType(String.class); 84 | OptionSpec blacklistPkg = parser.accepts("blacklist-pkg").withRequiredArg().ofType(String.class); 85 | OptionSpec blacklistMap = parser.accepts("blacklist-map").withRequiredArg().ofType(File.class); 86 | OptionSpec bundled = parser.accepts("bundled"); 87 | 88 | try { 89 | OptionSet options = parser.parse(args); 90 | 91 | File client_jar = options.valueOf(client); 92 | File server_jar = options.valueOf(server); 93 | File merged_jar = options.valueOf(merged); 94 | 95 | Merger merge = new Merger(client_jar, server_jar, merged_jar); 96 | 97 | if (merged_jar.exists() && !merged_jar.delete()) 98 | System.out.println("Could not delete output file: " + merged_jar); 99 | 100 | if (options.has(anno)) 101 | merge.annotate(options.valueOf(anno), !options.has(inject) || options.valueOf(inject)); 102 | 103 | if (options.has(data)) 104 | merge.keepData(); 105 | 106 | if (options.has(meta)) 107 | merge.keepMeta(); 108 | 109 | if (options.has(bundled)) 110 | merge.bundledServerJar(); 111 | 112 | Predicate filter = null; 113 | if (options.has(whitelist) || options.has(whitelistMap)) { 114 | Set classes = loadList(options.valuesOf(whitelist), options.valuesOf(whitelistMap)); 115 | if (!classes.isEmpty()) 116 | filter = classes::contains; 117 | } 118 | 119 | if (options.has(whitelistPkg)) { 120 | Set pkgs = loadPackages(options.valuesOf(whitelistPkg)); 121 | Predicate prefixes = name -> { 122 | int idx = name.lastIndexOf('/'); 123 | return idx == -1 ? pkgs.contains("/") : pkgs.contains(name.substring(0, idx)); 124 | }; 125 | 126 | if (filter == null) 127 | filter = prefixes; 128 | else 129 | filter = filter.or(prefixes); 130 | } 131 | 132 | if (filter == null) 133 | filter = name -> true; 134 | 135 | if (options.has(blacklist) || options.has(blacklistMap)) { 136 | Set classes = loadList(options.valuesOf(blacklist), options.valuesOf(blacklistMap)); 137 | if (!classes.isEmpty()) 138 | filter.and(name -> !classes.contains(name)); 139 | } 140 | 141 | if (options.has(blacklistPkg)) { 142 | Set pkgs = loadPackages(options.valuesOf(blacklistPkg)); 143 | filter.and(name -> { 144 | int idx = name.lastIndexOf('/'); 145 | return idx == -1 ? !pkgs.contains("/") : !pkgs.contains(name.substring(0, idx)); 146 | }); 147 | } 148 | 149 | merge.filter(filter); 150 | 151 | merge.process(); 152 | } catch (OptionException e) { 153 | System.out.println("Usage: ConsoleMerger --merge --client --server --output [--ann CPW|NMF|API] [--keep-data] [--keep-meta]"); 154 | e.printStackTrace(); 155 | sneak(e); 156 | } catch (IOException e) { 157 | e.printStackTrace(); 158 | sneak(e); 159 | } 160 | } 161 | 162 | private static void strip(String[] args) { 163 | OptionParser parser = new OptionParser(); 164 | OptionSpec input = parser.accepts("input").withRequiredArg().ofType(File.class).required(); 165 | OptionSpec output = parser.accepts("output").withRequiredArg().ofType(File.class).required(); 166 | OptionSpec data = parser.accepts("data").withRequiredArg().ofType(File.class).required(); 167 | 168 | try { 169 | OptionSet options = parser.parse(args); 170 | 171 | File input_jar = options.valueOf(input).getAbsoluteFile(); 172 | File output_jar = options.valueOf(output).getAbsoluteFile(); 173 | 174 | try { 175 | System.out.println("Input: " + input_jar); 176 | System.out.println("Output: " + output_jar); 177 | Stripper strip = new Stripper(); 178 | 179 | for (File dataF : options.valuesOf(data)) { 180 | System.out.println("Data: " + dataF.getAbsoluteFile()); 181 | strip.loadData(dataF); 182 | } 183 | 184 | if (output_jar.exists() && !output_jar.delete()) 185 | System.out.println("Could not delete output file: " + output_jar); 186 | 187 | strip.process(input_jar, output_jar); 188 | } catch (IOException e) { 189 | e.printStackTrace(); 190 | } 191 | } catch (OptionException e) { 192 | System.out.println("Usage: ConsoleMerger --strip --input --output --data ..."); 193 | e.printStackTrace(); 194 | } 195 | } 196 | 197 | 198 | private static Set loadList(List strings, List files) throws IOException { 199 | Set classes = new HashSet<>(); 200 | classes.addAll(strings); 201 | 202 | for (File value : files) { 203 | IMappingFile map = IMappingFile.load(value); 204 | for (IClass cls : map.getClasses()) 205 | classes.add(cls.getOriginal()); 206 | } 207 | 208 | return classes; 209 | } 210 | 211 | private static Set loadPackages(List strings) { 212 | Set pkgs = new HashSet<>(); 213 | for (String value : strings) { 214 | if (!value.endsWith("/")) 215 | value += '/'; 216 | pkgs.add(value); 217 | } 218 | return pkgs; 219 | } 220 | 221 | @SuppressWarnings("unchecked") 222 | private static R sneak(Throwable e) throws E { 223 | throw (E)e; 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /src/main/java/net/minecraftforge/mergetool/Merger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Forge Development LLC 3 | * SPDX-License-Identifier: LGPL-2.1-only 4 | */ 5 | package net.minecraftforge.mergetool; 6 | 7 | import org.objectweb.asm.ClassReader; 8 | import org.objectweb.asm.ClassWriter; 9 | import org.objectweb.asm.tree.AbstractInsnNode; 10 | import org.objectweb.asm.tree.ClassNode; 11 | import org.objectweb.asm.tree.FieldNode; 12 | import org.objectweb.asm.tree.InnerClassNode; 13 | import org.objectweb.asm.tree.LineNumberNode; 14 | import org.objectweb.asm.tree.MethodNode; 15 | 16 | import java.io.BufferedOutputStream; 17 | import java.io.BufferedReader; 18 | import java.io.ByteArrayOutputStream; 19 | import java.io.File; 20 | import java.io.FileInputStream; 21 | import java.io.FileOutputStream; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.io.InputStreamReader; 25 | import java.io.OutputStream; 26 | import java.util.ArrayList; 27 | import java.util.Collections; 28 | import java.util.Comparator; 29 | import java.util.HashSet; 30 | import java.util.Hashtable; 31 | import java.util.List; 32 | import java.util.Map; 33 | import java.util.Map.Entry; 34 | import java.util.Objects; 35 | import java.util.Set; 36 | import java.util.function.BiPredicate; 37 | import java.util.function.Function; 38 | import java.util.function.Predicate; 39 | import java.util.jar.Attributes; 40 | import java.util.jar.JarFile; 41 | import java.util.jar.Manifest; 42 | import java.util.zip.ZipEntry; 43 | import java.util.zip.ZipFile; 44 | import java.util.zip.ZipInputStream; 45 | import java.util.zip.ZipOutputStream; 46 | 47 | public class Merger { 48 | private static final boolean DEBUG = false; 49 | 50 | private final File client; 51 | private final File server; 52 | private final File merged; 53 | private AnnotationVersion annotation = null; 54 | private boolean annotationInject = true; 55 | private FieldName FIELD = new FieldName(); 56 | private MethodDesc METHOD = new MethodDesc(); 57 | private HashSet whitelist = new HashSet<>(); 58 | private Predicate filter = name -> this.whitelist.isEmpty() || this.whitelist.contains(name); 59 | private boolean copyData = false; 60 | private boolean keepMeta = false; 61 | private boolean bundledServerJar = false; 62 | 63 | public Merger(File client, File server, File merged) { 64 | this.client = client; 65 | this.server = server; 66 | this.merged = merged; 67 | } 68 | 69 | public Merger annotate(AnnotationVersion ano, boolean inject) { 70 | this.annotation = ano; 71 | this.annotationInject = inject; 72 | return this; 73 | } 74 | 75 | public Merger whitelist(String file) { 76 | this.whitelist.add(file); 77 | return this; 78 | } 79 | 80 | /* 81 | * The predicate is called with the class name in binary format {essentially the path to the class file, minus the .class suffix) 82 | * Anything that does not return true from this predicate will be filtered out. 83 | */ 84 | public Merger filter(Predicate filter) { 85 | this.filter = filter; 86 | return this; 87 | } 88 | 89 | public Merger keepData() { 90 | this.copyData = true; 91 | return this; 92 | } 93 | 94 | public Merger skipData() { 95 | this.copyData = false; 96 | return this; 97 | } 98 | 99 | public Merger keepMeta() { 100 | this.keepMeta = true; 101 | return this; 102 | } 103 | 104 | public Merger skipMeta() { 105 | this.keepMeta = false; 106 | return this; 107 | } 108 | 109 | public Merger bundledServerJar() { 110 | this.bundledServerJar = true; 111 | return this; 112 | } 113 | 114 | public void process() throws IOException { 115 | try (ZipOutputStream outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(this.merged)))) { 116 | Set added = new HashSet<>(); 117 | Map cClasses = getClassEntries(this.client, outJar, added); 118 | Map sClasses; 119 | if (this.bundledServerJar) 120 | sClasses = getBundledClassEntries(this.server, outJar, null); 121 | else 122 | sClasses = getClassEntries(this.server, outJar, null); //Skip data from the server, as it contains libraries. 123 | 124 | for (Entry entry : cClasses.entrySet()) { 125 | String name = entry.getKey(); 126 | 127 | if (!this.filter.test(name)) 128 | continue; 129 | 130 | byte[] cData = entry.getValue(); 131 | byte[] sData = sClasses.get(name); 132 | 133 | if (sData == null) { 134 | if (DEBUG) 135 | System.out.println("Copy class c->s : " + name); 136 | copyClass(name, cData, outJar, true); 137 | } else { 138 | if (DEBUG) 139 | System.out.println("Processing class: " + name); 140 | 141 | sClasses.remove(name); 142 | 143 | byte[] data = processClass(cData, sData); 144 | 145 | outJar.putNextEntry(getNewEntry(name + ".class")); 146 | outJar.write(data); 147 | } 148 | } 149 | 150 | for (Entry entry : sClasses.entrySet()) { 151 | String name = entry.getKey(); 152 | if (!this.filter.test(name)) 153 | continue; 154 | 155 | if (DEBUG) 156 | System.out.println("Copy class s->c : " + name); 157 | copyClass(name, entry.getValue(), outJar, false); 158 | } 159 | 160 | if (this.annotation != null && this.annotationInject) { 161 | for (String cls : this.annotation.getClasses()) { 162 | byte[] data = getResourceBytes(cls); 163 | 164 | outJar.putNextEntry(getNewEntry(cls + ".class")); 165 | outJar.write(data); 166 | } 167 | } 168 | 169 | } 170 | } 171 | 172 | private ZipEntry getNewEntry(String name) { 173 | ZipEntry ret = new ZipEntry(name); 174 | ret.setTime(0x92D6688800L); //Stabilize output as java will use current time if we don't set this, we can't use 0 as older java versions output different jars for values less then 1980 175 | return ret; 176 | } 177 | 178 | private void copyClass(String name, byte[] entry, ZipOutputStream outJar, boolean isClientOnly) throws IOException { 179 | ClassReader reader = new ClassReader(entry); 180 | ClassNode classNode = new ClassNode(); 181 | 182 | reader.accept(classNode, 0); 183 | 184 | if (this.annotation != null) 185 | this.annotation.add(classNode, isClientOnly); 186 | 187 | ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); 188 | classNode.accept(writer); 189 | 190 | byte[] data = writer.toByteArray(); 191 | 192 | outJar.putNextEntry(getNewEntry(name + ".class")); 193 | outJar.write(data); 194 | } 195 | 196 | private Map getClassEntries(File inFile, ZipOutputStream output, Set added) throws IOException { 197 | try (ZipInputStream zin = new ZipInputStream(new FileInputStream(inFile))) { 198 | return getClassEntries(zin, output, added); 199 | } 200 | } 201 | 202 | private Map getClassEntries(ZipInputStream input, ZipOutputStream output, Set added) throws IOException { 203 | Map ret = new Hashtable<>(); 204 | for (ZipEntry entry; (entry = input.getNextEntry()) != null; ) { 205 | String entryName = entry.getName(); 206 | if (!entry.isDirectory() && entryName.endsWith(".class") && !entryName.startsWith(".")) { 207 | entryName = entryName.substring(0, entryName.length() - 6); 208 | byte[] data = readFully(input); 209 | ret.put(entryName, data); 210 | } else if (this.copyData && added != null && !added.contains(entryName)) { 211 | if (!this.keepMeta && entryName.startsWith("META-INF")) 212 | continue; 213 | 214 | if (entry.isDirectory()) { 215 | //Skip directories, they arnt required. 216 | //output.putNextEntry(getNewEntry(entryName)); //New entry to reset time 217 | added.add(entryName); 218 | } else { 219 | output.putNextEntry(getNewEntry(entryName)); 220 | copy(input, output); 221 | added.add(entryName); 222 | } 223 | } 224 | } 225 | return ret; 226 | } 227 | 228 | private static final Attributes.Name BUNDLER_FORMAT = new Attributes.Name("Bundler-Format"); 229 | private static final String VERSIONS_LIST = "META-INF/versions.list"; 230 | private Map getBundledClassEntries(File inFile, ZipOutputStream output, Set added) throws IOException { 231 | try (ZipFile zin = new ZipFile(inFile)) { 232 | ZipEntry mfEntry = zin.getEntry(JarFile.MANIFEST_NAME); 233 | if (mfEntry == null) 234 | throw new IOException("Invalid bundled server jar, Missing " + JarFile.MANIFEST_NAME); 235 | 236 | Manifest mf = new Manifest(zin.getInputStream(mfEntry)); 237 | String format = mf.getMainAttributes().getValue(BUNDLER_FORMAT); 238 | if (format == null) 239 | throw new IOException("Invalid bundled server jar, Missing " + BUNDLER_FORMAT + " manifest entry"); 240 | 241 | if (!"1.0".equals(format)) 242 | throw new IOException("Unsupported Bundler-Format: " + format); 243 | 244 | ZipEntry verEntry = zin.getEntry(VERSIONS_LIST); 245 | if (verEntry == null) 246 | throw new IllegalStateException("Bundled Jar missing " + VERSIONS_LIST); 247 | 248 | List verList = readList(zin.getInputStream(verEntry)); 249 | if (verList.size() != 1) 250 | throw new IllegalStateException("Invalid bundler " + VERSIONS_LIST + " file, " + verList.size() + " entries, expected 1"); 251 | 252 | String serverJarName = "META-INF/versions/" + verList.get(0).path; 253 | ZipEntry serverJarEntry = zin.getEntry(serverJarName); 254 | if (serverJarEntry == null) 255 | throw new IOException("Invalid bundled server jar, Missing jar entry " + serverJarName); 256 | 257 | try (ZipInputStream server = new ZipInputStream(zin.getInputStream(serverJarEntry))) { 258 | return getClassEntries(server, output, added); 259 | } 260 | } 261 | } 262 | 263 | private static List readList(InputStream in) throws IOException { 264 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { 265 | List ret = new ArrayList<>(); 266 | while (reader.ready()) { 267 | String line = reader.readLine(); 268 | String[] pts = line.split("\t"); 269 | if (pts.length != 3) 270 | throw new IOException("Invalid bunder list line: " + line); 271 | ret.add(new BundleEntry(pts[0], pts[1], pts[2])); 272 | } 273 | return ret; 274 | } 275 | } 276 | 277 | private byte[] readFully(InputStream stream) throws IOException { 278 | ByteArrayOutputStream buf = new ByteArrayOutputStream(); 279 | copy(stream, buf); 280 | return buf.toByteArray(); 281 | } 282 | 283 | private static void copy(InputStream input, OutputStream output) throws IOException { 284 | byte[] data = new byte[4096]; 285 | int len; 286 | do { 287 | len = input.read(data); 288 | if (len > 0) 289 | output.write(data, 0, len); 290 | } while (len != -1); 291 | } 292 | 293 | private byte[] processClass(byte[] cIn, byte[] sIn) { 294 | ClassNode cClassNode = getClassNode(cIn); 295 | ClassNode sClassNode = getClassNode(sIn); 296 | 297 | processFields(cClassNode, sClassNode); 298 | processMethods(cClassNode, sClassNode); 299 | processInners(cClassNode, sClassNode); 300 | processInterfaces(cClassNode, sClassNode); 301 | 302 | ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); 303 | cClassNode.accept(writer); 304 | return writer.toByteArray(); 305 | } 306 | 307 | private boolean innerMatches(InnerClassNode o, InnerClassNode o2) { 308 | return equals(o.innerName, o2.innerName) && 309 | equals(o.name, o2.name) && 310 | equals(o.outerName, o2.outerName); 311 | } 312 | 313 | private boolean equals(Object o1, Object o2) { 314 | return o1 == null ? o2 == null : o2 == null ? false : o1.equals(o2); 315 | } 316 | 317 | private void processInners(ClassNode cClass, ClassNode sClass) { 318 | List cIners = cClass.innerClasses; 319 | List sIners = sClass.innerClasses; 320 | 321 | for (InnerClassNode n : cIners) { 322 | if (!sIners.stream().anyMatch(e -> innerMatches(e, n))) 323 | sIners.add(n); 324 | } 325 | 326 | for (InnerClassNode n : sIners) { 327 | if (!cIners.stream().anyMatch(e -> innerMatches(e, n))) 328 | cIners.add(n); 329 | } 330 | } 331 | 332 | private void processInterfaces(ClassNode cClass, ClassNode sClass) { 333 | List cIntfs = cClass.interfaces; 334 | List sIntfs = sClass.interfaces; 335 | List cOnly = new ArrayList<>(); 336 | List sOnly = new ArrayList<>(); 337 | 338 | for (String n : cIntfs) { 339 | if (!sIntfs.contains(n)) { 340 | sIntfs.add(n); 341 | cOnly.add(n); 342 | } 343 | } 344 | 345 | for (String n : sIntfs) { 346 | if (!cIntfs.contains(n)) { 347 | cIntfs.add(n); 348 | sOnly.add(n); 349 | } 350 | } 351 | 352 | Collections.sort(cIntfs); //Sort things, we're in obf territory but should stabilize things. 353 | Collections.sort(sIntfs); 354 | 355 | if (this.annotation != null && !cOnly.isEmpty() || !sOnly.isEmpty()) { 356 | this.annotation.add(cClass, cOnly, sOnly); 357 | this.annotation.add(sClass, cOnly, sOnly); 358 | } 359 | } 360 | 361 | private ClassNode getClassNode(byte[] data) { 362 | ClassReader reader = new ClassReader(data); 363 | ClassNode classNode = new ClassNode(); 364 | reader.accept(classNode, 0); 365 | return classNode; 366 | } 367 | 368 | private static BiPredicate curry(Function function, BiPredicate primary) { 369 | return (a,b) -> primary.test(function.apply(a), function.apply(b)); 370 | } 371 | 372 | private void processFields(ClassNode cClass, ClassNode sClass) { 373 | merge(cClass.name, sClass.name, cClass.fields, sClass.fields, curry(FIELD, Objects::equals), FIELD, FIELD, FIELD); 374 | } 375 | 376 | private void processMethods(ClassNode cClass, ClassNode sClass) { 377 | merge(cClass.name, sClass.name, cClass.methods, sClass.methods, curry(METHOD, Objects::equals), METHOD, METHOD, METHOD); 378 | } 379 | 380 | private interface MemberAnnotator { 381 | T process(T member, boolean isClient); 382 | } 383 | 384 | private class FieldName implements Function, MemberAnnotator, Comparator { 385 | public String apply(FieldNode in) { 386 | return in == null ? "null" : in.name; 387 | } 388 | 389 | public FieldNode process(FieldNode field, boolean isClient) { 390 | if (Merger.this.annotation != null) 391 | Merger.this.annotation.add(field, isClient); 392 | return field; 393 | } 394 | 395 | @Override 396 | public int compare(FieldNode a, FieldNode b) { 397 | if (a == b) return 0; 398 | if (a == null) return 1; 399 | if (b == null) return -1; 400 | return a.name.compareTo(b.name); 401 | } 402 | } 403 | 404 | private class MethodDesc implements Function, MemberAnnotator, Comparator { 405 | public String apply(MethodNode node) { 406 | return node == null ? "null" : node.name + node.desc; 407 | } 408 | 409 | public MethodNode process(MethodNode node, boolean isClient) { 410 | if (Merger.this.annotation != null) 411 | Merger.this.annotation.add(node, isClient); 412 | return node; 413 | } 414 | 415 | private int findLine(MethodNode member) { 416 | for (int x = 0; x < member.instructions.size(); x++) { 417 | AbstractInsnNode insn = member.instructions.get(x); 418 | if (insn instanceof LineNumberNode) 419 | return ((LineNumberNode)insn).line; 420 | } 421 | return Integer.MAX_VALUE; 422 | } 423 | 424 | @Override 425 | public int compare(MethodNode a, MethodNode b) { 426 | if (a == b) return 0; 427 | if (a == null) return 1; 428 | if (b == null) return -1; 429 | return findLine(a) - findLine(b); 430 | } 431 | } 432 | 433 | private void merge(String cName, String sName, List client, List server, BiPredicate eq, 434 | MemberAnnotator annotator, Function toString, Comparator compare) { 435 | // adding null to the end to not handle the index overflow in a special way 436 | client.add(null); 437 | server.add(null); 438 | List common = new ArrayList<>(); 439 | for(T ct : client) { 440 | for (T st : server) { 441 | if (eq.test(ct, st)) { 442 | common.add(ct); 443 | break; 444 | } 445 | } 446 | } 447 | 448 | int i = 0, mi = 0; 449 | for(; i < client.size(); i++) { 450 | T ct = client.get(i); 451 | T st = server.get(i); 452 | T mt = common.get(mi); 453 | 454 | if (eq.test(ct, st)) { 455 | mi++; 456 | if (!eq.test(ct, mt)) 457 | throw new IllegalStateException("merged list is in bad state: " + toString.apply(ct) + " " + toString.apply(st) + " " + toString.apply(mt)); 458 | if (DEBUG) 459 | System.out.printf("%d/%d %d/%d Both Shared : %s %s\n", i, client.size(), mi, common.size(), sName, toString.apply(st)); 460 | 461 | } else if(eq.test(st, mt)) { 462 | server.add(i, annotator.process(ct, true)); 463 | if (DEBUG) 464 | System.out.printf("%d/%d %d/%d Server *add* : %s %s\n", i, client.size(), mi, common.size(), sName, toString.apply(ct)); 465 | } else if (eq.test(ct, mt)) { 466 | client.add(i, annotator.process(st, false)); 467 | if (DEBUG) 468 | System.out.printf("%d/%d %d/%d Client *add* : %s %s\n", i, client.size(), mi, common.size(), cName, toString.apply(st)); 469 | } else { // Both server and client add a new method before we get to the next common method... Lets try and prioritize one. 470 | int diff = compare.compare(ct, st); 471 | if (diff > 0) { 472 | client.add(i, annotator.process(st, false)); 473 | if (DEBUG) 474 | System.out.printf("%d/%d %d/%d Client *add* : %s %s\n", i, client.size(), mi, common.size(), cName, toString.apply(st)); 475 | } else { /* if (diff < 0) */ //Technically this should be <0 and we special case when they can't agree who goes first.. but for now just push the client's first. 476 | server.add(i, annotator.process(ct, true)); 477 | if (DEBUG) 478 | System.out.printf("%d/%d %d/%d Server *add* : %s %s\n", i, client.size(), mi, common.size(), sName, toString.apply(ct)); 479 | } 480 | } 481 | } 482 | 483 | if (i < server.size() || mi < common.size() || (client.size() != server.size())) 484 | throw new IllegalStateException("merged list is in bad state: " + i + " " + mi); 485 | 486 | // removing the null 487 | client.remove(client.size() - 1); 488 | server.remove(server.size() - 1); 489 | } 490 | 491 | private byte[] getResourceBytes(String path) throws IOException { 492 | // If we're in the built jar, use the relocated classes {prevents them being 493 | InputStream stream = Merger.class.getResourceAsStream("/markers/" + path + ".marker"); 494 | // If not, then try and get them from the classpath 495 | if (stream == null) 496 | stream = Merger.class.getResourceAsStream("/" + path + ".class"); 497 | if (stream == null) 498 | throw new IllegalStateException("Could not find marker files: " + path); 499 | 500 | try { 501 | return readFully(stream); 502 | } finally { 503 | stream.close(); 504 | } 505 | } 506 | 507 | 508 | @SuppressWarnings("unused") 509 | private static class BundleEntry { 510 | public final String hash; 511 | public final String artifact; 512 | public final String path; 513 | 514 | private BundleEntry(String hash, String artifact, String path) { 515 | this.hash = hash; 516 | this.artifact = artifact; 517 | this.path = path; 518 | } 519 | } 520 | } 521 | -------------------------------------------------------------------------------- /src/main/java/net/minecraftforge/mergetool/Stripper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Forge Development LLC 3 | * SPDX-License-Identifier: LGPL-2.1-only 4 | */ 5 | package net.minecraftforge.mergetool; 6 | 7 | import java.io.File; 8 | import java.io.FileInputStream; 9 | import java.io.FileOutputStream; 10 | import java.io.IOException; 11 | import java.nio.file.Files; 12 | import java.util.HashSet; 13 | import java.util.Iterator; 14 | import java.util.Set; 15 | import java.util.zip.ZipEntry; 16 | import java.util.zip.ZipInputStream; 17 | import java.util.zip.ZipOutputStream; 18 | 19 | import org.objectweb.asm.ClassReader; 20 | import org.objectweb.asm.ClassWriter; 21 | import org.objectweb.asm.tree.AnnotationNode; 22 | import org.objectweb.asm.tree.ClassNode; 23 | 24 | public class Stripper { 25 | private Set classes = new HashSet<>(); 26 | private Set targets = new HashSet<>(); 27 | 28 | /* 29 | * Data files list whole classes, or methods that should be stripped out. 30 | * Comments are supported, anything following the # character will be stripped 31 | * Empty lines are ignored. 32 | * If the line starts with \t the \t will be stripped 33 | * You can strip annotations from classes, or methods 34 | */ 35 | public void loadData(File file) throws IOException { 36 | Files.lines(file.toPath()).forEach(line -> { 37 | int idx = line.indexOf('#'); 38 | if (idx == 0 || line.isEmpty()) return; 39 | if (idx != -1) line = line.substring(0, idx - 1); 40 | if (line.charAt(0) == '\t') line = line.substring(1); 41 | String[] pts = (line.trim() + " ").split(" ", -1); 42 | classes.add(pts[0]); 43 | if (pts.length > 1) 44 | targets.add(pts[0] + ' ' + pts[1]); 45 | else 46 | targets.add(pts[0]); 47 | }); 48 | } 49 | 50 | public void process(File input, File output) throws IOException { 51 | if (output.exists()) output.delete(); 52 | if (!output.getParentFile().exists()) output.getParentFile().mkdirs(); 53 | output.createNewFile(); 54 | 55 | Set types = new HashSet<>(); 56 | for (AnnotationVersion an : AnnotationVersion.values()) { 57 | for (String cls : an.getClasses()) 58 | types.add('L' + cls + ';'); 59 | } 60 | 61 | try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input)); 62 | ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output))) { 63 | ZipEntry entry; 64 | while ((entry = zis.getNextEntry()) != null) { 65 | ZipEntry next = new ZipEntry(entry.getName()); 66 | next.setTime(entry.getTime()); 67 | next.setLastModifiedTime(entry.getLastModifiedTime()); 68 | zos.putNextEntry(next); 69 | if (!entry.getName().endsWith(".class") || !classes.contains(entry.getName().substring(0, entry.getName().length() - 6))) { 70 | int read; 71 | byte[] buf = new byte[0x100]; 72 | while ((read = zis.read(buf, 0, buf.length)) != -1) 73 | zos.write(buf, 0, read); 74 | } else { 75 | ClassReader reader = new ClassReader(zis); 76 | ClassNode node = new ClassNode(); 77 | reader.accept(node, 0); 78 | 79 | if (node.methods != null) { 80 | node.methods.forEach(mtd -> { 81 | if (targets.contains(node.name + ' ' + mtd.name + mtd.desc)) { 82 | if (mtd.visibleAnnotations != null) { 83 | Iterator itr = mtd.visibleAnnotations.iterator(); 84 | while (itr.hasNext()) { 85 | if (types.contains(itr.next().desc)) 86 | itr.remove(); 87 | } 88 | } 89 | } 90 | }); 91 | } 92 | 93 | if (node.visibleAnnotations != null) { 94 | Iterator itr = node.visibleAnnotations.iterator(); 95 | while (itr.hasNext()) { 96 | if (types.contains(itr.next().desc)) 97 | itr.remove(); 98 | } 99 | } 100 | 101 | ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); 102 | node.accept(writer); 103 | zos.write(writer.toByteArray()); 104 | } 105 | zos.closeEntry(); 106 | } 107 | } 108 | } 109 | } 110 | --------------------------------------------------------------------------------