├── .devcontainer ├── devcontainer.json └── post-create.sh ├── .github ├── FUNDING.yml └── workflows │ ├── main.yml │ └── publish.yml ├── .gitignore ├── .gitpod.yml ├── CMakeLists.txt ├── COPYING ├── README.md ├── emscriptenbuild ├── .gitignore ├── build.sh ├── post-async.js ├── post.js └── pre.js ├── karma.conf-async.js ├── karma.conf.js ├── libgit2patchedfiles ├── examples │ ├── add.c │ ├── checkout.c │ ├── commit.c │ ├── common.h │ ├── lg2.c │ ├── push.c │ ├── reset.c │ ├── revert.c │ ├── stash.c │ └── status.c └── src │ └── transports │ ├── emscriptenhttp-async.c │ └── emscriptenhttp.c ├── package-lock.json ├── package.json ├── preparepublishnpm.sh ├── setup.sh ├── test-browser-async ├── lg2_async.js ├── lg2_async.wasm └── test.spec.js ├── test-browser ├── githttpserver.js ├── lg2.js ├── lg2.wasm ├── manycommits.spec.js ├── manycommits.worker.js ├── remote.spec.js ├── stashpop.spec.js ├── test.spec.js └── worker.js ├── test ├── .gitignore ├── checkout.spec.js ├── common.js ├── conflict.spec.js ├── fetch.spec.js ├── lg2.js ├── lg2.wasm ├── nodefs.spec.js └── revert.spec.js └── web-test-runner.config.js /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "postCreateCommand": "/workspaces/wasm-git/.devcontainer/post-create.sh", 3 | "customizations": { 4 | "vscode": { 5 | "extensions": [ 6 | "dtsvet.vscode-wasm", 7 | "ms-vscode.cpptools-extension-pack", 8 | "github.vscode-github-actions" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /.devcontainer/post-create.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | curl https://wasmtime.dev/install.sh -sSf | bash 3 | npm install 4 | sh setup.sh 5 | 6 | git clone https://github.com/emscripten-core/emsdk.git 7 | cd emsdk 8 | git pull 9 | ./emsdk install latest 10 | ./emsdk activate latest 11 | cd .. 12 | 13 | npx playwright install-deps 14 | npx playwright install -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [petersalomonsen] 4 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: [ master ] 5 | pull_request: 6 | branches: [ master ] 7 | jobs: 8 | detectonly: 9 | name: Detect use of .only 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Detect use of .only 14 | run: | 15 | grep -rq --include '*.spec.js' \.only\( . && echo 'You have .only() in your tests!' && exit 1 16 | exit 0 17 | default: 18 | name: "Default" 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Default 23 | run: | 24 | npm install 25 | npx playwright install-deps 26 | npx playwright install 27 | sh setup.sh 28 | git clone https://github.com/emscripten-core/emsdk.git 29 | cd emsdk 30 | ./emsdk install latest 31 | ./emsdk activate latest 32 | cd .. 33 | source ./emsdk/emsdk_env.sh 34 | cd emscriptenbuild 35 | ./build.sh Release 36 | cd .. 37 | set -e 38 | npm run test 39 | npm run test-browser 40 | asyncify: 41 | name: Asyncify 42 | runs-on: ubuntu-latest 43 | steps: 44 | - uses: actions/checkout@v2 45 | - name: Default 46 | run: | 47 | npm install 48 | npx playwright install-deps 49 | npx playwright install 50 | sh setup.sh 51 | git clone https://github.com/emscripten-core/emsdk.git 52 | cd emsdk 53 | ./emsdk install latest 54 | ./emsdk activate latest 55 | cd .. 56 | source ./emsdk/emsdk_env.sh 57 | cd emscriptenbuild 58 | ./build.sh Release-async 59 | cd .. 60 | set -e 61 | npm run test-browser-async 62 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | on: 3 | push: 4 | branches: [ master ] 5 | pull_request: 6 | branches: [ master ] 7 | jobs: 8 | default: 9 | name: "Default" 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | - uses: actions/setup-node@v3 14 | with: 15 | node-version: '18.x' 16 | registry-url: 'https://registry.npmjs.org' 17 | - name: Default 18 | run: | 19 | npm install 20 | npx playwright install-deps 21 | npx playwright install 22 | sh setup.sh 23 | git clone https://github.com/emscripten-core/emsdk.git 24 | cd emsdk 25 | ./emsdk install latest 26 | ./emsdk activate latest 27 | cd .. 28 | source ./emsdk/emsdk_env.sh 29 | cd emscriptenbuild 30 | ./build.sh Release 31 | ./build.sh Release-async 32 | cd .. 33 | set -e 34 | npm run test 35 | export VERSION=`npm view wasm-git dist-tags.latest` 36 | export NEWVERSION=`node -p "require('./package.json').version"` 37 | echo $VERSION $NEWVERSION 38 | ./preparepublishnpm.sh 39 | PACKAGEFILE=`npm pack | tail -n 1` 40 | tar -xvzf $PACKAGEFILE 41 | echo "run browser tests with npm package" 42 | rm test-browser/lg2.* 43 | cp package/lg2.* test-browser/ 44 | npm run test-browser 45 | rm test-browser-async/lg2_async.* 46 | cp package/lg2_async.* test-browser-async/ 47 | npm run test-browser-async 48 | BRANCH="$(git rev-parse --abbrev-ref HEAD)" 49 | if [[ "$VERSION" = "$NEWVERSION" || "$BRANCH" != "master" ]]; then 50 | echo "version change is $VERSION->$NEWVERSION, branch is $BRANCH, not publishing, only dry-run" 51 | npm publish --dry-run 52 | else 53 | npm publish 54 | fi 55 | env: 56 | NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }} 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | libgit2 2 | libgit2-* 3 | wasm-git-*.tgz 4 | lg2.js 5 | lg2.wasm 6 | lg2_async.js 7 | lg2_async.wasm 8 | .DS_Store 9 | .vscode 10 | node_modules 11 | package 12 | .idea 13 | emsdk 14 | nodefsclonetest 15 | google-chrome-stable_current_amd64.deb 16 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | # This configuration file was automatically generated by Gitpod. 2 | # Please adjust to your needs (see https://www.gitpod.io/docs/config-gitpod-file) 3 | # and commit this file to your remote git repository to share the goodness with others. 4 | 5 | tasks: 6 | - init: | 7 | npm install 8 | wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb 9 | sudo apt update 10 | sudo apt install -y ./google-chrome-stable_current_amd64.deb 11 | sudo apt install -y cmake 12 | 13 | rm ./google-chrome-stable_current_amd64.deb 14 | sh setup.sh 15 | git clone https://github.com/emscripten-core/emsdk.git 16 | cd emsdk 17 | ./emsdk install latest 18 | ./emsdk activate latest 19 | cd .. 20 | source ./emsdk/emsdk_env.sh 21 | 22 | 23 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(wasm-git) 2 | cmake_minimum_required(VERSION 3.0) 3 | add_subdirectory(libgit2) 4 | set_target_properties(lg2 PROPERTIES OUTPUT_NAME $ENV{LG2_OUTPUT_NAME}) 5 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | libgit2 is Copyright (C) the libgit2 contributors, 2 | unless otherwise stated. See the AUTHORS file for details. 3 | 4 | Note that the only valid version of the GPL as far as this project 5 | is concerned is _this_ particular version of the license (ie v2, not 6 | v2.2 or v3.x or whatever), unless explicitly otherwise stated. 7 | 8 | ---------------------------------------------------------------------- 9 | 10 | wasm-git is Copyright (C) the wasm-git contributors, 11 | unless otherwise stated. 12 | 13 | ---------------------------------------------------------------------- 14 | 15 | LINKING EXCEPTION 16 | 17 | In addition to the permissions in the GNU General Public License, 18 | the authors give you unlimited permission to link the compiled 19 | version of this library into combinations with other programs, 20 | and to distribute those combinations without any restriction 21 | coming from the use of this file. (The General Public License 22 | restrictions do apply in other respects; for example, they cover 23 | modification of the file, and distribution when not linked into 24 | a combined executable.) 25 | 26 | ---------------------------------------------------------------------- 27 | 28 | GNU GENERAL PUBLIC LICENSE 29 | Version 2, June 1991 30 | 31 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 32 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 33 | Everyone is permitted to copy and distribute verbatim copies 34 | of this license document, but changing it is not allowed. 35 | 36 | Preamble 37 | 38 | The licenses for most software are designed to take away your 39 | freedom to share and change it. By contrast, the GNU General Public 40 | License is intended to guarantee your freedom to share and change free 41 | software--to make sure the software is free for all its users. This 42 | General Public License applies to most of the Free Software 43 | Foundation's software and to any other program whose authors commit to 44 | using it. (Some other Free Software Foundation software is covered by 45 | the GNU Library General Public License instead.) You can apply it to 46 | your programs, too. 47 | 48 | When we speak of free software, we are referring to freedom, not 49 | price. Our General Public Licenses are designed to make sure that you 50 | have the freedom to distribute copies of free software (and charge for 51 | this service if you wish), that you receive source code or can get it 52 | if you want it, that you can change the software or use pieces of it 53 | in new free programs; and that you know you can do these things. 54 | 55 | To protect your rights, we need to make restrictions that forbid 56 | anyone to deny you these rights or to ask you to surrender the rights. 57 | These restrictions translate to certain responsibilities for you if you 58 | distribute copies of the software, or if you modify it. 59 | 60 | For example, if you distribute copies of such a program, whether 61 | gratis or for a fee, you must give the recipients all the rights that 62 | you have. You must make sure that they, too, receive or can get the 63 | source code. And you must show them these terms so they know their 64 | rights. 65 | 66 | We protect your rights with two steps: (1) copyright the software, and 67 | (2) offer you this license which gives you legal permission to copy, 68 | distribute and/or modify the software. 69 | 70 | Also, for each author's protection and ours, we want to make certain 71 | that everyone understands that there is no warranty for this free 72 | software. If the software is modified by someone else and passed on, we 73 | want its recipients to know that what they have is not the original, so 74 | that any problems introduced by others will not reflect on the original 75 | authors' reputations. 76 | 77 | Finally, any free program is threatened constantly by software 78 | patents. We wish to avoid the danger that redistributors of a free 79 | program will individually obtain patent licenses, in effect making the 80 | program proprietary. To prevent this, we have made it clear that any 81 | patent must be licensed for everyone's free use or not licensed at all. 82 | 83 | The precise terms and conditions for copying, distribution and 84 | modification follow. 85 | 86 | GNU GENERAL PUBLIC LICENSE 87 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 88 | 89 | 0. This License applies to any program or other work which contains 90 | a notice placed by the copyright holder saying it may be distributed 91 | under the terms of this General Public License. The "Program", below, 92 | refers to any such program or work, and a "work based on the Program" 93 | means either the Program or any derivative work under copyright law: 94 | that is to say, a work containing the Program or a portion of it, 95 | either verbatim or with modifications and/or translated into another 96 | language. (Hereinafter, translation is included without limitation in 97 | the term "modification".) Each licensee is addressed as "you". 98 | 99 | Activities other than copying, distribution and modification are not 100 | covered by this License; they are outside its scope. The act of 101 | running the Program is not restricted, and the output from the Program 102 | is covered only if its contents constitute a work based on the 103 | Program (independent of having been made by running the Program). 104 | Whether that is true depends on what the Program does. 105 | 106 | 1. You may copy and distribute verbatim copies of the Program's 107 | source code as you receive it, in any medium, provided that you 108 | conspicuously and appropriately publish on each copy an appropriate 109 | copyright notice and disclaimer of warranty; keep intact all the 110 | notices that refer to this License and to the absence of any warranty; 111 | and give any other recipients of the Program a copy of this License 112 | along with the Program. 113 | 114 | You may charge a fee for the physical act of transferring a copy, and 115 | you may at your option offer warranty protection in exchange for a fee. 116 | 117 | 2. You may modify your copy or copies of the Program or any portion 118 | of it, thus forming a work based on the Program, and copy and 119 | distribute such modifications or work under the terms of Section 1 120 | above, provided that you also meet all of these conditions: 121 | 122 | a) You must cause the modified files to carry prominent notices 123 | stating that you changed the files and the date of any change. 124 | 125 | b) You must cause any work that you distribute or publish, that in 126 | whole or in part contains or is derived from the Program or any 127 | part thereof, to be licensed as a whole at no charge to all third 128 | parties under the terms of this License. 129 | 130 | c) If the modified program normally reads commands interactively 131 | when run, you must cause it, when started running for such 132 | interactive use in the most ordinary way, to print or display an 133 | announcement including an appropriate copyright notice and a 134 | notice that there is no warranty (or else, saying that you provide 135 | a warranty) and that users may redistribute the program under 136 | these conditions, and telling the user how to view a copy of this 137 | License. (Exception: if the Program itself is interactive but 138 | does not normally print such an announcement, your work based on 139 | the Program is not required to print an announcement.) 140 | 141 | These requirements apply to the modified work as a whole. If 142 | identifiable sections of that work are not derived from the Program, 143 | and can be reasonably considered independent and separate works in 144 | themselves, then this License, and its terms, do not apply to those 145 | sections when you distribute them as separate works. But when you 146 | distribute the same sections as part of a whole which is a work based 147 | on the Program, the distribution of the whole must be on the terms of 148 | this License, whose permissions for other licensees extend to the 149 | entire whole, and thus to each and every part regardless of who wrote it. 150 | 151 | Thus, it is not the intent of this section to claim rights or contest 152 | your rights to work written entirely by you; rather, the intent is to 153 | exercise the right to control the distribution of derivative or 154 | collective works based on the Program. 155 | 156 | In addition, mere aggregation of another work not based on the Program 157 | with the Program (or with a work based on the Program) on a volume of 158 | a storage or distribution medium does not bring the other work under 159 | the scope of this License. 160 | 161 | 3. You may copy and distribute the Program (or a work based on it, 162 | under Section 2) in object code or executable form under the terms of 163 | Sections 1 and 2 above provided that you also do one of the following: 164 | 165 | a) Accompany it with the complete corresponding machine-readable 166 | source code, which must be distributed under the terms of Sections 167 | 1 and 2 above on a medium customarily used for software interchange; or, 168 | 169 | b) Accompany it with a written offer, valid for at least three 170 | years, to give any third party, for a charge no more than your 171 | cost of physically performing source distribution, a complete 172 | machine-readable copy of the corresponding source code, to be 173 | distributed under the terms of Sections 1 and 2 above on a medium 174 | customarily used for software interchange; or, 175 | 176 | c) Accompany it with the information you received as to the offer 177 | to distribute corresponding source code. (This alternative is 178 | allowed only for noncommercial distribution and only if you 179 | received the program in object code or executable form with such 180 | an offer, in accord with Subsection b above.) 181 | 182 | The source code for a work means the preferred form of the work for 183 | making modifications to it. For an executable work, complete source 184 | code means all the source code for all modules it contains, plus any 185 | associated interface definition files, plus the scripts used to 186 | control compilation and installation of the executable. However, as a 187 | special exception, the source code distributed need not include 188 | anything that is normally distributed (in either source or binary 189 | form) with the major components (compiler, kernel, and so on) of the 190 | operating system on which the executable runs, unless that component 191 | itself accompanies the executable. 192 | 193 | If distribution of executable or object code is made by offering 194 | access to copy from a designated place, then offering equivalent 195 | access to copy the source code from the same place counts as 196 | distribution of the source code, even though third parties are not 197 | compelled to copy the source along with the object code. 198 | 199 | 4. You may not copy, modify, sublicense, or distribute the Program 200 | except as expressly provided under this License. Any attempt 201 | otherwise to copy, modify, sublicense or distribute the Program is 202 | void, and will automatically terminate your rights under this License. 203 | However, parties who have received copies, or rights, from you under 204 | this License will not have their licenses terminated so long as such 205 | parties remain in full compliance. 206 | 207 | 5. You are not required to accept this License, since you have not 208 | signed it. However, nothing else grants you permission to modify or 209 | distribute the Program or its derivative works. These actions are 210 | prohibited by law if you do not accept this License. Therefore, by 211 | modifying or distributing the Program (or any work based on the 212 | Program), you indicate your acceptance of this License to do so, and 213 | all its terms and conditions for copying, distributing or modifying 214 | the Program or works based on it. 215 | 216 | 6. Each time you redistribute the Program (or any work based on the 217 | Program), the recipient automatically receives a license from the 218 | original licensor to copy, distribute or modify the Program subject to 219 | these terms and conditions. You may not impose any further 220 | restrictions on the recipients' exercise of the rights granted herein. 221 | You are not responsible for enforcing compliance by third parties to 222 | this License. 223 | 224 | 7. If, as a consequence of a court judgment or allegation of patent 225 | infringement or for any other reason (not limited to patent issues), 226 | conditions are imposed on you (whether by court order, agreement or 227 | otherwise) that contradict the conditions of this License, they do not 228 | excuse you from the conditions of this License. If you cannot 229 | distribute so as to satisfy simultaneously your obligations under this 230 | License and any other pertinent obligations, then as a consequence you 231 | may not distribute the Program at all. For example, if a patent 232 | license would not permit royalty-free redistribution of the Program by 233 | all those who receive copies directly or indirectly through you, then 234 | the only way you could satisfy both it and this License would be to 235 | refrain entirely from distribution of the Program. 236 | 237 | If any portion of this section is held invalid or unenforceable under 238 | any particular circumstance, the balance of the section is intended to 239 | apply and the section as a whole is intended to apply in other 240 | circumstances. 241 | 242 | It is not the purpose of this section to induce you to infringe any 243 | patents or other property right claims or to contest validity of any 244 | such claims; this section has the sole purpose of protecting the 245 | integrity of the free software distribution system, which is 246 | implemented by public license practices. Many people have made 247 | generous contributions to the wide range of software distributed 248 | through that system in reliance on consistent application of that 249 | system; it is up to the author/donor to decide if he or she is willing 250 | to distribute software through any other system and a licensee cannot 251 | impose that choice. 252 | 253 | This section is intended to make thoroughly clear what is believed to 254 | be a consequence of the rest of this License. 255 | 256 | 8. If the distribution and/or use of the Program is restricted in 257 | certain countries either by patents or by copyrighted interfaces, the 258 | original copyright holder who places the Program under this License 259 | may add an explicit geographical distribution limitation excluding 260 | those countries, so that distribution is permitted only in or among 261 | countries not thus excluded. In such case, this License incorporates 262 | the limitation as if written in the body of this License. 263 | 264 | 9. The Free Software Foundation may publish revised and/or new versions 265 | of the General Public License from time to time. Such new versions will 266 | be similar in spirit to the present version, but may differ in detail to 267 | address new problems or concerns. 268 | 269 | Each version is given a distinguishing version number. If the Program 270 | specifies a version number of this License which applies to it and "any 271 | later version", you have the option of following the terms and conditions 272 | either of that version or of any later version published by the Free 273 | Software Foundation. If the Program does not specify a version number of 274 | this License, you may choose any version ever published by the Free Software 275 | Foundation. 276 | 277 | 10. If you wish to incorporate parts of the Program into other free 278 | programs whose distribution conditions are different, write to the author 279 | to ask for permission. For software which is copyrighted by the Free 280 | Software Foundation, write to the Free Software Foundation; we sometimes 281 | make exceptions for this. Our decision will be guided by the two goals 282 | of preserving the free status of all derivatives of our free software and 283 | of promoting the sharing and reuse of software generally. 284 | 285 | NO WARRANTY 286 | 287 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 288 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 289 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 290 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 291 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 292 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 293 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 294 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 295 | REPAIR OR CORRECTION. 296 | 297 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 298 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 299 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 300 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 301 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 302 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 303 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 304 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 305 | POSSIBILITY OF SUCH DAMAGES. 306 | 307 | END OF TERMS AND CONDITIONS 308 | 309 | How to Apply These Terms to Your New Programs 310 | 311 | If you develop a new program, and you want it to be of the greatest 312 | possible use to the public, the best way to achieve this is to make it 313 | free software which everyone can redistribute and change under these terms. 314 | 315 | To do so, attach the following notices to the program. It is safest 316 | to attach them to the start of each source file to most effectively 317 | convey the exclusion of warranty; and each file should have at least 318 | the "copyright" line and a pointer to where the full notice is found. 319 | 320 | 321 | Copyright (C) 322 | 323 | This program is free software; you can redistribute it and/or modify 324 | it under the terms of the GNU General Public License as published by 325 | the Free Software Foundation; either version 2 of the License, or 326 | (at your option) any later version. 327 | 328 | This program is distributed in the hope that it will be useful, 329 | but WITHOUT ANY WARRANTY; without even the implied warranty of 330 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 331 | GNU General Public License for more details. 332 | 333 | You should have received a copy of the GNU General Public License 334 | along with this program; if not, write to the Free Software 335 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 336 | 337 | 338 | Also add information on how to contact you by electronic and paper mail. 339 | 340 | If the program is interactive, make it output a short notice like this 341 | when it starts in an interactive mode: 342 | 343 | Gnomovision version 69, Copyright (C) year name of author 344 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 345 | This is free software, and you are welcome to redistribute it 346 | under certain conditions; type `show c' for details. 347 | 348 | The hypothetical commands `show w' and `show c' should show the appropriate 349 | parts of the General Public License. Of course, the commands you use may 350 | be called something other than `show w' and `show c'; they could even be 351 | mouse-clicks or menu items--whatever suits your program. 352 | 353 | You should also get your employer (if you work as a programmer) or your 354 | school, if any, to sign a "copyright disclaimer" for the program, if 355 | necessary. Here is a sample; alter the names: 356 | 357 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 358 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 359 | 360 | , 1 April 1989 361 | Ty Coon, President of Vice 362 | 363 | This General Public License does not permit incorporating your program into 364 | proprietary programs. If your program is a subroutine library, you may 365 | consider it more useful to permit linking proprietary applications with the 366 | library. If this is what you want to do, use the GNU Library General 367 | Public License instead of this License. 368 | 369 | ---------------------------------------------------------------------- 370 | 371 | The bundled ZLib code is licensed under the ZLib license: 372 | 373 | Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler 374 | 375 | This software is provided 'as-is', without any express or implied 376 | warranty. In no event will the authors be held liable for any damages 377 | arising from the use of this software. 378 | 379 | Permission is granted to anyone to use this software for any purpose, 380 | including commercial applications, and to alter it and redistribute it 381 | freely, subject to the following restrictions: 382 | 383 | 1. The origin of this software must not be misrepresented; you must not 384 | claim that you wrote the original software. If you use this software 385 | in a product, an acknowledgment in the product documentation would be 386 | appreciated but is not required. 387 | 2. Altered source versions must be plainly marked as such, and must not be 388 | misrepresented as being the original software. 389 | 3. This notice may not be removed or altered from any source distribution. 390 | 391 | Jean-loup Gailly Mark Adler 392 | jloup@gzip.org madler@alumni.caltech.edu 393 | 394 | ---------------------------------------------------------------------- 395 | 396 | The Clar framework is licensed under the ISC license: 397 | 398 | Copyright (c) 2011-2015 Vicent Marti 399 | 400 | Permission to use, copy, modify, and/or distribute this software for any 401 | purpose with or without fee is hereby granted, provided that the above 402 | copyright notice and this permission notice appear in all copies. 403 | 404 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 405 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 406 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 407 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 408 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 409 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 410 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 411 | 412 | ---------------------------------------------------------------------- 413 | 414 | The regex library (deps/regex/) is licensed under the GNU LGPL 415 | (available at the end of this file). 416 | 417 | Definitions for data structures and routines for the regular 418 | expression library. 419 | 420 | Copyright (C) 1985,1989-93,1995-98,2000,2001,2002,2003,2005,2006,2008 421 | Free Software Foundation, Inc. 422 | This file is part of the GNU C Library. 423 | 424 | The GNU C Library is free software; you can redistribute it and/or 425 | modify it under the terms of the GNU Lesser General Public 426 | License as published by the Free Software Foundation; either 427 | version 2.1 of the License, or (at your option) any later version. 428 | 429 | The GNU C Library is distributed in the hope that it will be useful, 430 | but WITHOUT ANY WARRANTY; without even the implied warranty of 431 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 432 | Lesser General Public License for more details. 433 | 434 | You should have received a copy of the GNU Lesser General Public 435 | License along with the GNU C Library; if not, write to the Free 436 | Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 437 | 02110-1301 USA. 438 | 439 | ---------------------------------------------------------------------- 440 | 441 | The bundled winhttp definition files (deps/winhttp/) are licensed under 442 | the GNU LGPL (available at the end of this file). 443 | 444 | Copyright (C) 2007 Francois Gouget 445 | 446 | This library is free software; you can redistribute it and/or 447 | modify it under the terms of the GNU Lesser General Public 448 | License as published by the Free Software Foundation; either 449 | version 2.1 of the License, or (at your option) any later version. 450 | 451 | This library is distributed in the hope that it will be useful, 452 | but WITHOUT ANY WARRANTY; without even the implied warranty of 453 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 454 | Lesser General Public License for more details. 455 | 456 | You should have received a copy of the GNU Lesser General Public 457 | License along with this library; if not, write to the Free Software 458 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA 459 | 460 | ---------------------------------------------------------------------- 461 | 462 | GNU LESSER GENERAL PUBLIC LICENSE 463 | Version 2.1, February 1999 464 | 465 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 466 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 467 | Everyone is permitted to copy and distribute verbatim copies 468 | of this license document, but changing it is not allowed. 469 | 470 | [This is the first released version of the Lesser GPL. It also counts 471 | as the successor of the GNU Library Public License, version 2, hence 472 | the version number 2.1.] 473 | 474 | Preamble 475 | 476 | The licenses for most software are designed to take away your 477 | freedom to share and change it. By contrast, the GNU General Public 478 | Licenses are intended to guarantee your freedom to share and change 479 | free software--to make sure the software is free for all its users. 480 | 481 | This license, the Lesser General Public License, applies to some 482 | specially designated software packages--typically libraries--of the 483 | Free Software Foundation and other authors who decide to use it. You 484 | can use it too, but we suggest you first think carefully about whether 485 | this license or the ordinary General Public License is the better 486 | strategy to use in any particular case, based on the explanations below. 487 | 488 | When we speak of free software, we are referring to freedom of use, 489 | not price. Our General Public Licenses are designed to make sure that 490 | you have the freedom to distribute copies of free software (and charge 491 | for this service if you wish); that you receive source code or can get 492 | it if you want it; that you can change the software and use pieces of 493 | it in new free programs; and that you are informed that you can do 494 | these things. 495 | 496 | To protect your rights, we need to make restrictions that forbid 497 | distributors to deny you these rights or to ask you to surrender these 498 | rights. These restrictions translate to certain responsibilities for 499 | you if you distribute copies of the library or if you modify it. 500 | 501 | For example, if you distribute copies of the library, whether gratis 502 | or for a fee, you must give the recipients all the rights that we gave 503 | you. You must make sure that they, too, receive or can get the source 504 | code. If you link other code with the library, you must provide 505 | complete object files to the recipients, so that they can relink them 506 | with the library after making changes to the library and recompiling 507 | it. And you must show them these terms so they know their rights. 508 | 509 | We protect your rights with a two-step method: (1) we copyright the 510 | library, and (2) we offer you this license, which gives you legal 511 | permission to copy, distribute and/or modify the library. 512 | 513 | To protect each distributor, we want to make it very clear that 514 | there is no warranty for the free library. Also, if the library is 515 | modified by someone else and passed on, the recipients should know 516 | that what they have is not the original version, so that the original 517 | author's reputation will not be affected by problems that might be 518 | introduced by others. 519 | 520 | Finally, software patents pose a constant threat to the existence of 521 | any free program. We wish to make sure that a company cannot 522 | effectively restrict the users of a free program by obtaining a 523 | restrictive license from a patent holder. Therefore, we insist that 524 | any patent license obtained for a version of the library must be 525 | consistent with the full freedom of use specified in this license. 526 | 527 | Most GNU software, including some libraries, is covered by the 528 | ordinary GNU General Public License. This license, the GNU Lesser 529 | General Public License, applies to certain designated libraries, and 530 | is quite different from the ordinary General Public License. We use 531 | this license for certain libraries in order to permit linking those 532 | libraries into non-free programs. 533 | 534 | When a program is linked with a library, whether statically or using 535 | a shared library, the combination of the two is legally speaking a 536 | combined work, a derivative of the original library. The ordinary 537 | General Public License therefore permits such linking only if the 538 | entire combination fits its criteria of freedom. The Lesser General 539 | Public License permits more lax criteria for linking other code with 540 | the library. 541 | 542 | We call this license the "Lesser" General Public License because it 543 | does Less to protect the user's freedom than the ordinary General 544 | Public License. It also provides other free software developers Less 545 | of an advantage over competing non-free programs. These disadvantages 546 | are the reason we use the ordinary General Public License for many 547 | libraries. However, the Lesser license provides advantages in certain 548 | special circumstances. 549 | 550 | For example, on rare occasions, there may be a special need to 551 | encourage the widest possible use of a certain library, so that it becomes 552 | a de-facto standard. To achieve this, non-free programs must be 553 | allowed to use the library. A more frequent case is that a free 554 | library does the same job as widely used non-free libraries. In this 555 | case, there is little to gain by limiting the free library to free 556 | software only, so we use the Lesser General Public License. 557 | 558 | In other cases, permission to use a particular library in non-free 559 | programs enables a greater number of people to use a large body of 560 | free software. For example, permission to use the GNU C Library in 561 | non-free programs enables many more people to use the whole GNU 562 | operating system, as well as its variant, the GNU/Linux operating 563 | system. 564 | 565 | Although the Lesser General Public License is Less protective of the 566 | users' freedom, it does ensure that the user of a program that is 567 | linked with the Library has the freedom and the wherewithal to run 568 | that program using a modified version of the Library. 569 | 570 | The precise terms and conditions for copying, distribution and 571 | modification follow. Pay close attention to the difference between a 572 | "work based on the library" and a "work that uses the library". The 573 | former contains code derived from the library, whereas the latter must 574 | be combined with the library in order to run. 575 | 576 | GNU LESSER GENERAL PUBLIC LICENSE 577 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 578 | 579 | 0. This License Agreement applies to any software library or other 580 | program which contains a notice placed by the copyright holder or 581 | other authorized party saying it may be distributed under the terms of 582 | this Lesser General Public License (also called "this License"). 583 | Each licensee is addressed as "you". 584 | 585 | A "library" means a collection of software functions and/or data 586 | prepared so as to be conveniently linked with application programs 587 | (which use some of those functions and data) to form executables. 588 | 589 | The "Library", below, refers to any such software library or work 590 | which has been distributed under these terms. A "work based on the 591 | Library" means either the Library or any derivative work under 592 | copyright law: that is to say, a work containing the Library or a 593 | portion of it, either verbatim or with modifications and/or translated 594 | straightforwardly into another language. (Hereinafter, translation is 595 | included without limitation in the term "modification".) 596 | 597 | "Source code" for a work means the preferred form of the work for 598 | making modifications to it. For a library, complete source code means 599 | all the source code for all modules it contains, plus any associated 600 | interface definition files, plus the scripts used to control compilation 601 | and installation of the library. 602 | 603 | Activities other than copying, distribution and modification are not 604 | covered by this License; they are outside its scope. The act of 605 | running a program using the Library is not restricted, and output from 606 | such a program is covered only if its contents constitute a work based 607 | on the Library (independent of the use of the Library in a tool for 608 | writing it). Whether that is true depends on what the Library does 609 | and what the program that uses the Library does. 610 | 611 | 1. You may copy and distribute verbatim copies of the Library's 612 | complete source code as you receive it, in any medium, provided that 613 | you conspicuously and appropriately publish on each copy an 614 | appropriate copyright notice and disclaimer of warranty; keep intact 615 | all the notices that refer to this License and to the absence of any 616 | warranty; and distribute a copy of this License along with the 617 | Library. 618 | 619 | You may charge a fee for the physical act of transferring a copy, 620 | and you may at your option offer warranty protection in exchange for a 621 | fee. 622 | 623 | 2. You may modify your copy or copies of the Library or any portion 624 | of it, thus forming a work based on the Library, and copy and 625 | distribute such modifications or work under the terms of Section 1 626 | above, provided that you also meet all of these conditions: 627 | 628 | a) The modified work must itself be a software library. 629 | 630 | b) You must cause the files modified to carry prominent notices 631 | stating that you changed the files and the date of any change. 632 | 633 | c) You must cause the whole of the work to be licensed at no 634 | charge to all third parties under the terms of this License. 635 | 636 | d) If a facility in the modified Library refers to a function or a 637 | table of data to be supplied by an application program that uses 638 | the facility, other than as an argument passed when the facility 639 | is invoked, then you must make a good faith effort to ensure that, 640 | in the event an application does not supply such function or 641 | table, the facility still operates, and performs whatever part of 642 | its purpose remains meaningful. 643 | 644 | (For example, a function in a library to compute square roots has 645 | a purpose that is entirely well-defined independent of the 646 | application. Therefore, Subsection 2d requires that any 647 | application-supplied function or table used by this function must 648 | be optional: if the application does not supply it, the square 649 | root function must still compute square roots.) 650 | 651 | These requirements apply to the modified work as a whole. If 652 | identifiable sections of that work are not derived from the Library, 653 | and can be reasonably considered independent and separate works in 654 | themselves, then this License, and its terms, do not apply to those 655 | sections when you distribute them as separate works. But when you 656 | distribute the same sections as part of a whole which is a work based 657 | on the Library, the distribution of the whole must be on the terms of 658 | this License, whose permissions for other licensees extend to the 659 | entire whole, and thus to each and every part regardless of who wrote 660 | it. 661 | 662 | Thus, it is not the intent of this section to claim rights or contest 663 | your rights to work written entirely by you; rather, the intent is to 664 | exercise the right to control the distribution of derivative or 665 | collective works based on the Library. 666 | 667 | In addition, mere aggregation of another work not based on the Library 668 | with the Library (or with a work based on the Library) on a volume of 669 | a storage or distribution medium does not bring the other work under 670 | the scope of this License. 671 | 672 | 3. You may opt to apply the terms of the ordinary GNU General Public 673 | License instead of this License to a given copy of the Library. To do 674 | this, you must alter all the notices that refer to this License, so 675 | that they refer to the ordinary GNU General Public License, version 2, 676 | instead of to this License. (If a newer version than version 2 of the 677 | ordinary GNU General Public License has appeared, then you can specify 678 | that version instead if you wish.) Do not make any other change in 679 | these notices. 680 | 681 | Once this change is made in a given copy, it is irreversible for 682 | that copy, so the ordinary GNU General Public License applies to all 683 | subsequent copies and derivative works made from that copy. 684 | 685 | This option is useful when you wish to copy part of the code of 686 | the Library into a program that is not a library. 687 | 688 | 4. You may copy and distribute the Library (or a portion or 689 | derivative of it, under Section 2) in object code or executable form 690 | under the terms of Sections 1 and 2 above provided that you accompany 691 | it with the complete corresponding machine-readable source code, which 692 | must be distributed under the terms of Sections 1 and 2 above on a 693 | medium customarily used for software interchange. 694 | 695 | If distribution of object code is made by offering access to copy 696 | from a designated place, then offering equivalent access to copy the 697 | source code from the same place satisfies the requirement to 698 | distribute the source code, even though third parties are not 699 | compelled to copy the source along with the object code. 700 | 701 | 5. A program that contains no derivative of any portion of the 702 | Library, but is designed to work with the Library by being compiled or 703 | linked with it, is called a "work that uses the Library". Such a 704 | work, in isolation, is not a derivative work of the Library, and 705 | therefore falls outside the scope of this License. 706 | 707 | However, linking a "work that uses the Library" with the Library 708 | creates an executable that is a derivative of the Library (because it 709 | contains portions of the Library), rather than a "work that uses the 710 | library". The executable is therefore covered by this License. 711 | Section 6 states terms for distribution of such executables. 712 | 713 | When a "work that uses the Library" uses material from a header file 714 | that is part of the Library, the object code for the work may be a 715 | derivative work of the Library even though the source code is not. 716 | Whether this is true is especially significant if the work can be 717 | linked without the Library, or if the work is itself a library. The 718 | threshold for this to be true is not precisely defined by law. 719 | 720 | If such an object file uses only numerical parameters, data 721 | structure layouts and accessors, and small macros and small inline 722 | functions (ten lines or less in length), then the use of the object 723 | file is unrestricted, regardless of whether it is legally a derivative 724 | work. (Executables containing this object code plus portions of the 725 | Library will still fall under Section 6.) 726 | 727 | Otherwise, if the work is a derivative of the Library, you may 728 | distribute the object code for the work under the terms of Section 6. 729 | Any executables containing that work also fall under Section 6, 730 | whether or not they are linked directly with the Library itself. 731 | 732 | 6. As an exception to the Sections above, you may also combine or 733 | link a "work that uses the Library" with the Library to produce a 734 | work containing portions of the Library, and distribute that work 735 | under terms of your choice, provided that the terms permit 736 | modification of the work for the customer's own use and reverse 737 | engineering for debugging such modifications. 738 | 739 | You must give prominent notice with each copy of the work that the 740 | Library is used in it and that the Library and its use are covered by 741 | this License. You must supply a copy of this License. If the work 742 | during execution displays copyright notices, you must include the 743 | copyright notice for the Library among them, as well as a reference 744 | directing the user to the copy of this License. Also, you must do one 745 | of these things: 746 | 747 | a) Accompany the work with the complete corresponding 748 | machine-readable source code for the Library including whatever 749 | changes were used in the work (which must be distributed under 750 | Sections 1 and 2 above); and, if the work is an executable linked 751 | with the Library, with the complete machine-readable "work that 752 | uses the Library", as object code and/or source code, so that the 753 | user can modify the Library and then relink to produce a modified 754 | executable containing the modified Library. (It is understood 755 | that the user who changes the contents of definitions files in the 756 | Library will not necessarily be able to recompile the application 757 | to use the modified definitions.) 758 | 759 | b) Use a suitable shared library mechanism for linking with the 760 | Library. A suitable mechanism is one that (1) uses at run time a 761 | copy of the library already present on the user's computer system, 762 | rather than copying library functions into the executable, and (2) 763 | will operate properly with a modified version of the library, if 764 | the user installs one, as long as the modified version is 765 | interface-compatible with the version that the work was made with. 766 | 767 | c) Accompany the work with a written offer, valid for at 768 | least three years, to give the same user the materials 769 | specified in Subsection 6a, above, for a charge no more 770 | than the cost of performing this distribution. 771 | 772 | d) If distribution of the work is made by offering access to copy 773 | from a designated place, offer equivalent access to copy the above 774 | specified materials from the same place. 775 | 776 | e) Verify that the user has already received a copy of these 777 | materials or that you have already sent this user a copy. 778 | 779 | For an executable, the required form of the "work that uses the 780 | Library" must include any data and utility programs needed for 781 | reproducing the executable from it. However, as a special exception, 782 | the materials to be distributed need not include anything that is 783 | normally distributed (in either source or binary form) with the major 784 | components (compiler, kernel, and so on) of the operating system on 785 | which the executable runs, unless that component itself accompanies 786 | the executable. 787 | 788 | It may happen that this requirement contradicts the license 789 | restrictions of other proprietary libraries that do not normally 790 | accompany the operating system. Such a contradiction means you cannot 791 | use both them and the Library together in an executable that you 792 | distribute. 793 | 794 | 7. You may place library facilities that are a work based on the 795 | Library side-by-side in a single library together with other library 796 | facilities not covered by this License, and distribute such a combined 797 | library, provided that the separate distribution of the work based on 798 | the Library and of the other library facilities is otherwise 799 | permitted, and provided that you do these two things: 800 | 801 | a) Accompany the combined library with a copy of the same work 802 | based on the Library, uncombined with any other library 803 | facilities. This must be distributed under the terms of the 804 | Sections above. 805 | 806 | b) Give prominent notice with the combined library of the fact 807 | that part of it is a work based on the Library, and explaining 808 | where to find the accompanying uncombined form of the same work. 809 | 810 | 8. You may not copy, modify, sublicense, link with, or distribute 811 | the Library except as expressly provided under this License. Any 812 | attempt otherwise to copy, modify, sublicense, link with, or 813 | distribute the Library is void, and will automatically terminate your 814 | rights under this License. However, parties who have received copies, 815 | or rights, from you under this License will not have their licenses 816 | terminated so long as such parties remain in full compliance. 817 | 818 | 9. You are not required to accept this License, since you have not 819 | signed it. However, nothing else grants you permission to modify or 820 | distribute the Library or its derivative works. These actions are 821 | prohibited by law if you do not accept this License. Therefore, by 822 | modifying or distributing the Library (or any work based on the 823 | Library), you indicate your acceptance of this License to do so, and 824 | all its terms and conditions for copying, distributing or modifying 825 | the Library or works based on it. 826 | 827 | 10. Each time you redistribute the Library (or any work based on the 828 | Library), the recipient automatically receives a license from the 829 | original licensor to copy, distribute, link with or modify the Library 830 | subject to these terms and conditions. You may not impose any further 831 | restrictions on the recipients' exercise of the rights granted herein. 832 | You are not responsible for enforcing compliance by third parties with 833 | this License. 834 | 835 | 11. If, as a consequence of a court judgment or allegation of patent 836 | infringement or for any other reason (not limited to patent issues), 837 | conditions are imposed on you (whether by court order, agreement or 838 | otherwise) that contradict the conditions of this License, they do not 839 | excuse you from the conditions of this License. If you cannot 840 | distribute so as to satisfy simultaneously your obligations under this 841 | License and any other pertinent obligations, then as a consequence you 842 | may not distribute the Library at all. For example, if a patent 843 | license would not permit royalty-free redistribution of the Library by 844 | all those who receive copies directly or indirectly through you, then 845 | the only way you could satisfy both it and this License would be to 846 | refrain entirely from distribution of the Library. 847 | 848 | If any portion of this section is held invalid or unenforceable under any 849 | particular circumstance, the balance of the section is intended to apply, 850 | and the section as a whole is intended to apply in other circumstances. 851 | 852 | It is not the purpose of this section to induce you to infringe any 853 | patents or other property right claims or to contest validity of any 854 | such claims; this section has the sole purpose of protecting the 855 | integrity of the free software distribution system which is 856 | implemented by public license practices. Many people have made 857 | generous contributions to the wide range of software distributed 858 | through that system in reliance on consistent application of that 859 | system; it is up to the author/donor to decide if he or she is willing 860 | to distribute software through any other system and a licensee cannot 861 | impose that choice. 862 | 863 | This section is intended to make thoroughly clear what is believed to 864 | be a consequence of the rest of this License. 865 | 866 | 12. If the distribution and/or use of the Library is restricted in 867 | certain countries either by patents or by copyrighted interfaces, the 868 | original copyright holder who places the Library under this License may add 869 | an explicit geographical distribution limitation excluding those countries, 870 | so that distribution is permitted only in or among countries not thus 871 | excluded. In such case, this License incorporates the limitation as if 872 | written in the body of this License. 873 | 874 | 13. The Free Software Foundation may publish revised and/or new 875 | versions of the Lesser General Public License from time to time. 876 | Such new versions will be similar in spirit to the present version, 877 | but may differ in detail to address new problems or concerns. 878 | 879 | Each version is given a distinguishing version number. If the Library 880 | specifies a version number of this License which applies to it and 881 | "any later version", you have the option of following the terms and 882 | conditions either of that version or of any later version published by 883 | the Free Software Foundation. If the Library does not specify a 884 | license version number, you may choose any version ever published by 885 | the Free Software Foundation. 886 | 887 | 14. If you wish to incorporate parts of the Library into other free 888 | programs whose distribution conditions are incompatible with these, 889 | write to the author to ask for permission. For software which is 890 | copyrighted by the Free Software Foundation, write to the Free 891 | Software Foundation; we sometimes make exceptions for this. Our 892 | decision will be guided by the two goals of preserving the free status 893 | of all derivatives of our free software and of promoting the sharing 894 | and reuse of software generally. 895 | 896 | NO WARRANTY 897 | 898 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 899 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 900 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 901 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 902 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 903 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 904 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 905 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 906 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 907 | 908 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 909 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 910 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 911 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 912 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 913 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 914 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 915 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 916 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 917 | DAMAGES. 918 | 919 | END OF TERMS AND CONDITIONS 920 | 921 | How to Apply These Terms to Your New Libraries 922 | 923 | If you develop a new library, and you want it to be of the greatest 924 | possible use to the public, we recommend making it free software that 925 | everyone can redistribute and change. You can do so by permitting 926 | redistribution under these terms (or, alternatively, under the terms of the 927 | ordinary General Public License). 928 | 929 | To apply these terms, attach the following notices to the library. It is 930 | safest to attach them to the start of each source file to most effectively 931 | convey the exclusion of warranty; and each file should have at least the 932 | "copyright" line and a pointer to where the full notice is found. 933 | 934 | 935 | Copyright (C) 936 | 937 | This library is free software; you can redistribute it and/or 938 | modify it under the terms of the GNU Lesser General Public 939 | License as published by the Free Software Foundation; either 940 | version 2.1 of the License, or (at your option) any later version. 941 | 942 | This library is distributed in the hope that it will be useful, 943 | but WITHOUT ANY WARRANTY; without even the implied warranty of 944 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 945 | Lesser General Public License for more details. 946 | 947 | You should have received a copy of the GNU Lesser General Public 948 | License along with this library; if not, write to the Free Software 949 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 950 | 951 | Also add information on how to contact you by electronic and paper mail. 952 | 953 | You should also get your employer (if you work as a programmer) or your 954 | school, if any, to sign a "copyright disclaimer" for the library, if 955 | necessary. Here is a sample; alter the names: 956 | 957 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 958 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 959 | 960 | , 1 April 1990 961 | Ty Coon, President of Vice 962 | 963 | That's all there is to it! 964 | 965 | ---------------------------------------------------------------------- 966 | 967 | The bundled SHA1 collision detection code is licensed under the MIT license: 968 | 969 | MIT License 970 | 971 | Copyright (c) 2017: 972 | Marc Stevens 973 | Cryptology Group 974 | Centrum Wiskunde & Informatica 975 | P.O. Box 94079, 1090 GB Amsterdam, Netherlands 976 | marc@marc-stevens.nl 977 | 978 | Dan Shumow 979 | Microsoft Research 980 | danshu@microsoft.com 981 | 982 | Permission is hereby granted, free of charge, to any person obtaining a copy 983 | of this software and associated documentation files (the "Software"), to deal 984 | in the Software without restriction, including without limitation the rights 985 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 986 | copies of the Software, and to permit persons to whom the Software is 987 | furnished to do so, subject to the following conditions: 988 | 989 | The above copyright notice and this permission notice shall be included in all 990 | copies or substantial portions of the Software. 991 | 992 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 993 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 994 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 995 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 996 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 997 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 998 | SOFTWARE. 999 | 1000 | ---------------------------------------------------------------------- 1001 | 1002 | The bundled wildmatch code is licensed under the BSD license: 1003 | 1004 | Copyright Rich Salz. 1005 | All rights reserved. 1006 | 1007 | Redistribution and use in any form are permitted provided that the 1008 | following restrictions are are met: 1009 | 1010 | 1. Source distributions must retain this entire copyright notice 1011 | and comment. 1012 | 2. Binary distributions must include the acknowledgement ``This 1013 | product includes software developed by Rich Salz'' in the 1014 | documentation or other materials provided with the 1015 | distribution. This must not be represented as an endorsement 1016 | or promotion without specific prior written permission. 1017 | 3. The origin of this software must not be misrepresented, either 1018 | by explicit claim or by omission. Credits must appear in the 1019 | source and documentation. 1020 | 4. Altered versions must be plainly marked as such in the source 1021 | and documentation and must not be misrepresented as being the 1022 | original software. 1023 | 1024 | THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED 1025 | WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF 1026 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Wasm-git 2 | ======== 3 | (Wasm should be pronounced like `awesome` starting with a `W` ). 4 | 5 | ![](https://github.com/petersalomonsen/wasm-git/actions/workflows/main.yml/badge.svg) 6 | 7 | GIT for nodejs and the browser using [libgit2](https://libgit2.org/) compiled to WebAssembly with [Emscripten](https://emscripten.org). 8 | 9 | The main purpose of bringing git to the browser, is to enable storage of web application data locally in the users web browser, with the option to synchronize with a remote server. 10 | 11 | # Demo in the browser 12 | 13 | A simple demo in the browser can be found at: 14 | 15 | https://wasm-git.petersalomonsen.com/ 16 | 17 | **Please do not abuse, this is open for you to test and see the proof of concept** 18 | 19 | The sources for the demo can be found in the [githttpserver](https://github.com/petersalomonsen/githttpserver) project. It shows basic operations like cloning, edit files, add and commit, push and pull. 20 | 21 | # Demo videos 22 | 23 | Videos showing example applications using wasm-git can bee seen in [this playlist](https://www.youtube.com/watch?v=1Hqy7cVkygU&list=PLv5wm4YuO4Iyx00ifs6xUwIRSFnBI8GZh). Wasm-git is used for local and offline storage of web application data, and for syncing with a remote server. 24 | 25 | # Examples 26 | 27 | Wasm-git packages are built in two variants: Synchronuous and Asynchronuous. To run the sync version in the browser, a [webworker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) is needed. This is because of the use of synchronous http requests and long running operations that would block if running on the main thread. The sync version has the smallest binary, but need extra client code to communicate with the web worker. When using the sync version in nodejs [worker_threads](https://nodejs.org/api/worker_threads.html) are used, with [Atomics](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics) to exchange data between threads. 28 | 29 | The async version use [Emscripten Asyncify](https://emscripten.org/docs/porting/asyncify.html), which allows calling the Wasm-git functions with `async` / `await`. It can also run from the main thread in the browser. Asyncify increase the binary size because of instrumentation to unwind and rewind WebAssembly state, but makes it possible to have simple client code without exchanging data with worker threads like in the sync version. 30 | 31 | Examples of using Wasm-git can be found in the tests: 32 | 33 | - [test](./test/) for NodeJS 34 | - [test-browser](./test-browser/) for the sync version in the browser with a web worker 35 | - [test-browser-async](./test-browser-async/)] for the async version in the browser 36 | 37 | The examples shows importing the `lg2.js` / `lg2-async.js` modules from the local build, but you may also access these from releases available at public CDNs. 38 | 39 | # Building and developing 40 | 41 | The [Github actions test pipeline](./.github/workflows/main.yml) shows all the commands needed to install dependencies, build the packages and run the tests. 42 | 43 | Another option is loading the repository into a github codespace, where the configuration in [.devcontainer](./.devcontainer) folder will be used to install dependencies and set up a full development environment. 44 | 45 | # Emscripten fixes that were needed for making Wasm-git work 46 | 47 | As part of being able to compile libgit2 to WebAssembly and run it in a Javascript environment, some fixes to [Emscripten](https://emscripten.org/) were needed. 48 | 49 | Here are the Pull Requests that resolved the issues identified when the first version was developed: 50 | 51 | - https://github.com/emscripten-core/emscripten/pull/10095 52 | - https://github.com/emscripten-core/emscripten/pull/10526 53 | - https://github.com/emscripten-core/emscripten/pull/10782 54 | 55 | for using with `NODEFS` you'll also need https://github.com/emscripten-core/emscripten/pull/10669 56 | 57 | All of these pull requests are merged to emscripten master as of 2020-03-29. 58 | 59 | -------------------------------------------------------------------------------- /emscriptenbuild/.gitignore: -------------------------------------------------------------------------------- 1 | CMake* 2 | src 3 | deps 4 | examples 5 | libgit2* 6 | include 7 | Makefile 8 | *.cmake 9 | *.a -------------------------------------------------------------------------------- /emscriptenbuild/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | BUILD_TYPE=Debug 4 | ASYNCIFY_FLAGS=" -s ASYNCIFY -s 'ASYNCIFY_IMPORTS=[\"emscriptenhttp_do_get\", \"emscriptenhttp_do_read\", \"emscriptenhttp_do_post\"]' " 5 | POST_JS="--post-js $(pwd)/post.js" 6 | 7 | # Reset in case we've done an '-async' build 8 | cp ../libgit2patchedfiles/src/transports/emscriptenhttp.c ../libgit2/src/libgit2/transports/emscriptenhttp.c 9 | 10 | export LG2_OUTPUT_NAME=lg2 11 | 12 | # Set build type to Release for release 13 | if [ "$1" == "Release" ]; then 14 | BUILD_TYPE=Release 15 | EXTRA_CMAKE_C_FLAGS="-Oz" 16 | fi 17 | 18 | # For async transports we overwrite emscripenhttp.c, use post-async.js and change the extra flags 19 | if [ "$1" == "Release-async" ]; then 20 | BUILD_TYPE=Release 21 | cp ../libgit2patchedfiles/src/transports/emscriptenhttp-async.c ../libgit2/src/libgit2/transports/emscriptenhttp.c 22 | 23 | EXTRA_CMAKE_C_FLAGS="-O3 $ASYNCIFY_FLAGS" 24 | POST_JS="--post-js $(pwd)/post-async.js" 25 | export LG2_OUTPUT_NAME=lg2_async 26 | elif [ "$1" == "Debug-async" ]; then 27 | BUILD_TYPE=Debug 28 | cp ../libgit2patchedfiles/src/transports/emscriptenhttp-async.c ../libgit2/src/libgit2/transports/emscriptenhttp.c 29 | 30 | EXTRA_CMAKE_C_FLAGS="$ASYNCIFY_FLAGS" 31 | POST_JS="--post-js $(pwd)/post-async.js" 32 | export LG2_OUTPUT_NAME=lg2_async 33 | fi 34 | 35 | # Before building, remove any ../libgit2/src/ transports/emscriptenhttp.c left from running setup.sh 36 | [ -f "../libgit2/src/libgit2/transports/emscriptenhttp-async.c" ] && rm ../libgit2/src/libgit2/transports/emscriptenhttp-async.c 37 | 38 | emcmake cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_C_FLAGS="$EXTRA_CMAKE_C_FLAGS --pre-js $(pwd)/pre.js $POST_JS -s \"EXPORTED_RUNTIME_METHODS=['FS','MEMFS','IDBFS','NODEFS','callMain']\" -sFORCE_FILESYSTEM -sEXPORT_ES6 -s INVOKE_RUN=0 -s ALLOW_MEMORY_GROWTH=1 -s STACK_SIZE=131072 -lidbfs.js -lnodefs.js" -DREGEX_BACKEND=regcomp -DSONAME=OFF -DUSE_HTTPS=OFF -DBUILD_SHARED_LIBS=OFF -DTHREADSAFE=OFF -DUSE_SSH=OFF -DBUILD_CLAR=OFF -DBUILD_EXAMPLES=ON .. 39 | emmake make lg2 40 | -------------------------------------------------------------------------------- /emscriptenbuild/post-async.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Javascript functions for emscripten http transport for nodejs and the browser NOT using a webworker 3 | * 4 | * If you can't use a webworker, you can build Release-async or Debug-async versions of wasm-git 5 | * which use async transports, and can be run without a webworker. The lg2 release files are about 6 | * twice the size with this option, and your UI may be affected by doing git operations in the 7 | * main JavaScript thread. 8 | * 9 | * This the non-webworker version (see also post.js) 10 | */ 11 | 12 | const emscriptenhttpconnections = {}; 13 | let httpConnectionNo = 0; 14 | 15 | const chmod = FS.chmod; 16 | 17 | FS.chmod = function(path, mode, dontFollow) { 18 | if (mode === 0o100000 > 0) { 19 | // workaround for libgit2 calling chmod with only S_IFREG set (permisions 0000) 20 | // reason currently not known 21 | return chmod(path, mode, dontFollow); 22 | } else { 23 | return 0; 24 | } 25 | }; 26 | 27 | if(ENVIRONMENT_IS_WEB) { 28 | Module.origCallMain = Module.callMain; 29 | Module.callMain = async (args) => { 30 | await Module.origCallMain(args); 31 | if (typeof Asyncify === 'object' && Asyncify.currData) { 32 | await Asyncify.whenDone(); 33 | } 34 | }; 35 | 36 | Object.assign(Module, { 37 | emscriptenhttpconnect: async function(url, buffersize, method, headers) { 38 | let result = new Promise((resolve, reject) => { 39 | if(!method) { 40 | method = 'GET'; 41 | } 42 | 43 | const xhr = new XMLHttpRequest(); 44 | xhr.open(method, url, true); 45 | xhr.responseType = 'arraybuffer'; 46 | 47 | if (headers) { 48 | Object.keys(headers).forEach(header => xhr.setRequestHeader(header, headers[header])); 49 | } 50 | 51 | emscriptenhttpconnections[httpConnectionNo] = { 52 | xhr: xhr, 53 | resultbufferpointer: 0, 54 | buffersize: buffersize 55 | }; 56 | 57 | if(method === 'GET') { 58 | xhr.onload = function () { 59 | resolve(httpConnectionNo++); 60 | }; 61 | xhr.send(); 62 | } else { 63 | resolve(httpConnectionNo++); 64 | } 65 | }); 66 | return result; 67 | }, 68 | emscriptenhttpwrite: function(connectionNo, buffer, length) { 69 | const connection = emscriptenhttpconnections[connectionNo]; 70 | const buf = new Uint8Array(Module.HEAPU8.buffer,buffer,length).slice(0); 71 | if(!connection.content) { 72 | connection.content = buf; 73 | } else { 74 | const content = new Uint8Array(connection.content.length + buf.length); 75 | content.set(connection.content); 76 | content.set(buf, connection.content.length); 77 | connection.content = content; 78 | } 79 | }, 80 | emscriptenhttpread: async function(connectionNo, buffer, buffersize) { 81 | const connection = emscriptenhttpconnections[connectionNo]; 82 | 83 | function handleResponse(connection, buffer, buffersize) { 84 | let bytes_read = connection.xhr.response.byteLength - connection.resultbufferpointer; 85 | if (bytes_read > buffersize) { 86 | bytes_read = buffersize; 87 | } 88 | const responseChunk = new Uint8Array(connection.xhr.response, connection.resultbufferpointer, bytes_read); 89 | writeArrayToMemory(responseChunk, buffer); 90 | connection.resultbufferpointer += bytes_read; 91 | return bytes_read; 92 | } 93 | 94 | let result = new Promise((resolve) => { 95 | if(connection.content) { 96 | connection.xhr.onload = function () { 97 | resolve(handleResponse(connection, buffer, buffersize)); 98 | }; 99 | connection.xhr.send(connection.content.buffer); 100 | connection.content = null; 101 | } else { 102 | resolve(handleResponse(connection, buffer, buffersize)); 103 | } 104 | }); 105 | 106 | return result; 107 | }, 108 | emscriptenhttpfree: function(connectionNo) { 109 | delete emscriptenhttpconnections[connectionNo]; 110 | } 111 | }); 112 | } else if(ENVIRONMENT_IS_NODE) { 113 | const { Worker } = require('worker_threads'); 114 | 115 | Object.assign(Module, { 116 | emscriptenhttpconnect: function(url, buffersize, method, headers) { 117 | const statusArray = new Int32Array(new SharedArrayBuffer(4)); 118 | Atomics.store(statusArray, 0, method === 'POST' ? -1 : 0); 119 | 120 | const resultBuffer = new SharedArrayBuffer(buffersize); 121 | const resultArray = new Uint8Array(resultBuffer); 122 | const workerData = { 123 | statusArray: statusArray, 124 | resultArray: resultArray, 125 | url: url, 126 | method: method ? method: 'GET', 127 | headers: headers 128 | }; 129 | 130 | new Worker('(' + (function requestWorker() { 131 | const { workerData } = require('worker_threads'); 132 | const req = require(workerData.url.indexOf('https') === 0 ? 'https' : 'http') 133 | .request(workerData.url, { 134 | headers: workerData.headers, 135 | method: workerData.method 136 | }, (res) => { 137 | res.on('data', chunk => { 138 | const previousStatus = workerData.statusArray[0]; 139 | if(previousStatus !== 0) { 140 | Atomics.wait(workerData.statusArray, 0, previousStatus); 141 | } 142 | workerData.resultArray.set(chunk); 143 | Atomics.store(workerData.statusArray, 0, chunk.length); 144 | Atomics.notify(workerData.statusArray, 0, 1); 145 | }); 146 | }); 147 | 148 | if(workerData.method === 'POST') { 149 | while(workerData.statusArray[0] !== 0) { 150 | Atomics.wait(workerData.statusArray, 0, -1); 151 | const length = workerData.statusArray[0]; 152 | if(length === 0) { 153 | break; 154 | } 155 | req.write(Buffer.from(workerData.resultArray.slice(0, length))); 156 | Atomics.store(workerData.statusArray, 0, -1); 157 | Atomics.notify(workerData.statusArray, 0, 1); 158 | } 159 | } 160 | 161 | req.end(); 162 | }).toString()+')()' , { 163 | eval: true, 164 | workerData: workerData 165 | }); 166 | emscriptenhttpconnections[httpConnectionNo] = workerData; 167 | console.log('connected with method', workerData.method, 'to', workerData.url); 168 | return httpConnectionNo++; 169 | }, 170 | emscriptenhttpwrite: function(connectionNo, buffer, length) { 171 | const connection = emscriptenhttpconnections[connectionNo]; 172 | connection.resultArray.set(new Uint8Array(Module.HEAPU8.buffer,buffer,length)); 173 | Atomics.store(connection.statusArray, 0, length); 174 | Atomics.notify(connection.statusArray, 0, 1); 175 | // Wait for write to finish 176 | Atomics.wait(connection.statusArray, 0, length); 177 | }, 178 | emscriptenhttpread: function(connectionNo, buffer) { 179 | const connection = emscriptenhttpconnections[connectionNo]; 180 | 181 | if(connection.statusArray[0] === -1 && connection.method === 'POST') { 182 | // Stop writing 183 | Atomics.store(connection.statusArray, 0, 0); 184 | Atomics.notify(connection.statusArray, 0, 1); 185 | } 186 | Atomics.wait(connection.statusArray, 0, 0); 187 | const bytes_read = connection.statusArray[0]; 188 | 189 | writeArrayToMemory(connection.resultArray.slice(0, bytes_read), buffer); 190 | 191 | //console.log('read with connectionNo', connectionNo, 'length', bytes_read, 'content', 192 | // new TextDecoder('utf-8').decode(connection.resultArray.slice(0, bytes_read))); 193 | Atomics.store(connection.statusArray, 0, 0); 194 | Atomics.notify(connection.statusArray, 0, 1); 195 | 196 | return bytes_read; 197 | }, 198 | emscriptenhttpfree: function(connectionNo) { 199 | delete emscriptenhttpconnections[connectionNo]; 200 | } 201 | }); 202 | } -------------------------------------------------------------------------------- /emscriptenbuild/post.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Javascript functions for emscripten http transport for nodejs and the browser using a webworker 3 | * 4 | * If you can't use a webworker, you can build Release-async or Debug-async versions of wasm-git 5 | * which use async transports, and can be run without a webworker. The lg2 release files are about 6 | * twice the size with this option, and your UI may be affected by doing git operations in the 7 | * main JavaScript thread. 8 | * 9 | * This the non-webworker version (see also post-async.js) 10 | */ 11 | 12 | const emscriptenhttpconnections = {}; 13 | let httpConnectionNo = 0; 14 | 15 | if(ENVIRONMENT_IS_WORKER) { 16 | Object.assign(Module, { 17 | emscriptenhttpconnect: function(url, buffersize, method, headers) { 18 | if(!method) { 19 | method = 'GET'; 20 | } 21 | 22 | const xhr = new XMLHttpRequest(); 23 | xhr.open(method, url, false); 24 | xhr.responseType = 'arraybuffer'; 25 | 26 | if (headers) { 27 | Object.keys(headers).forEach(header => xhr.setRequestHeader(header, headers[header])); 28 | } 29 | 30 | emscriptenhttpconnections[httpConnectionNo] = { 31 | xhr: xhr, 32 | resultbufferpointer: 0, 33 | buffersize: buffersize 34 | }; 35 | 36 | if(method === 'GET') { 37 | xhr.send(); 38 | } 39 | 40 | return httpConnectionNo++; 41 | }, 42 | emscriptenhttpwrite: function(connectionNo, buffer, length) { 43 | const connection = emscriptenhttpconnections[connectionNo]; 44 | const buf = new Uint8Array(Module.HEAPU8.buffer,buffer,length).slice(0); 45 | if(!connection.content) { 46 | connection.content = buf; 47 | } else { 48 | const content = new Uint8Array(connection.content.length + buf.length); 49 | content.set(connection.content); 50 | content.set(buf, connection.content.length); 51 | connection.content = content; 52 | } 53 | }, 54 | emscriptenhttpread: function(connectionNo, buffer, buffersize) { 55 | const connection = emscriptenhttpconnections[connectionNo]; 56 | if(connection.content) { 57 | connection.xhr.send(connection.content.buffer); 58 | connection.content = null; 59 | } 60 | let bytes_read = connection.xhr.response.byteLength - connection.resultbufferpointer; 61 | if (bytes_read > buffersize) { 62 | bytes_read = buffersize; 63 | } 64 | const responseChunk = new Uint8Array(connection.xhr.response, connection.resultbufferpointer, bytes_read); 65 | writeArrayToMemory(responseChunk, buffer); 66 | connection.resultbufferpointer += bytes_read; 67 | return bytes_read; 68 | }, 69 | emscriptenhttpfree: function(connectionNo) { 70 | delete emscriptenhttpconnections[connectionNo]; 71 | } 72 | }); 73 | } else if(ENVIRONMENT_IS_NODE) { 74 | const { Worker } = require('worker_threads'); 75 | 76 | Object.assign(Module, { 77 | emscriptenhttpconnect: function(url, buffersize, method, headers) { 78 | const statusArray = new Int32Array(new SharedArrayBuffer(4)); 79 | Atomics.store(statusArray, 0, method === 'POST' ? -1 : 0); 80 | 81 | const resultBuffer = new SharedArrayBuffer(buffersize); 82 | const resultArray = new Uint8Array(resultBuffer); 83 | const workerData = { 84 | statusArray: statusArray, 85 | resultArray: resultArray, 86 | url: url, 87 | method: method ? method: 'GET', 88 | headers: headers 89 | }; 90 | 91 | new Worker('(' + (function requestWorker() { 92 | const { workerData } = require('worker_threads'); 93 | const req = require(workerData.url.indexOf('https') === 0 ? 'https' : 'http') 94 | .request(workerData.url, { 95 | headers: workerData.headers, 96 | method: workerData.method 97 | }, (res) => { 98 | res.on('data', chunk => { 99 | const previousStatus = workerData.statusArray[0]; 100 | if(previousStatus !== 0) { 101 | Atomics.wait(workerData.statusArray, 0, previousStatus); 102 | } 103 | workerData.resultArray.set(chunk); 104 | Atomics.store(workerData.statusArray, 0, chunk.length); 105 | Atomics.notify(workerData.statusArray, 0, 1); 106 | }); 107 | }); 108 | 109 | if(workerData.method === 'POST') { 110 | while(workerData.statusArray[0] !== 0) { 111 | Atomics.wait(workerData.statusArray, 0, -1); 112 | const length = workerData.statusArray[0]; 113 | if(length === 0) { 114 | break; 115 | } 116 | req.write(Buffer.from(workerData.resultArray.slice(0, length))); 117 | Atomics.store(workerData.statusArray, 0, -1); 118 | Atomics.notify(workerData.statusArray, 0, 1); 119 | } 120 | } 121 | 122 | req.end(); 123 | }).toString()+')()' , { 124 | eval: true, 125 | workerData: workerData 126 | }); 127 | emscriptenhttpconnections[httpConnectionNo] = workerData; 128 | console.log('connected with method', workerData.method, 'to', workerData.url); 129 | return httpConnectionNo++; 130 | }, 131 | emscriptenhttpwrite: function(connectionNo, buffer, length) { 132 | const connection = emscriptenhttpconnections[connectionNo]; 133 | connection.resultArray.set(new Uint8Array(Module.HEAPU8.buffer,buffer,length)); 134 | Atomics.store(connection.statusArray, 0, length); 135 | Atomics.notify(connection.statusArray, 0, 1); 136 | // Wait for write to finish 137 | Atomics.wait(connection.statusArray, 0, length); 138 | }, 139 | emscriptenhttpread: function(connectionNo, buffer) { 140 | const connection = emscriptenhttpconnections[connectionNo]; 141 | 142 | if(connection.statusArray[0] === -1 && connection.method === 'POST') { 143 | // Stop writing 144 | Atomics.store(connection.statusArray, 0, 0); 145 | Atomics.notify(connection.statusArray, 0, 1); 146 | } 147 | Atomics.wait(connection.statusArray, 0, 0); 148 | const bytes_read = connection.statusArray[0]; 149 | 150 | writeArrayToMemory(connection.resultArray.slice(0, bytes_read), buffer); 151 | 152 | //console.log('read with connectionNo', connectionNo, 'length', bytes_read, 'content', 153 | // new TextDecoder('utf-8').decode(connection.resultArray.slice(0, bytes_read))); 154 | Atomics.store(connection.statusArray, 0, 0); 155 | Atomics.notify(connection.statusArray, 0, 1); 156 | 157 | return bytes_read; 158 | }, 159 | emscriptenhttpfree: function(connectionNo) { 160 | delete emscriptenhttpconnections[connectionNo]; 161 | } 162 | }); 163 | } -------------------------------------------------------------------------------- /emscriptenbuild/pre.js: -------------------------------------------------------------------------------- 1 | Object.assign(Module, globalThis.wasmGitModuleOverrides); 2 | 3 | if (!Module.print && !Module.printErr) { 4 | let capturedOutput = null; 5 | let capturedError = null; 6 | let quitStatus; 7 | 8 | Module.print = (msg) => { 9 | if (capturedOutput !== null) { 10 | capturedOutput.push(msg); 11 | } 12 | console.log(msg); 13 | } 14 | 15 | Module.printErr = (msg) => { 16 | if (capturedError !== null) { 17 | capturedError.push(msg); 18 | } 19 | console.error(msg); 20 | } 21 | 22 | Module.quit = (status) => { 23 | quitStatus = status; 24 | }; 25 | 26 | Module.callWithOutput = (args) => { 27 | capturedOutput = []; 28 | capturedError = []; 29 | quitStatus = null; 30 | 31 | Module.callMain(args); 32 | 33 | const ret = capturedOutput.join('\n'); 34 | const err = capturedError.join('\n'); 35 | capturedOutput = null; 36 | capturedError = null; 37 | 38 | if (!quitStatus) { 39 | return ret; 40 | } else { 41 | throw(quitStatus + ': ' + err); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /karma.conf-async.js: -------------------------------------------------------------------------------- 1 | // Karma configuration 2 | // Generated on Sun May 10 2020 17:41:31 GMT+0200 (sentraleuropeisk sommertid) 3 | const gitserver = require('./test-browser/githttpserver.js'); 4 | gitserver.startServer(); 5 | 6 | module.exports = function(config) { 7 | config.set({ 8 | 9 | // base path that will be used to resolve all patterns (eg. files, exclude) 10 | basePath: 'test-browser-async', 11 | 12 | 13 | // frameworks to use 14 | // available frameworks: https://npmjs.org/browse/keyword/karma-adapter 15 | frameworks: ['mocha', 'chai'], 16 | 17 | // list of files / patterns to load in the browser 18 | files: [ 19 | {pattern: 'lg2_async.*', included: false}, 20 | // {pattern: 'async-test.js', included: false}, 21 | {pattern: '**/*.spec.js'} 22 | ], 23 | 24 | // list of files / patterns to exclude 25 | exclude: [ 26 | ], 27 | 28 | proxies: { 29 | '/testrepo.git': 'http://localhost:8080/testrepo.git', 30 | }, 31 | 32 | // preprocess matching files before serving them to the browser 33 | // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor 34 | preprocessors: { 35 | }, 36 | 37 | 38 | // test results reporter to use 39 | // possible values: 'dots', 'progress' 40 | // available reporters: https://npmjs.org/browse/keyword/karma-reporter 41 | reporters: ['progress'], 42 | 43 | 44 | // web server port 45 | port: 9876, 46 | 47 | 48 | // enable / disable colors in the output (reporters and logs) 49 | colors: true, 50 | 51 | 52 | // level of logging 53 | // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG 54 | logLevel: config.LOG_INFO, 55 | 56 | 57 | // enable / disable watching file and executing tests whenever any file changes 58 | autoWatch: true, 59 | 60 | 61 | // start these browsers 62 | // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher 63 | browsers: ['Chrome'], 64 | 65 | 66 | // Continuous Integration mode 67 | // if true, Karma captures browsers, runs the tests and exits 68 | singleRun: false, 69 | 70 | // Concurrency level 71 | // how many browser should be started simultaneous 72 | concurrency: Infinity 73 | }) 74 | } 75 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration 2 | // Generated on Sun May 10 2020 17:41:31 GMT+0200 (sentraleuropeisk sommertid) 3 | const gitserver = require('./test-browser/githttpserver.js'); 4 | gitserver.startServer(); 5 | 6 | module.exports = function(config) { 7 | config.set({ 8 | 9 | // base path that will be used to resolve all patterns (eg. files, exclude) 10 | basePath: 'test-browser', 11 | 12 | 13 | // frameworks to use 14 | // available frameworks: https://npmjs.org/browse/keyword/karma-adapter 15 | frameworks: ['mocha', 'chai'], 16 | 17 | 18 | // list of files / patterns to load in the browser 19 | files: [ 20 | {pattern: 'lg2.*', included: false}, 21 | {pattern: 'worker.js', included: false}, 22 | {pattern: '**/*.spec.js'} 23 | ], 24 | 25 | // list of files / patterns to exclude 26 | exclude: [ 27 | ], 28 | 29 | proxies: { 30 | '/testrepo.git': 'http://localhost:8080/testrepo.git', 31 | '/testremote.git': 'http://localhost:8080/testremote.git', 32 | }, 33 | 34 | // preprocess matching files before serving them to the browser 35 | // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor 36 | preprocessors: { 37 | }, 38 | 39 | 40 | // test results reporter to use 41 | // possible values: 'dots', 'progress' 42 | // available reporters: https://npmjs.org/browse/keyword/karma-reporter 43 | reporters: ['progress'], 44 | 45 | 46 | // web server port 47 | port: 9876, 48 | browserNoActivityTimeout: 10000, 49 | 50 | // enable / disable colors in the output (reporters and logs) 51 | colors: true, 52 | 53 | 54 | // level of logging 55 | // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG 56 | logLevel: config.LOG_INFO, 57 | 58 | 59 | // enable / disable watching file and executing tests whenever any file changes 60 | autoWatch: true, 61 | 62 | 63 | // start these browsers 64 | // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher 65 | browsers: ['Chrome'], 66 | 67 | 68 | // Continuous Integration mode 69 | // if true, Karma captures browsers, runs the tests and exits 70 | singleRun: false, 71 | 72 | // Concurrency level 73 | // how many browser should be started simultaneous 74 | concurrency: Infinity 75 | }) 76 | } 77 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/add.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libgit2 "add" example - shows how to modify the index 3 | * 4 | * Written by the libgit2 contributors 5 | * 6 | * To the extent possible under law, the author(s) have dedicated all copyright 7 | * and related and neighboring rights to this software to the public domain 8 | * worldwide. This software is distributed without any warranty. 9 | * 10 | * You should have received a copy of the CC0 Public Domain Dedication along 11 | * with this software. If not, see 12 | * . 13 | */ 14 | 15 | #include "common.h" 16 | 17 | /** 18 | * The following example demonstrates how to add files with libgit2. 19 | * 20 | * It will use the repository in the current working directory, and act 21 | * on files passed as its parameters. 22 | * 23 | * Recognized options are: 24 | * -v/--verbose: show the file's status after acting on it. 25 | * -n/--dry-run: do not actually change the index. 26 | * -u/--update: update the index instead of adding to it. 27 | */ 28 | 29 | enum index_mode { 30 | INDEX_NONE, 31 | INDEX_ADD, 32 | }; 33 | 34 | struct index_options { 35 | int dry_run; 36 | int verbose; 37 | git_repository *repo; 38 | enum index_mode mode; 39 | int add_update; 40 | }; 41 | 42 | /* Forward declarations for helpers */ 43 | static void parse_opts(const char **repo_path, struct index_options *opts, struct args_info *args); 44 | int print_matched_cb(const char *path, const char *matched_pathspec, void *payload); 45 | 46 | int lg2_add(git_repository *repo, int argc, char **argv) 47 | { 48 | git_index_matched_path_cb matched_cb = NULL; 49 | git_index *index; 50 | git_strarray array = {0}; 51 | struct index_options options = {0}; 52 | struct args_info args = ARGS_INFO_INIT; 53 | 54 | options.mode = INDEX_ADD; 55 | 56 | /* Parse the options & arguments. */ 57 | parse_opts(NULL, &options, &args); 58 | strarray_from_args(&array, &args); 59 | 60 | /* Grab the repository's index. */ 61 | check_lg2(git_repository_index(&index, repo), "Could not open repository index", NULL); 62 | 63 | /* Setup a callback if the requested options need it */ 64 | if (options.verbose || options.dry_run) { 65 | matched_cb = &print_matched_cb; 66 | } 67 | 68 | options.repo = repo; 69 | 70 | /* Perform the requested action with the index and files */ 71 | if (options.add_update) { 72 | git_index_update_all(index, &array, matched_cb, &options); 73 | } else { 74 | git_index_add_all(index, &array, 0, matched_cb, &options); 75 | } 76 | 77 | /* Cleanup memory */ 78 | git_index_write(index); 79 | git_index_free(index); 80 | 81 | return 0; 82 | } 83 | 84 | /* 85 | * This callback is called for each file under consideration by 86 | * git_index_(update|add)_all above. 87 | * It makes uses of the callback's ability to abort the action. 88 | */ 89 | int print_matched_cb(const char *path, const char *matched_pathspec, void *payload) 90 | { 91 | struct index_options *opts = (struct index_options *)(payload); 92 | int ret; 93 | unsigned status; 94 | (void)matched_pathspec; 95 | 96 | /* Get the file status */ 97 | if (git_status_file(&status, opts->repo, path) < 0) 98 | return -1; 99 | 100 | if ((status & GIT_STATUS_WT_MODIFIED) || (status & GIT_STATUS_WT_NEW)) { 101 | printf("add '%s'\n", path); 102 | ret = 0; 103 | } else { 104 | ret = 1; 105 | } 106 | 107 | if (opts->dry_run) 108 | ret = 1; 109 | 110 | return ret; 111 | } 112 | 113 | void init_array(git_strarray *array, int argc, char **argv) 114 | { 115 | unsigned int i; 116 | 117 | array->count = argc; 118 | array->strings = calloc(array->count, sizeof(char *)); 119 | assert(array->strings != NULL); 120 | 121 | for (i = 0; i < array->count; i++) { 122 | array->strings[i] = argv[i]; 123 | } 124 | 125 | return; 126 | } 127 | 128 | void print_usage(void) 129 | { 130 | fprintf(stderr, "usage: add [options] [--] file-spec [file-spec] [...]\n\n"); 131 | fprintf(stderr, "\t-n, --dry-run dry run\n"); 132 | fprintf(stderr, "\t-v, --verbose be verbose\n"); 133 | fprintf(stderr, "\t-u, --update update tracked files\n"); 134 | exit(1); 135 | } 136 | 137 | static void parse_opts(const char **repo_path, struct index_options *opts, struct args_info *args) 138 | { 139 | if (args->argc <= 1) 140 | print_usage(); 141 | 142 | for (args->pos = 1; args->pos < args->argc; ++args->pos) { 143 | const char *curr = args->argv[args->pos]; 144 | 145 | if (curr[0] != '-') { 146 | if (!strcmp("add", curr)) { 147 | opts->mode = INDEX_ADD; 148 | continue; 149 | } else if (opts->mode == INDEX_NONE) { 150 | fprintf(stderr, "missing command: %s", curr); 151 | print_usage(); 152 | break; 153 | } else { 154 | /* We might be looking at a filename */ 155 | break; 156 | } 157 | } else if (match_bool_arg(&opts->verbose, args, "--verbose") || 158 | match_bool_arg(&opts->dry_run, args, "--dry-run") || 159 | match_str_arg(repo_path, args, "--git-dir") || 160 | (opts->mode == INDEX_ADD && match_bool_arg(&opts->add_update, args, "--update"))) { 161 | continue; 162 | } else if (match_bool_arg(NULL, args, "--help")) { 163 | print_usage(); 164 | break; 165 | } else if (match_arg_separator(args)) { 166 | break; 167 | } else { 168 | fprintf(stderr, "Unsupported option %s.\n", curr); 169 | print_usage(); 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/checkout.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libgit2 "checkout" example - shows how to perform checkouts 3 | * 4 | * Written by the libgit2 contributors 5 | * 6 | * To the extent possible under law, the author(s) have dedicated all copyright 7 | * and related and neighboring rights to this software to the public domain 8 | * worldwide. This software is distributed without any warranty. 9 | * 10 | * You should have received a copy of the CC0 Public Domain Dedication along 11 | * with this software. If not, see 12 | * . 13 | */ 14 | 15 | #include "common.h" 16 | 17 | /* Define the printf format specifer to use for size_t output */ 18 | #if defined(_MSC_VER) || defined(__MINGW32__) 19 | # define PRIuZ "Iu" 20 | # define PRIxZ "Ix" 21 | # define PRIdZ "Id" 22 | #else 23 | # define PRIuZ "zu" 24 | # define PRIxZ "zx" 25 | # define PRIdZ "zd" 26 | #endif 27 | 28 | /** 29 | * The following example demonstrates how to do checkouts with libgit2. 30 | * 31 | * Recognized options are : 32 | * -b: create new branch 33 | * --force: force the checkout to happen. 34 | * --[no-]progress: show checkout progress, on by default. 35 | * --perf: show performance data. 36 | */ 37 | 38 | typedef struct { 39 | int force : 1; 40 | int progress : 1; 41 | int perf : 1; 42 | } checkout_options; 43 | 44 | static void print_usage(void) 45 | { 46 | fprintf(stderr, "usage: checkout [options] \n" 47 | "Options are :\n" 48 | " -b: create new branch" 49 | " --git-dir: use the following git repository.\n" 50 | " --force: force the checkout.\n" 51 | " --[no-]progress: show checkout progress.\n" 52 | " --perf: show performance data.\n"); 53 | exit(1); 54 | } 55 | 56 | static void parse_options(const char **repo_path, checkout_options *opts, struct args_info *args) 57 | { 58 | if (args->argc <= 1) 59 | print_usage(); 60 | 61 | memset(opts, 0, sizeof(*opts)); 62 | 63 | /* Default values */ 64 | opts->progress = 1; 65 | 66 | for (args->pos = 1; args->pos < args->argc; ++args->pos) { 67 | const char *curr = args->argv[args->pos]; 68 | int bool_arg; 69 | 70 | if (match_arg_separator(args)) { 71 | break; 72 | } else if (!strcmp(curr, "--force")) { 73 | opts->force = 1; 74 | } else if (match_bool_arg(&bool_arg, args, "--progress")) { 75 | opts->progress = bool_arg; 76 | } else if (match_bool_arg(&bool_arg, args, "--perf")) { 77 | opts->perf = bool_arg; 78 | } else if (match_str_arg(repo_path, args, "--git-dir")) { 79 | continue; 80 | } else { 81 | break; 82 | } 83 | } 84 | } 85 | 86 | /** 87 | * This function is called to report progression, ie. it's called once with 88 | * a NULL path and the number of total steps, then for each subsequent path, 89 | * the current completed_step value. 90 | */ 91 | static void print_checkout_progress(const char *path, size_t completed_steps, size_t total_steps, void *payload) 92 | { 93 | (void)payload; 94 | if (path == NULL) { 95 | printf("checkout started: %" PRIuZ " steps\n", total_steps); 96 | } else { 97 | printf("checkout: %s %" PRIuZ "/%" PRIuZ "\n", path, completed_steps, total_steps); 98 | } 99 | } 100 | 101 | /** 102 | * This function is called when the checkout completes, and is used to report the 103 | * number of syscalls performed. 104 | */ 105 | static void print_perf_data(const git_checkout_perfdata *perfdata, void *payload) 106 | { 107 | (void)payload; 108 | printf("perf: stat: %" PRIuZ " mkdir: %" PRIuZ " chmod: %" PRIuZ "\n", 109 | perfdata->stat_calls, perfdata->mkdir_calls, perfdata->chmod_calls); 110 | } 111 | 112 | /** 113 | * This is the main "checkout " function, responsible for performing 114 | * a branch-based checkout. 115 | */ 116 | static int perform_checkout_ref(git_repository *repo, git_annotated_commit *target, const char *target_ref, checkout_options *opts) 117 | { 118 | git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; 119 | git_reference *ref = NULL, *branch = NULL; 120 | git_commit *target_commit = NULL; 121 | int err; 122 | 123 | /** Setup our checkout options from the parsed options */ 124 | checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE; 125 | if (opts->force) 126 | checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE; 127 | 128 | if (opts->progress) 129 | checkout_opts.progress_cb = print_checkout_progress; 130 | 131 | if (opts->perf) 132 | checkout_opts.perfdata_cb = print_perf_data; 133 | 134 | /** Grab the commit we're interested to move to */ 135 | err = git_commit_lookup(&target_commit, repo, git_annotated_commit_id(target)); 136 | if (err != 0) { 137 | fprintf(stderr, "failed to lookup commit: %s\n", git_error_last()->message); 138 | goto cleanup; 139 | } 140 | 141 | /** 142 | * Perform the checkout so the workdir corresponds to what target_commit 143 | * contains. 144 | * 145 | * Note that it's okay to pass a git_commit here, because it will be 146 | * peeled to a tree. 147 | */ 148 | err = git_checkout_tree(repo, (const git_object *)target_commit, &checkout_opts); 149 | if (err != 0) { 150 | fprintf(stderr, "failed to checkout tree: %s\n", git_error_last()->message); 151 | goto cleanup; 152 | } 153 | 154 | /** 155 | * Now that the checkout has completed, we have to update HEAD. 156 | * 157 | * Depending on the "origin" of target (ie. it's an OID or a branch name), 158 | * we might need to detach HEAD. 159 | */ 160 | if (git_annotated_commit_ref(target)) { 161 | const char *target_head; 162 | 163 | if ((err = git_reference_lookup(&ref, repo, git_annotated_commit_ref(target))) < 0) 164 | goto error; 165 | 166 | if (git_reference_is_remote(ref)) { 167 | if ((err = git_branch_create_from_annotated(&branch, repo, target_ref, target, 0)) < 0) 168 | goto error; 169 | target_head = git_reference_name(branch); 170 | } else { 171 | target_head = git_annotated_commit_ref(target); 172 | } 173 | 174 | err = git_repository_set_head(repo, target_head); 175 | } else { 176 | err = git_repository_set_head_detached_from_annotated(repo, target); 177 | } 178 | 179 | error: 180 | if (err != 0) { 181 | fprintf(stderr, "failed to update HEAD reference: %s\n", git_error_last()->message); 182 | goto cleanup; 183 | } 184 | 185 | cleanup: 186 | git_commit_free(target_commit); 187 | git_reference_free(branch); 188 | git_reference_free(ref); 189 | 190 | return err; 191 | } 192 | 193 | /** 194 | * This corresponds to `git switch --guess`: if a given ref does 195 | * not exist, git will by default try to guess the reference by 196 | * seeing whether any remote has a branch called . If there 197 | * is a single remote only that has it, then it is assumed to be 198 | * the desired reference and a local branch is created for it. 199 | * 200 | * The following is a simplified implementation. It will not try 201 | * to check whether the ref is unique across all remotes. 202 | */ 203 | static int guess_refish(git_annotated_commit **out, git_repository *repo, const char *ref) 204 | { 205 | git_strarray remotes = { NULL, 0 }; 206 | git_reference *remote_ref = NULL; 207 | int error; 208 | size_t i; 209 | 210 | if ((error = git_remote_list(&remotes, repo)) < 0) 211 | goto out; 212 | 213 | for (i = 0; i < remotes.count; i++) { 214 | char *refname = NULL; 215 | size_t reflen; 216 | 217 | reflen = snprintf(refname, 0, "refs/remotes/%s/%s", remotes.strings[i], ref); 218 | if ((refname = malloc(reflen + 1)) == NULL) { 219 | error = -1; 220 | goto next; 221 | } 222 | snprintf(refname, reflen + 1, "refs/remotes/%s/%s", remotes.strings[i], ref); 223 | 224 | if ((error = git_reference_lookup(&remote_ref, repo, refname)) < 0) 225 | goto next; 226 | 227 | break; 228 | next: 229 | free(refname); 230 | if (error < 0 && error != GIT_ENOTFOUND) 231 | break; 232 | } 233 | 234 | if (!remote_ref) { 235 | error = GIT_ENOTFOUND; 236 | goto out; 237 | } 238 | 239 | if ((error = git_annotated_commit_from_ref(out, repo, remote_ref)) < 0) 240 | goto out; 241 | 242 | out: 243 | git_reference_free(remote_ref); 244 | git_strarray_dispose(&remotes); 245 | return error; 246 | } 247 | 248 | /** That example's entry point */ 249 | int lg2_checkout(git_repository *repo, int argc, char **argv) 250 | { 251 | struct args_info args = ARGS_INFO_INIT; 252 | checkout_options opts; 253 | git_repository_state_t state; 254 | git_annotated_commit *checkout_target = NULL; 255 | git_reference *new_branch_ref = NULL; 256 | git_object *target_obj = NULL; 257 | git_commit *target_commit = NULL; 258 | git_reference *branch_ref = NULL; 259 | git_reference *upstream_ref = NULL; 260 | 261 | const char *opt_new_branch; 262 | 263 | int err = 0; 264 | const char *path = "."; 265 | 266 | /** Parse our command line options */ 267 | parse_options(&path, &opts, &args); 268 | 269 | /** Make sure we're not about to checkout while something else is going on */ 270 | state = git_repository_state(repo); 271 | if (state != GIT_REPOSITORY_STATE_NONE) { 272 | fprintf(stderr, "repository is in unexpected state %d\n", state); 273 | goto cleanup; 274 | } 275 | 276 | if (optional_str_arg(&opt_new_branch, &args, "-b", "")) { 277 | err = git_revparse_single(&target_obj, repo, "HEAD"); 278 | if (err != 0) { 279 | fprintf(stderr, "error: %s\n", git_error_last()->message); 280 | goto cleanup; 281 | } 282 | err = git_commit_lookup(&target_commit, repo, git_object_id(target_obj)); 283 | if (err != 0) { 284 | fprintf(stderr, "error looking up commit: %s\n", git_error_last()->message); 285 | goto cleanup; 286 | } 287 | err = git_branch_create(&new_branch_ref, repo, opt_new_branch, target_commit, 0); 288 | if (err != 0) { 289 | fprintf(stderr, "error creating branch: %s\n", git_error_last()->message); 290 | goto cleanup; 291 | } 292 | } 293 | 294 | if (match_arg_separator(&args)) { 295 | /** 296 | * Try to checkout the given path(s) 297 | */ 298 | 299 | git_checkout_options copts = GIT_CHECKOUT_OPTIONS_INIT; 300 | git_strarray paths; 301 | 302 | copts.checkout_strategy = GIT_CHECKOUT_FORCE; 303 | 304 | paths.count = args.argc - args.pos; 305 | 306 | if (paths.count == 0) { 307 | fprintf(stderr, "error: no paths specified\n"); 308 | return GIT_ERROR_INVALID; 309 | } 310 | 311 | paths.strings = &args.argv[args.pos]; 312 | copts.paths = paths; 313 | 314 | err = git_checkout_head(repo, &copts); 315 | if (err != 0) { 316 | fprintf(stderr, "error: %s\n", git_error_last()->message); 317 | } 318 | return err; 319 | } else { 320 | /** 321 | * Try to resolve a "refish" argument to a target libgit2 can use 322 | */ 323 | 324 | const char *branchname; 325 | char upstreamname[1024] = "origin/"; 326 | 327 | if ((err = resolve_refish(&checkout_target, repo, args.argv[args.pos])) < 0 && 328 | (err = guess_refish(&checkout_target, repo, args.argv[args.pos])) < 0) { 329 | fprintf(stderr, "failed to resolve %s: %s\n", args.argv[args.pos], git_error_last()->message); 330 | goto cleanup; 331 | } 332 | err = perform_checkout_ref(repo, checkout_target, args.argv[args.pos], &opts); 333 | if (err != 0) { 334 | fprintf(stderr, "failed to checkout %s: %s\n", args.argv[args.pos], git_error_last()->message); 335 | goto cleanup; 336 | } 337 | err = git_repository_head(&branch_ref, repo); 338 | if (!err && git_branch_upstream(&upstream_ref, branch_ref) == GIT_ENOTFOUND) { 339 | branchname = git_reference_shorthand(branch_ref); 340 | strcat(upstreamname, branchname); 341 | 342 | err = git_branch_set_upstream(branch_ref,upstreamname); 343 | if (err == GIT_ENOTFOUND) { 344 | // no upstream exists 345 | git_error_clear(); 346 | err = 0; 347 | } 348 | if (err != 0) { 349 | fprintf(stderr, "error: %s\n", git_error_last()->message); 350 | goto cleanup; 351 | } 352 | printf("Branch '%s' set up to track remote branch '%s'\n", branchname, upstreamname); 353 | } 354 | } 355 | 356 | cleanup: 357 | git_commit_free(target_commit); 358 | git_object_free(target_obj); 359 | 360 | git_annotated_commit_free(checkout_target); 361 | git_reference_free(new_branch_ref); 362 | git_reference_free(branch_ref); 363 | git_reference_free(upstream_ref); 364 | return err; 365 | } 366 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/commit.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libgit2 "commit" example - shows how to create a git commit 3 | * 4 | * Written by the libgit2 contributors 5 | * 6 | * To the extent possible under law, the author(s) have dedicated all copyright 7 | * and related and neighboring rights to this software to the public domain 8 | * worldwide. This software is distributed without any warranty. 9 | * 10 | * You should have received a copy of the CC0 Public Domain Dedication along 11 | * with this software. If not, see 12 | * . 13 | */ 14 | 15 | #include "common.h" 16 | 17 | /** 18 | * This example demonstrates the libgit2 commit APIs to roughly 19 | * simulate `git commit` with the commit message argument. 20 | * 21 | * This does not have: 22 | * 23 | * - Robust error handling 24 | * - Most of the `git commit` options 25 | * 26 | * This does have: 27 | * 28 | * - Example of performing a git commit with a comment 29 | * 30 | */ 31 | int lg2_commit(git_repository *repo, int argc, char **argv) 32 | { 33 | const char *opt = argv[1]; 34 | const char *comment = argv[2]; 35 | int error; 36 | 37 | git_oid commit_oid,tree_oid; 38 | git_tree *tree; 39 | git_index *index; 40 | git_object *parent = NULL; 41 | git_reference *ref = NULL; 42 | git_signature *signature; 43 | 44 | /* Validate args */ 45 | if (argc < 3 || strcmp(opt, "-m") != 0) { 46 | printf ("USAGE: %s -m \n", argv[0]); 47 | return -1; 48 | } 49 | 50 | error = git_revparse_ext(&parent, &ref, repo, "HEAD"); 51 | if (error == GIT_ENOTFOUND) { 52 | printf("HEAD not found. Creating first commit\n"); 53 | error = 0; 54 | } else if (error != 0) { 55 | const git_error *err = git_error_last(); 56 | if (err) printf("ERROR %d: %s\n", err->klass, err->message); 57 | else printf("ERROR %d: no detailed info\n", error); 58 | } 59 | 60 | check_lg2(git_repository_index(&index, repo), "Could not open repository index", NULL); 61 | check_lg2(git_index_write_tree(&tree_oid, index), "Could not write tree", NULL);; 62 | check_lg2(git_index_write(index), "Could not write index", NULL);; 63 | 64 | check_lg2(git_tree_lookup(&tree, repo, &tree_oid), "Error looking up tree", NULL); 65 | 66 | check_lg2(git_signature_default(&signature, repo), "Error creating signature", NULL); 67 | 68 | if (git_repository_state(repo) == GIT_REPOSITORY_STATE_MERGE) { 69 | git_object * mergehead = NULL; 70 | git_reference * mergeheadref = NULL; 71 | 72 | check_lg2(git_revparse_ext(&mergehead, &mergeheadref, repo, "MERGE_HEAD"), "Error looking up MERGE_HEAD", NULL); 73 | check_lg2(git_commit_create_v( 74 | &commit_oid, 75 | repo, 76 | "HEAD", 77 | signature, 78 | signature, 79 | NULL, 80 | comment, 81 | tree, 82 | 2, parent, mergehead), "Error creating commit", NULL); 83 | git_repository_state_cleanup(repo); 84 | } else { 85 | check_lg2(git_commit_create_v( 86 | &commit_oid, 87 | repo, 88 | "HEAD", 89 | signature, 90 | signature, 91 | NULL, 92 | comment, 93 | tree, 94 | parent ? 1 : 0, parent), "Error creating commit", NULL); 95 | } 96 | git_index_free(index); 97 | git_signature_free(signature); 98 | git_tree_free(tree); 99 | 100 | return error; 101 | } 102 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Utilities library for libgit2 examples 3 | * 4 | * Written by the libgit2 contributors 5 | * 6 | * To the extent possible under law, the author(s) have dedicated all copyright 7 | * and related and neighboring rights to this software to the public domain 8 | * worldwide. This software is distributed without any warranty. 9 | * 10 | * You should have received a copy of the CC0 Public Domain Dedication along 11 | * with this software. If not, see 12 | * . 13 | */ 14 | #ifndef INCLUDE_examples_common_h__ 15 | #define INCLUDE_examples_common_h__ 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #ifdef _WIN32 27 | # include 28 | # include 29 | # define open _open 30 | # define read _read 31 | # define close _close 32 | # define ssize_t int 33 | # define sleep(a) Sleep(a * 1000) 34 | #else 35 | # include 36 | #endif 37 | 38 | #ifndef PRIuZ 39 | /* Define the printf format specifer to use for size_t output */ 40 | #if defined(_MSC_VER) || defined(__MINGW32__) 41 | # define PRIuZ "Iu" 42 | #else 43 | # define PRIuZ "zu" 44 | #endif 45 | #endif 46 | 47 | #ifdef _MSC_VER 48 | #define snprintf sprintf_s 49 | #define strcasecmp strcmpi 50 | #endif 51 | 52 | #define ARRAY_SIZE(x) (sizeof(x)/sizeof(*x)) 53 | #define UNUSED(x) (void)(x) 54 | 55 | #include "args.h" 56 | 57 | extern int lg2_add(git_repository *repo, int argc, char **argv); 58 | extern int lg2_blame(git_repository *repo, int argc, char **argv); 59 | extern int lg2_cat_file(git_repository *repo, int argc, char **argv); 60 | extern int lg2_checkout(git_repository *repo, int argc, char **argv); 61 | extern int lg2_clone(git_repository *repo, int argc, char **argv); 62 | extern int lg2_commit(git_repository *repo, int argc, char **argv); 63 | extern int lg2_config(git_repository *repo, int argc, char **argv); 64 | extern int lg2_describe(git_repository *repo, int argc, char **argv); 65 | extern int lg2_diff(git_repository *repo, int argc, char **argv); 66 | extern int lg2_fetch(git_repository *repo, int argc, char **argv); 67 | extern int lg2_for_each_ref(git_repository *repo, int argc, char **argv); 68 | extern int lg2_general(git_repository *repo, int argc, char **argv); 69 | extern int lg2_index_pack(git_repository *repo, int argc, char **argv); 70 | extern int lg2_init(git_repository *repo, int argc, char **argv); 71 | extern int lg2_log(git_repository *repo, int argc, char **argv); 72 | extern int lg2_ls_files(git_repository *repo, int argc, char **argv); 73 | extern int lg2_ls_remote(git_repository *repo, int argc, char **argv); 74 | extern int lg2_merge(git_repository *repo, int argc, char **argv); 75 | extern int lg2_push(git_repository *repo, int argc, char **argv); 76 | extern int lg2_remote(git_repository *repo, int argc, char **argv); 77 | extern int lg2_reset(git_repository *repo, int argc, char **argv); 78 | extern int lg2_revert(git_repository *repo, int argc, char **argv); 79 | extern int lg2_rev_list(git_repository *repo, int argc, char **argv); 80 | extern int lg2_rev_parse(git_repository *repo, int argc, char **argv); 81 | extern int lg2_show_index(git_repository *repo, int argc, char **argv); 82 | extern int lg2_stash(git_repository *repo, int argc, char **argv); 83 | extern int lg2_status(git_repository *repo, int argc, char **argv); 84 | extern int lg2_tag(git_repository *repo, int argc, char **argv); 85 | 86 | /** 87 | * Check libgit2 error code, printing error to stderr on failure and 88 | * exiting the program. 89 | */ 90 | extern void check_lg2(int error, const char *message, const char *extra); 91 | 92 | /** 93 | * Read a file into a buffer 94 | * 95 | * @param path The path to the file that shall be read 96 | * @return NUL-terminated buffer if the file was successfully read, NULL-pointer otherwise 97 | */ 98 | extern char *read_file(const char *path); 99 | 100 | /** 101 | * Exit the program, printing error to stderr 102 | */ 103 | extern void fatal(const char *message, const char *extra); 104 | 105 | /** 106 | * Basic output function for plain text diff output 107 | * Pass `FILE*` such as `stdout` or `stderr` as payload (or NULL == `stdout`) 108 | */ 109 | extern int diff_output( 110 | const git_diff_delta*, const git_diff_hunk*, const git_diff_line*, void*); 111 | 112 | /** 113 | * Convert a treeish argument to an actual tree; this will call check_lg2 114 | * and exit the program if `treeish` cannot be resolved to a tree 115 | */ 116 | extern void treeish_to_tree( 117 | git_tree **out, git_repository *repo, const char *treeish); 118 | 119 | /** 120 | * A realloc that exits on failure 121 | */ 122 | extern void *xrealloc(void *oldp, size_t newsz); 123 | 124 | /** 125 | * Convert a refish to an annotated commit. 126 | */ 127 | extern int resolve_refish(git_annotated_commit **commit, git_repository *repo, const char *refish); 128 | 129 | /** 130 | * Acquire credentials via command line 131 | */ 132 | extern int cred_acquire_cb(git_credential **out, 133 | const char *url, 134 | const char *username_from_url, 135 | unsigned int allowed_types, 136 | void *payload); 137 | 138 | #endif 139 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/lg2.c: -------------------------------------------------------------------------------- 1 | #include "common.h" 2 | 3 | /* This part is not strictly libgit2-dependent, but you can use this 4 | * as a starting point for a git-like tool */ 5 | 6 | typedef int (*git_command_fn)(git_repository *, int , char **); 7 | 8 | struct { 9 | char *name; 10 | git_command_fn fn; 11 | char requires_repo; 12 | } commands[] = { 13 | { "add", lg2_add, 1 }, 14 | { "blame", lg2_blame, 1 }, 15 | { "cat-file", lg2_cat_file, 1 }, 16 | { "checkout", lg2_checkout, 1 }, 17 | { "clone", lg2_clone, 0 }, 18 | { "commit", lg2_commit, 1 }, 19 | { "config", lg2_config, 1 }, 20 | { "describe", lg2_describe, 1 }, 21 | { "diff", lg2_diff, 1 }, 22 | { "fetch", lg2_fetch, 1 }, 23 | { "for-each-ref", lg2_for_each_ref, 1 }, 24 | { "general", lg2_general, 0 }, 25 | { "index-pack", lg2_index_pack, 1 }, 26 | { "init", lg2_init, 0 }, 27 | { "log", lg2_log, 1 }, 28 | { "ls-files", lg2_ls_files, 1 }, 29 | { "ls-remote", lg2_ls_remote, 1 }, 30 | { "merge", lg2_merge, 1 }, 31 | { "push", lg2_push, 1 }, 32 | { "remote", lg2_remote, 1 }, 33 | { "reset", lg2_reset, 1 }, 34 | { "revert", lg2_revert, 1 }, 35 | { "rev-list", lg2_rev_list, 1 }, 36 | { "rev-parse", lg2_rev_parse, 1 }, 37 | { "show-index", lg2_show_index, 0 }, 38 | { "stash", lg2_stash, 1 }, 39 | { "status", lg2_status, 1 }, 40 | { "tag", lg2_tag, 1 }, 41 | }; 42 | 43 | static int run_command(git_command_fn fn, git_repository *repo, struct args_info args) 44 | { 45 | int error; 46 | 47 | /* Run the command. If something goes wrong, print the error message to stderr */ 48 | error = fn(repo, args.argc - args.pos, &args.argv[args.pos]); 49 | if (error < 0) { 50 | if (git_error_last() == NULL) 51 | fprintf(stderr, "Error without message"); 52 | else 53 | fprintf(stderr, "Bad news:\n %s\n", git_error_last()->message); 54 | } 55 | 56 | return !!error; 57 | } 58 | 59 | static int usage(const char *prog) 60 | { 61 | size_t i; 62 | 63 | fprintf(stderr, "usage: %s ...\n\nAvailable commands:\n\n", prog); 64 | for (i = 0; i < ARRAY_SIZE(commands); i++) 65 | fprintf(stderr, "\t%s\n", commands[i].name); 66 | 67 | exit(EXIT_FAILURE); 68 | } 69 | 70 | int main(int argc, char **argv) 71 | { 72 | struct args_info args = ARGS_INFO_INIT; 73 | git_repository *repo = NULL; 74 | const char *git_dir = NULL; 75 | int return_code = 1; 76 | size_t i; 77 | 78 | if (argc < 2) 79 | usage(argv[0]); 80 | 81 | git_libgit2_init(); 82 | 83 | for (args.pos = 1; args.pos < args.argc; ++args.pos) { 84 | char *a = args.argv[args.pos]; 85 | 86 | if (a[0] != '-') { 87 | /* non-arg */ 88 | break; 89 | } else if (optional_str_arg(&git_dir, &args, "--git-dir", ".git")) { 90 | continue; 91 | } else if (match_arg_separator(&args)) { 92 | break; 93 | } 94 | } 95 | 96 | if (args.pos == args.argc) 97 | usage(argv[0]); 98 | 99 | if (!git_dir) 100 | git_dir = "."; 101 | 102 | for (i = 0; i < ARRAY_SIZE(commands); ++i) { 103 | if (strcmp(args.argv[args.pos], commands[i].name)) 104 | continue; 105 | 106 | /* 107 | * Before running the actual command, create an instance 108 | * of the local repository and pass it to the function. 109 | * */ 110 | if (commands[i].requires_repo) { 111 | check_lg2(git_repository_open_ext(&repo, git_dir, 0, NULL), 112 | "Unable to open repository '%s'", git_dir); 113 | } 114 | 115 | return_code = run_command(commands[i].fn, repo, args); 116 | goto shutdown; 117 | } 118 | 119 | fprintf(stderr, "Command not found: %s\n", argv[1]); 120 | 121 | shutdown: 122 | git_repository_free(repo); 123 | git_libgit2_shutdown(); 124 | 125 | return return_code; 126 | } 127 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/push.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libgit2 "push" example - shows how to push to remote 3 | * 4 | * Written by the libgit2 contributors 5 | * 6 | * To the extent possible under law, the author(s) have dedicated all copyright 7 | * and related and neighboring rights to this software to the public domain 8 | * worldwide. This software is distributed without any warranty. 9 | * 10 | * You should have received a copy of the CC0 Public Domain Dedication along 11 | * with this software. If not, see 12 | * . 13 | */ 14 | 15 | #include "common.h" 16 | 17 | /** 18 | * This example demonstrates the libgit2 push API to roughly 19 | * simulate `git push`. 20 | * 21 | * This does not have: 22 | * 23 | * - Robust error handling 24 | * - Any of the `git push` options 25 | * 26 | * This does have: 27 | * 28 | * - Example of push to origin/master 29 | * 30 | */ 31 | 32 | /** Entry point for this command */ 33 | int lg2_push(git_repository *repo, int argc, char **argv) { 34 | git_push_options options; 35 | git_remote* remote = NULL; 36 | char *refspec = NULL; 37 | git_reference* head_ref; 38 | 39 | git_reference_lookup(&head_ref, repo, "HEAD"); 40 | refspec = git_reference_symbolic_target(head_ref); 41 | 42 | const git_strarray refspecs = { 43 | &refspec, 44 | 1 45 | }; 46 | 47 | /* Validate args */ 48 | if (argc > 1) { 49 | printf ("USAGE: %s\n\nsorry, no arguments supported yet\n", argv[0]); 50 | return -1; 51 | } 52 | 53 | check_lg2(git_remote_lookup(&remote, repo, "origin" ), "Unable to lookup remote", NULL); 54 | 55 | check_lg2(git_push_options_init(&options, GIT_PUSH_OPTIONS_VERSION ), "Error initializing push", NULL); 56 | 57 | check_lg2(git_remote_push(remote, &refspecs, &options), "Error pushing", NULL); 58 | 59 | printf("pushed\n"); 60 | git_reference_free(head_ref); 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/reset.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libgit2 "reset" example - Reset current HEAD to the specified state 3 | * 4 | * Written by the libgit2 contributors 5 | * 6 | * To the extent possible under law, the author(s) have dedicated all copyright 7 | * and related and neighboring rights to this software to the public domain 8 | * worldwide. This software is distributed without any warranty. 9 | * 10 | * You should have received a copy of the CC0 Public Domain Dedication along 11 | * with this software. If not, see 12 | * . 13 | */ 14 | 15 | #include "common.h" 16 | 17 | /** 18 | * The following example demonstrates how to reset libgit2. 19 | * 20 | * It will use the repository in the current working directory, and reset to the specified revspec 21 | * 22 | * Recognized options are: 23 | * --hard: reset hard 24 | * --soft: reset soft 25 | */ 26 | 27 | int lg2_reset(git_repository *repo, int argc, char **argv) 28 | { 29 | git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT; 30 | git_commit *target_commit = NULL; 31 | git_revspec revspec; 32 | git_reset_t reset_type = GIT_RESET_MIXED; 33 | int err; 34 | 35 | err = git_revparse(&revspec, repo, argv[argc - 1]); 36 | if (err != 0) 37 | { 38 | fprintf(stderr, "failed to lookup rev: %s\n", git_error_last()->message); 39 | goto cleanup; 40 | } 41 | err = git_commit_lookup(&target_commit, repo, revspec.from); 42 | if (err != 0) 43 | { 44 | fprintf(stderr, "failed to lookup commit: %s\n", git_error_last()->message); 45 | goto cleanup; 46 | } 47 | 48 | if (argc > 1) 49 | { 50 | if (!strcmp(argv[argc - 2], "--hard")) 51 | { 52 | reset_type = GIT_RESET_HARD; 53 | } 54 | else if (!strcmp(argv[argc - 2], "--soft")) 55 | { 56 | reset_type = GIT_RESET_SOFT; 57 | } 58 | } 59 | err = git_reset(repo, target_commit, reset_type, &checkout_opts); 60 | if (err != 0) 61 | { 62 | fprintf(stderr, "reset error: %s\n", git_error_last()->message); 63 | goto cleanup; 64 | } 65 | cleanup: 66 | git_commit_free(target_commit); 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/revert.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libgit2 "revert" example - shows how to git revert 3 | * 4 | * Written by the libgit2 contributors 5 | * 6 | * To the extent possible under law, the author(s) have dedicated all copyright 7 | * and related and neighboring rights to this software to the public domain 8 | * worldwide. This software is distributed without any warranty. 9 | * 10 | * You should have received a copy of the CC0 Public Domain Dedication along 11 | * with this software. If not, see 12 | * . 13 | */ 14 | 15 | #include "common.h" 16 | 17 | /** 18 | * This example demonstrates the libgit2 revert APIs to roughly 19 | * simulate `git revert`. 20 | * 21 | * This does not have: 22 | * 23 | * - Robust error handling 24 | * - Most of the `git revert` options 25 | * 26 | */ 27 | int lg2_revert(git_repository *repo, int argc, char **argv) 28 | { 29 | git_revert_options revert_options; 30 | git_commit *target_commit = NULL; 31 | git_revspec revspec; 32 | int err = 0; 33 | 34 | check_lg2(git_revert_options_init(&revert_options, GIT_REVERT_OPTIONS_VERSION), git_error_last()->message, NULL); 35 | 36 | err = git_revparse(&revspec, repo, argv[argc - 1]); 37 | if (err != 0) 38 | { 39 | fprintf(stderr, "failed to lookup rev: %s\n", git_error_last()->message); 40 | goto cleanup; 41 | } 42 | err = git_commit_lookup(&target_commit, repo, revspec.from); 43 | if (err != 0) 44 | { 45 | fprintf(stderr, "failed to lookup commit: %s\n", git_error_last()->message); 46 | goto cleanup; 47 | } 48 | err = git_revert(repo, target_commit, &revert_options); 49 | cleanup: 50 | git_commit_free(target_commit); 51 | 52 | return err; 53 | } 54 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/stash.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libgit2 "stash" example - shows how to use the stash API 3 | * 4 | * Written by the libgit2 contributors 5 | * 6 | * To the extent possible under law, the author(s) have dedicated all copyright 7 | * and related and neighboring rights to this software to the public domain 8 | * worldwide. This software is distributed without any warranty. 9 | * 10 | * You should have received a copy of the CC0 Public Domain Dedication along 11 | * with this software. If not, see 12 | * . 13 | */ 14 | 15 | #include 16 | 17 | #include "common.h" 18 | 19 | enum subcmd { 20 | SUBCMD_APPLY, 21 | SUBCMD_LIST, 22 | SUBCMD_POP, 23 | SUBCMD_PUSH, 24 | SUBCMD_DROP, 25 | }; 26 | 27 | struct opts { 28 | enum subcmd cmd; 29 | int argc; 30 | char **argv; 31 | }; 32 | 33 | static void usage(const char *fmt, ...) 34 | { 35 | va_list ap; 36 | 37 | fputs("usage: git stash list\n", stderr); 38 | fputs(" or: git stash ( pop | apply | drop )\n", stderr); 39 | fputs(" or: git stash [push]\n", stderr); 40 | fputs("\n", stderr); 41 | 42 | va_start(ap, fmt); 43 | vfprintf(stderr, fmt, ap); 44 | va_end(ap); 45 | 46 | exit(1); 47 | } 48 | 49 | static void parse_subcommand(struct opts *opts, int argc, char *argv[]) 50 | { 51 | char *arg = (argc < 2) ? "push" : argv[1]; 52 | enum subcmd cmd; 53 | 54 | if (!strcmp(arg, "apply")) { 55 | cmd = SUBCMD_APPLY; 56 | } else if (!strcmp(arg, "list")) { 57 | cmd = SUBCMD_LIST; 58 | } else if (!strcmp(arg, "pop")) { 59 | cmd = SUBCMD_POP; 60 | } else if (!strcmp(arg, "push")) { 61 | cmd = SUBCMD_PUSH; 62 | } else if (!strcmp(arg, "drop")) { 63 | cmd = SUBCMD_DROP; 64 | } else { 65 | usage("invalid command %s", arg); 66 | return; 67 | } 68 | 69 | opts->cmd = cmd; 70 | opts->argc = (argc < 2) ? argc - 1 : argc - 2; 71 | opts->argv = argv; 72 | } 73 | 74 | static int cmd_apply(git_repository *repo, struct opts *opts) 75 | { 76 | unsigned long index = strtoul(opts->argc ? opts->argv[2] : "0", NULL, 10); 77 | printf("Applying index: %lu\n", index); 78 | check_lg2(git_stash_apply(repo, index, NULL), 79 | "Unable to apply stash", NULL); 80 | 81 | return 0; 82 | } 83 | 84 | static int list_stash_cb(size_t index, const char *message, 85 | const git_oid *stash_id, void *payload) 86 | { 87 | UNUSED(stash_id); 88 | UNUSED(payload); 89 | printf("stash@{%"PRIuZ"}: %s\n", index, message); 90 | return 0; 91 | } 92 | 93 | static int cmd_list(git_repository *repo, struct opts *opts) 94 | { 95 | if (opts->argc) 96 | usage("list does not accept any parameters"); 97 | 98 | check_lg2(git_stash_foreach(repo, list_stash_cb, NULL), 99 | "Unable to list stashes", NULL); 100 | 101 | return 0; 102 | } 103 | 104 | static int cmd_push(git_repository *repo, struct opts *opts) 105 | { 106 | git_signature *signature; 107 | git_commit *stash; 108 | git_oid stashid; 109 | 110 | if (opts->argc) 111 | usage("push does not accept any parameters"); 112 | 113 | check_lg2(git_signature_default(&signature, repo), 114 | "Unable to get signature", NULL); 115 | check_lg2(git_stash_save(&stashid, repo, signature, NULL, GIT_STASH_DEFAULT), 116 | "Unable to save stash", NULL); 117 | check_lg2(git_commit_lookup(&stash, repo, &stashid), 118 | "Unable to lookup stash commit", NULL); 119 | 120 | printf("Saved working directory %s\n", git_commit_summary(stash)); 121 | 122 | git_signature_free(signature); 123 | git_commit_free(stash); 124 | 125 | return 0; 126 | } 127 | 128 | static int cmd_drop(git_repository* repo, struct opts* opts) 129 | { 130 | unsigned long index = strtoul(opts->argc ? opts->argv[2] : "0", NULL, 10); 131 | printf("Dropping index: %lu\n", index); 132 | check_lg2(git_stash_drop(repo, index), 133 | "Unable to drop stash", NULL); 134 | 135 | printf("Dropped refs/stash@{%lu}\n", index); 136 | 137 | return 0; 138 | } 139 | 140 | static int cmd_pop(git_repository *repo, struct opts *opts) 141 | { 142 | if (opts->argc) 143 | usage("pop does not accept any parameters"); 144 | 145 | check_lg2(git_stash_pop(repo, 0, NULL), 146 | "Unable to pop stash", NULL); 147 | 148 | printf("Dropped refs/stash@{0}\n"); 149 | 150 | return 0; 151 | } 152 | 153 | int lg2_stash(git_repository *repo, int argc, char *argv[]) 154 | { 155 | struct opts opts = { 0 }; 156 | 157 | parse_subcommand(&opts, argc, argv); 158 | 159 | switch (opts.cmd) { 160 | case SUBCMD_APPLY: 161 | return cmd_apply(repo, &opts); 162 | case SUBCMD_LIST: 163 | return cmd_list(repo, &opts); 164 | case SUBCMD_PUSH: 165 | return cmd_push(repo, &opts); 166 | case SUBCMD_POP: 167 | return cmd_pop(repo, &opts); 168 | case SUBCMD_DROP: 169 | return cmd_drop(repo, &opts); 170 | } 171 | 172 | return -1; 173 | } 174 | -------------------------------------------------------------------------------- /libgit2patchedfiles/examples/status.c: -------------------------------------------------------------------------------- 1 | /* 2 | * libgit2 "status" example - shows how to use the status APIs 3 | * 4 | * Written by the libgit2 contributors 5 | * 6 | * To the extent possible under law, the author(s) have dedicated all copyright 7 | * and related and neighboring rights to this software to the public domain 8 | * worldwide. This software is distributed without any warranty. 9 | * 10 | * You should have received a copy of the CC0 Public Domain Dedication along 11 | * with this software. If not, see 12 | * . 13 | */ 14 | 15 | #include "common.h" 16 | 17 | /** 18 | * This example demonstrates the use of the libgit2 status APIs, 19 | * particularly the `git_status_list` object, to roughly simulate the 20 | * output of running `git status`. It serves as a simple example of 21 | * using those APIs to get basic status information. 22 | * 23 | * This does not have: 24 | * 25 | * - Robust error handling 26 | * - Colorized or paginated output formatting 27 | * 28 | * This does have: 29 | * 30 | * - Examples of translating command line arguments to the status 31 | * options settings to mimic `git status` results. 32 | * - A sample status formatter that matches the default "long" format 33 | * from `git status` 34 | * - A sample status formatter that matches the "short" format 35 | * - Count of commits ahead/behind the remote upstream 36 | */ 37 | 38 | enum 39 | { 40 | FORMAT_DEFAULT = 0, 41 | FORMAT_LONG = 1, 42 | FORMAT_SHORT = 2, 43 | FORMAT_PORCELAIN = 3, 44 | }; 45 | 46 | #define MAX_PATHSPEC 8 47 | 48 | struct status_opts 49 | { 50 | git_status_options statusopt; 51 | char *repodir; 52 | char *pathspec[MAX_PATHSPEC]; 53 | int npaths; 54 | int format; 55 | int zterm; 56 | int showbranch; 57 | int showsubmod; 58 | int repeat; 59 | }; 60 | 61 | static void parse_opts(struct status_opts *o, int argc, char *argv[]); 62 | static void show_branch(git_repository *repo, int format); 63 | static void show_ahead_behind(git_repository *repo); 64 | static void print_conflicts(git_repository *repo); 65 | static void print_long(git_status_list *status); 66 | static void print_short(git_repository *repo, git_status_list *status); 67 | static int print_submod(git_submodule *sm, const char *name, void *payload); 68 | 69 | int lg2_status(git_repository *repo, int argc, char *argv[]) 70 | { 71 | git_status_list *status; 72 | struct status_opts o = {GIT_STATUS_OPTIONS_INIT, "."}; 73 | 74 | o.statusopt.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR; 75 | o.statusopt.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | 76 | GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX | 77 | GIT_STATUS_OPT_SORT_CASE_SENSITIVELY; 78 | 79 | parse_opts(&o, argc, argv); 80 | 81 | if (git_repository_is_bare(repo)) 82 | fatal("Cannot report status on bare repository", 83 | git_repository_path(repo)); 84 | 85 | show_status: 86 | if (o.repeat) 87 | printf("\033[H\033[2J"); 88 | 89 | /** 90 | * Run status on the repository 91 | * 92 | * We use `git_status_list_new()` to generate a list of status 93 | * information which lets us iterate over it at our 94 | * convenience and extract the data we want to show out of 95 | * each entry. 96 | * 97 | * You can use `git_status_foreach()` or 98 | * `git_status_foreach_ext()` if you'd prefer to execute a 99 | * callback for each entry. The latter gives you more control 100 | * about what results are presented. 101 | */ 102 | check_lg2(git_status_list_new(&status, repo, &o.statusopt), 103 | "Could not get status", NULL); 104 | 105 | if (o.showbranch) 106 | show_branch(repo, o.format); 107 | 108 | show_ahead_behind(repo); 109 | 110 | if (o.showsubmod) 111 | { 112 | int submod_count = 0; 113 | check_lg2(git_submodule_foreach(repo, print_submod, &submod_count), 114 | "Cannot iterate submodules", o.repodir); 115 | } 116 | 117 | if (o.format == FORMAT_LONG) 118 | print_long(status); 119 | else 120 | print_short(repo, status); 121 | 122 | print_conflicts(repo); 123 | 124 | git_status_list_free(status); 125 | 126 | if (o.repeat) 127 | { 128 | sleep(o.repeat); 129 | goto show_status; 130 | } 131 | 132 | return 0; 133 | } 134 | 135 | /** 136 | * If the user asked for the branch, let's show the short name of the 137 | * branch. 138 | */ 139 | static void show_branch(git_repository *repo, int format) 140 | { 141 | int error = 0; 142 | const char *branch = NULL; 143 | git_reference *head = NULL; 144 | 145 | error = git_repository_head(&head, repo); 146 | 147 | if (error == GIT_EUNBORNBRANCH || error == GIT_ENOTFOUND) 148 | branch = NULL; 149 | else if (!error) 150 | { 151 | branch = git_reference_shorthand(head); 152 | } 153 | else 154 | check_lg2(error, "failed to get current branch", NULL); 155 | 156 | if (format == FORMAT_LONG) 157 | printf("# On branch %s\n", 158 | branch ? branch : "Not currently on any branch."); 159 | else 160 | printf("## %s\n", branch ? branch : "HEAD (no branch)"); 161 | 162 | git_reference_free(head); 163 | } 164 | 165 | static void show_ahead_behind(git_repository *repo) 166 | { 167 | git_reference *upstream = NULL; 168 | git_reference *head_ref = NULL; 169 | size_t ahead; 170 | size_t behind; 171 | int err; 172 | 173 | err = git_repository_head(&head_ref, repo); 174 | if (err != 0) 175 | { 176 | fprintf(stderr, "error: %s\n", git_error_last()->message); 177 | goto cleanup; 178 | } 179 | 180 | err = git_branch_upstream(&upstream, head_ref); 181 | if (err != 0) 182 | { 183 | goto cleanup; 184 | } 185 | err = git_graph_ahead_behind(&ahead, &behind, repo, git_reference_target(head_ref), git_reference_target(upstream)); 186 | if (err != 0) 187 | { 188 | fprintf(stderr, "error: %s\n", git_error_last()->message); 189 | goto cleanup; 190 | } 191 | if (ahead > 0 || behind > 0) { 192 | printf("# Your branch is ahead by %d, behind by %d commits.\n", ahead, behind); 193 | } 194 | cleanup: 195 | git_reference_free(head_ref); 196 | git_reference_free(upstream); 197 | } 198 | 199 | /** 200 | * Simple printing of conflicts 201 | */ 202 | static void print_conflicts(git_repository *repo) { 203 | git_index *index = NULL; 204 | git_repository_index(&index, repo); 205 | 206 | if(git_index_has_conflicts(index)) { 207 | git_index_conflict_iterator *conflicts; 208 | const git_index_entry *ancestor = NULL; 209 | const git_index_entry *our = NULL; 210 | const git_index_entry *their = NULL; 211 | int err = 0; 212 | 213 | git_index_conflict_iterator_new(&conflicts, index); 214 | 215 | while ((err = git_index_conflict_next(&ancestor, &our, &their, conflicts)) == 0) { 216 | printf("conflict: a:%s o:%s t:%s\n", 217 | ancestor!=NULL ? ancestor->path : "NULL", 218 | our!=NULL ? our->path : "NULL", 219 | their!=NULL ? their->path : "NULL"); 220 | } 221 | 222 | if (err != GIT_ITEROVER) { 223 | fprintf(stderr, "error iterating conflicts\n"); 224 | } 225 | 226 | git_index_conflict_iterator_free(conflicts); 227 | } 228 | git_index_free(index); 229 | } 230 | 231 | /** 232 | * This function print out an output similar to git's status command 233 | * in long form, including the command-line hints. 234 | */ 235 | static void print_long(git_status_list *status) 236 | { 237 | size_t i, maxi = git_status_list_entrycount(status); 238 | const git_status_entry *s; 239 | int header = 0, changes_in_index = 0; 240 | int changed_in_workdir = 0, rm_in_workdir = 0; 241 | const char *old_path, *new_path; 242 | 243 | /** Print index changes. */ 244 | 245 | for (i = 0; i < maxi; ++i) 246 | { 247 | char *istatus = NULL; 248 | 249 | s = git_status_byindex(status, i); 250 | 251 | if (s->status == GIT_STATUS_CURRENT) 252 | continue; 253 | 254 | if (s->status & GIT_STATUS_WT_DELETED) 255 | rm_in_workdir = 1; 256 | 257 | if (s->status & GIT_STATUS_INDEX_NEW) 258 | istatus = "new file: "; 259 | if (s->status & GIT_STATUS_INDEX_MODIFIED) 260 | istatus = "modified: "; 261 | if (s->status & GIT_STATUS_INDEX_DELETED) 262 | istatus = "deleted: "; 263 | if (s->status & GIT_STATUS_INDEX_RENAMED) 264 | istatus = "renamed: "; 265 | if (s->status & GIT_STATUS_INDEX_TYPECHANGE) 266 | istatus = "typechange:"; 267 | 268 | if (istatus == NULL) 269 | continue; 270 | 271 | if (!header) 272 | { 273 | printf("# Changes to be committed:\n"); 274 | printf("# (use \"git reset HEAD ...\" to unstage)\n"); 275 | printf("#\n"); 276 | header = 1; 277 | } 278 | 279 | old_path = s->head_to_index->old_file.path; 280 | new_path = s->head_to_index->new_file.path; 281 | 282 | if (old_path && new_path && strcmp(old_path, new_path)) 283 | printf("#\t%s %s -> %s\n", istatus, old_path, new_path); 284 | else 285 | printf("#\t%s %s\n", istatus, old_path ? old_path : new_path); 286 | } 287 | 288 | if (header) 289 | { 290 | changes_in_index = 1; 291 | printf("#\n"); 292 | } 293 | header = 0; 294 | 295 | /** Print workdir changes to tracked files. */ 296 | 297 | for (i = 0; i < maxi; ++i) 298 | { 299 | char *wstatus = NULL; 300 | 301 | s = git_status_byindex(status, i); 302 | 303 | /** 304 | * With `GIT_STATUS_OPT_INCLUDE_UNMODIFIED` (not used in this example) 305 | * `index_to_workdir` may not be `NULL` even if there are 306 | * no differences, in which case it will be a `GIT_DELTA_UNMODIFIED`. 307 | */ 308 | if (s->status == GIT_STATUS_CURRENT || s->index_to_workdir == NULL) 309 | continue; 310 | 311 | /** Print out the output since we know the file has some changes */ 312 | if (s->status & GIT_STATUS_WT_MODIFIED) 313 | wstatus = "modified: "; 314 | if (s->status & GIT_STATUS_WT_DELETED) 315 | wstatus = "deleted: "; 316 | if (s->status & GIT_STATUS_WT_RENAMED) 317 | wstatus = "renamed: "; 318 | if (s->status & GIT_STATUS_WT_TYPECHANGE) 319 | wstatus = "typechange:"; 320 | 321 | if (wstatus == NULL) 322 | continue; 323 | 324 | if (!header) 325 | { 326 | printf("# Changes not staged for commit:\n"); 327 | printf("# (use \"git add%s ...\" to update what will be committed)\n", rm_in_workdir ? "/rm" : ""); 328 | printf("# (use \"git checkout -- ...\" to discard changes in working directory)\n"); 329 | printf("#\n"); 330 | header = 1; 331 | } 332 | 333 | old_path = s->index_to_workdir->old_file.path; 334 | new_path = s->index_to_workdir->new_file.path; 335 | 336 | if (old_path && new_path && strcmp(old_path, new_path)) 337 | printf("#\t%s %s -> %s\n", wstatus, old_path, new_path); 338 | else 339 | printf("#\t%s %s\n", wstatus, old_path ? old_path : new_path); 340 | } 341 | 342 | if (header) 343 | { 344 | changed_in_workdir = 1; 345 | printf("#\n"); 346 | } 347 | 348 | /** Print untracked files. */ 349 | 350 | header = 0; 351 | 352 | for (i = 0; i < maxi; ++i) 353 | { 354 | s = git_status_byindex(status, i); 355 | 356 | if (s->status == GIT_STATUS_WT_NEW) 357 | { 358 | 359 | if (!header) 360 | { 361 | printf("# Untracked files:\n"); 362 | printf("# (use \"git add ...\" to include in what will be committed)\n"); 363 | printf("#\n"); 364 | header = 1; 365 | } 366 | 367 | printf("#\t%s\n", s->index_to_workdir->old_file.path); 368 | } 369 | } 370 | 371 | header = 0; 372 | 373 | /** Print ignored files. */ 374 | 375 | for (i = 0; i < maxi; ++i) 376 | { 377 | s = git_status_byindex(status, i); 378 | 379 | if (s->status == GIT_STATUS_IGNORED) 380 | { 381 | 382 | if (!header) 383 | { 384 | printf("# Ignored files:\n"); 385 | printf("# (use \"git add -f ...\" to include in what will be committed)\n"); 386 | printf("#\n"); 387 | header = 1; 388 | } 389 | 390 | printf("#\t%s\n", s->index_to_workdir->old_file.path); 391 | } 392 | } 393 | 394 | if (!changes_in_index && changed_in_workdir) 395 | printf("no changes added to commit (use \"git add\" and/or \"git commit -a\")\n"); 396 | } 397 | 398 | /** 399 | * This version of the output prefixes each path with two status 400 | * columns and shows submodule status information. 401 | */ 402 | static void print_short(git_repository *repo, git_status_list *status) 403 | { 404 | size_t i, maxi = git_status_list_entrycount(status); 405 | const git_status_entry *s; 406 | char istatus, wstatus; 407 | const char *extra, *a, *b, *c; 408 | 409 | for (i = 0; i < maxi; ++i) 410 | { 411 | s = git_status_byindex(status, i); 412 | 413 | if (s->status == GIT_STATUS_CURRENT) 414 | continue; 415 | 416 | a = b = c = NULL; 417 | istatus = wstatus = ' '; 418 | extra = ""; 419 | 420 | if (s->status & GIT_STATUS_INDEX_NEW) 421 | istatus = 'A'; 422 | if (s->status & GIT_STATUS_INDEX_MODIFIED) 423 | istatus = 'M'; 424 | if (s->status & GIT_STATUS_INDEX_DELETED) 425 | istatus = 'D'; 426 | if (s->status & GIT_STATUS_INDEX_RENAMED) 427 | istatus = 'R'; 428 | if (s->status & GIT_STATUS_INDEX_TYPECHANGE) 429 | istatus = 'T'; 430 | 431 | if (s->status & GIT_STATUS_WT_NEW) 432 | { 433 | if (istatus == ' ') 434 | istatus = '?'; 435 | wstatus = '?'; 436 | } 437 | if (s->status & GIT_STATUS_WT_MODIFIED) 438 | wstatus = 'M'; 439 | if (s->status & GIT_STATUS_WT_DELETED) 440 | wstatus = 'D'; 441 | if (s->status & GIT_STATUS_WT_RENAMED) 442 | wstatus = 'R'; 443 | if (s->status & GIT_STATUS_WT_TYPECHANGE) 444 | wstatus = 'T'; 445 | 446 | if (s->status & GIT_STATUS_IGNORED) 447 | { 448 | istatus = '!'; 449 | wstatus = '!'; 450 | } 451 | 452 | if (istatus == '?' && wstatus == '?') 453 | continue; 454 | 455 | /** 456 | * A commit in a tree is how submodules are stored, so 457 | * let's go take a look at its status. 458 | */ 459 | if (s->index_to_workdir && 460 | s->index_to_workdir->new_file.mode == GIT_FILEMODE_COMMIT) 461 | { 462 | unsigned int smstatus = 0; 463 | 464 | if (!git_submodule_status(&smstatus, repo, s->index_to_workdir->new_file.path, 465 | GIT_SUBMODULE_IGNORE_UNSPECIFIED)) 466 | { 467 | if (smstatus & GIT_SUBMODULE_STATUS_WD_MODIFIED) 468 | extra = " (new commits)"; 469 | else if (smstatus & GIT_SUBMODULE_STATUS_WD_INDEX_MODIFIED) 470 | extra = " (modified content)"; 471 | else if (smstatus & GIT_SUBMODULE_STATUS_WD_WD_MODIFIED) 472 | extra = " (modified content)"; 473 | else if (smstatus & GIT_SUBMODULE_STATUS_WD_UNTRACKED) 474 | extra = " (untracked content)"; 475 | } 476 | } 477 | 478 | /** 479 | * Now that we have all the information, format the output. 480 | */ 481 | 482 | if (s->head_to_index) 483 | { 484 | a = s->head_to_index->old_file.path; 485 | b = s->head_to_index->new_file.path; 486 | } 487 | if (s->index_to_workdir) 488 | { 489 | if (!a) 490 | a = s->index_to_workdir->old_file.path; 491 | if (!b) 492 | b = s->index_to_workdir->old_file.path; 493 | c = s->index_to_workdir->new_file.path; 494 | } 495 | 496 | if (istatus == 'R') 497 | { 498 | if (wstatus == 'R') 499 | printf("%c%c %s %s %s%s\n", istatus, wstatus, a, b, c, extra); 500 | else 501 | printf("%c%c %s %s%s\n", istatus, wstatus, a, b, extra); 502 | } 503 | else 504 | { 505 | if (wstatus == 'R') 506 | printf("%c%c %s %s%s\n", istatus, wstatus, a, c, extra); 507 | else 508 | printf("%c%c %s%s\n", istatus, wstatus, a, extra); 509 | } 510 | } 511 | 512 | for (i = 0; i < maxi; ++i) 513 | { 514 | s = git_status_byindex(status, i); 515 | 516 | if (s->status == GIT_STATUS_WT_NEW) 517 | printf("?? %s\n", s->index_to_workdir->old_file.path); 518 | } 519 | } 520 | 521 | static int print_submod(git_submodule *sm, const char *name, void *payload) 522 | { 523 | int *count = payload; 524 | (void)name; 525 | 526 | if (*count == 0) 527 | printf("# Submodules\n"); 528 | (*count)++; 529 | 530 | printf("# - submodule '%s' at %s\n", 531 | git_submodule_name(sm), git_submodule_path(sm)); 532 | 533 | return 0; 534 | } 535 | 536 | /** 537 | * Parse options that git's status command supports. 538 | */ 539 | static void parse_opts(struct status_opts *o, int argc, char *argv[]) 540 | { 541 | struct args_info args = ARGS_INFO_INIT; 542 | 543 | for (args.pos = 1; args.pos < argc; ++args.pos) 544 | { 545 | char *a = argv[args.pos]; 546 | 547 | if (a[0] != '-') 548 | { 549 | if (o->npaths < MAX_PATHSPEC) 550 | o->pathspec[o->npaths++] = a; 551 | else 552 | fatal("Example only supports a limited pathspec", NULL); 553 | } 554 | else if (!strcmp(a, "-s") || !strcmp(a, "--short")) 555 | o->format = FORMAT_SHORT; 556 | else if (!strcmp(a, "--long")) 557 | o->format = FORMAT_LONG; 558 | else if (!strcmp(a, "--porcelain")) 559 | o->format = FORMAT_PORCELAIN; 560 | else if (!strcmp(a, "-b") || !strcmp(a, "--branch")) 561 | o->showbranch = 1; 562 | else if (!strcmp(a, "-z")) 563 | { 564 | o->zterm = 1; 565 | if (o->format == FORMAT_DEFAULT) 566 | o->format = FORMAT_PORCELAIN; 567 | } 568 | else if (!strcmp(a, "--ignored")) 569 | o->statusopt.flags |= GIT_STATUS_OPT_INCLUDE_IGNORED; 570 | else if (!strcmp(a, "-uno") || 571 | !strcmp(a, "--untracked-files=no")) 572 | o->statusopt.flags &= ~GIT_STATUS_OPT_INCLUDE_UNTRACKED; 573 | else if (!strcmp(a, "-unormal") || 574 | !strcmp(a, "--untracked-files=normal")) 575 | o->statusopt.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED; 576 | else if (!strcmp(a, "-uall") || 577 | !strcmp(a, "--untracked-files=all")) 578 | o->statusopt.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED | 579 | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS; 580 | else if (!strcmp(a, "--ignore-submodules=all")) 581 | o->statusopt.flags |= GIT_STATUS_OPT_EXCLUDE_SUBMODULES; 582 | else if (!strncmp(a, "--git-dir=", strlen("--git-dir="))) 583 | o->repodir = a + strlen("--git-dir="); 584 | else if (!strcmp(a, "--repeat")) 585 | o->repeat = 10; 586 | else if (match_int_arg(&o->repeat, &args, "--repeat", 0)) 587 | /* okay */; 588 | else if (!strcmp(a, "--list-submodules")) 589 | o->showsubmod = 1; 590 | else 591 | check_lg2(-1, "Unsupported option", a); 592 | } 593 | 594 | if (o->format == FORMAT_DEFAULT) 595 | o->format = FORMAT_LONG; 596 | if (o->format == FORMAT_LONG) 597 | o->showbranch = 1; 598 | if (o->npaths > 0) 599 | { 600 | o->statusopt.pathspec.strings = o->pathspec; 601 | o->statusopt.pathspec.count = o->npaths; 602 | } 603 | } 604 | -------------------------------------------------------------------------------- /libgit2patchedfiles/src/transports/emscriptenhttp-async.c: -------------------------------------------------------------------------------- 1 | #ifdef __EMSCRIPTEN__ 2 | 3 | #include "common.h" 4 | #include "emscripten.h" 5 | #include "git2/transport.h" 6 | #include "smart.h" 7 | 8 | #define DEFAULT_BUFSIZE 65536 9 | 10 | static const char *upload_pack_ls_service_url = "/info/refs?service=git-upload-pack"; 11 | static const char *upload_pack_service_url = "/git-upload-pack"; 12 | static const char *receive_pack_ls_service_url = "/info/refs?service=git-receive-pack"; 13 | static const char *receive_pack_service_url = "/git-receive-pack"; 14 | 15 | typedef struct { 16 | git_smart_subtransport_stream parent; 17 | const char *service_url; 18 | int connectionNo; 19 | } emscriptenhttp_stream; 20 | 21 | typedef struct { 22 | git_smart_subtransport parent; 23 | transport_smart *owner; 24 | 25 | } emscriptenhttp_subtransport; 26 | 27 | // Asyncified functions wrap async transports for browser when not using a webworker 28 | 29 | EM_JS(int, emscriptenhttp_do_get, (const char* url, size_t buf_size), { 30 | return Asyncify.handleAsync(async () => { 31 | const urlString = UTF8ToString(url); 32 | return await Module.emscriptenhttpconnect(urlString, buf_size); 33 | }); 34 | }); 35 | 36 | EM_JS(int, emscriptenhttp_do_post, (const char* url, size_t buf_size), { 37 | return Asyncify.handleAsync(async () => { 38 | const urlString = UTF8ToString(url); 39 | return await Module.emscriptenhttpconnect(urlString, buf_size, 'POST', { 40 | 'Content-Type': urlString.indexOf('git-upload-pack') > 0 ? 41 | 'application/x-git-upload-pack-request' : 42 | 'application/x-git-receive-pack-request' 43 | }); 44 | }); 45 | }); 46 | 47 | EM_JS(size_t, emscriptenhttp_do_read, (int connectionNo, char* buffer, size_t buf_size), { 48 | return Asyncify.handleAsync(async () => { 49 | return await Module.emscriptenhttpread(connectionNo, buffer, buf_size); 50 | }); 51 | }); 52 | 53 | static void emscriptenhttp_stream_free(git_smart_subtransport_stream *stream) 54 | { 55 | emscriptenhttp_stream *s = (emscriptenhttp_stream *)stream; 56 | 57 | git__free(s); 58 | } 59 | 60 | static int emscriptenhttp_stream_read( 61 | git_smart_subtransport_stream *stream, 62 | char *buffer, 63 | size_t buf_size, 64 | size_t *bytes_read) 65 | { 66 | emscriptenhttp_stream *s = (emscriptenhttp_stream *)stream; 67 | 68 | if(s->connectionNo == -1) { 69 | s->connectionNo = emscriptenhttp_do_get(s->service_url, DEFAULT_BUFSIZE); 70 | } 71 | 72 | *bytes_read = emscriptenhttp_do_read(s->connectionNo, buffer, buf_size); 73 | 74 | return 0; 75 | } 76 | 77 | static int emscriptenhttp_stream_write_single( 78 | git_smart_subtransport_stream *stream, 79 | const char *buffer, 80 | size_t len) 81 | { 82 | emscriptenhttp_stream *s = (emscriptenhttp_stream *)stream; 83 | 84 | if(s->connectionNo == -1) { 85 | s->connectionNo = emscriptenhttp_do_post(s->service_url, DEFAULT_BUFSIZE); 86 | } 87 | 88 | EM_ASM({ 89 | return Module.emscriptenhttpwrite($0, $1, $2); 90 | }, s->connectionNo, buffer, len); 91 | 92 | return 0; 93 | } 94 | 95 | static int emscriptenhttp_stream_alloc(emscriptenhttp_subtransport *t, emscriptenhttp_stream **stream) 96 | { 97 | emscriptenhttp_stream *s; 98 | 99 | if (!stream) 100 | return -1; 101 | 102 | s = git__calloc(1, sizeof(emscriptenhttp_stream)); 103 | GIT_ERROR_CHECK_ALLOC(s); 104 | 105 | s->parent.subtransport = &t->parent; 106 | s->parent.read = emscriptenhttp_stream_read; 107 | s->parent.write = emscriptenhttp_stream_write_single; 108 | s->parent.free = emscriptenhttp_stream_free; 109 | s->connectionNo = -1; 110 | 111 | *stream = s; 112 | 113 | return 0; 114 | } 115 | 116 | static int emscriptenhttp_action( 117 | git_smart_subtransport_stream **stream, 118 | git_smart_subtransport *subtransport, 119 | const char *url, 120 | git_smart_service_t action) 121 | { 122 | emscriptenhttp_subtransport *t = (emscriptenhttp_subtransport *)subtransport; 123 | emscriptenhttp_stream *s; 124 | 125 | if (emscriptenhttp_stream_alloc(t, &s) < 0) 126 | return -1; 127 | 128 | git_str buf = GIT_STR_INIT; 129 | 130 | switch(action) { 131 | case GIT_SERVICE_UPLOADPACK_LS: 132 | git_str_printf(&buf, "%s%s", url, upload_pack_ls_service_url); 133 | 134 | break; 135 | case GIT_SERVICE_UPLOADPACK: 136 | git_str_printf(&buf, "%s%s", url, upload_pack_service_url); 137 | break; 138 | case GIT_SERVICE_RECEIVEPACK_LS: 139 | git_str_printf(&buf, "%s%s", url, receive_pack_ls_service_url); 140 | break; 141 | case GIT_SERVICE_RECEIVEPACK: 142 | git_str_printf(&buf, "%s%s", url, receive_pack_service_url); 143 | break; 144 | } 145 | 146 | s->service_url = git_str_cstr(&buf); 147 | *stream = &s->parent; 148 | 149 | return 0; 150 | } 151 | 152 | static int emscriptenhttp_close(git_smart_subtransport *subtransport) 153 | { 154 | return 0; 155 | } 156 | 157 | static void emscriptenhttp_free(git_smart_subtransport *subtransport) 158 | { 159 | emscriptenhttp_subtransport *t = (emscriptenhttp_subtransport *)subtransport; 160 | 161 | emscriptenhttp_close(subtransport); 162 | 163 | git__free(t); 164 | } 165 | 166 | int git_smart_subtransport_http(git_smart_subtransport **out, git_transport *owner, void *param) { 167 | emscriptenhttp_subtransport *t; 168 | 169 | GIT_UNUSED(param); 170 | 171 | if (!out) 172 | return -1; 173 | 174 | t = git__calloc(1, sizeof(emscriptenhttp_subtransport)); 175 | GIT_ERROR_CHECK_ALLOC(t); 176 | 177 | t->owner = (transport_smart *)owner; 178 | t->parent.action = emscriptenhttp_action; 179 | t->parent.close = emscriptenhttp_close; 180 | t->parent.free = emscriptenhttp_free; 181 | 182 | *out = (git_smart_subtransport *) t; 183 | 184 | return 0; 185 | } 186 | 187 | #endif /* __EMSCRIPTEN__ */ -------------------------------------------------------------------------------- /libgit2patchedfiles/src/transports/emscriptenhttp.c: -------------------------------------------------------------------------------- 1 | #ifdef __EMSCRIPTEN__ 2 | 3 | #include "common.h" 4 | #include "emscripten.h" 5 | #include "git2/transport.h" 6 | #include "smart.h" 7 | 8 | #define DEFAULT_BUFSIZE 65536 9 | 10 | static const char *upload_pack_ls_service_url = "/info/refs?service=git-upload-pack"; 11 | static const char *upload_pack_service_url = "/git-upload-pack"; 12 | static const char *receive_pack_ls_service_url = "/info/refs?service=git-receive-pack"; 13 | static const char *receive_pack_service_url = "/git-receive-pack"; 14 | 15 | typedef struct { 16 | git_smart_subtransport_stream parent; 17 | const char *service_url; 18 | int connectionNo; 19 | } emscriptenhttp_stream; 20 | 21 | typedef struct { 22 | git_smart_subtransport parent; 23 | transport_smart *owner; 24 | 25 | } emscriptenhttp_subtransport; 26 | 27 | static int emscriptenhttp_stream_read( 28 | git_smart_subtransport_stream *stream, 29 | char *buffer, 30 | size_t buf_size, 31 | size_t *bytes_read) 32 | { 33 | emscriptenhttp_stream *s = (emscriptenhttp_stream *)stream; 34 | 35 | if(s->connectionNo == -1) { 36 | s->connectionNo = EM_ASM_INT({ 37 | const url = UTF8ToString($0); 38 | return Module.emscriptenhttpconnect(url, $1); 39 | }, s->service_url, DEFAULT_BUFSIZE); 40 | } 41 | 42 | *bytes_read = EM_ASM_INT({ 43 | return Module.emscriptenhttpread($0, $1, $2); 44 | }, s->connectionNo, buffer, buf_size); 45 | 46 | return 0; 47 | } 48 | 49 | static int emscriptenhttp_stream_write_single( 50 | git_smart_subtransport_stream *stream, 51 | const char *buffer, 52 | size_t len) 53 | { 54 | emscriptenhttp_stream *s = (emscriptenhttp_stream *)stream; 55 | 56 | if(s->connectionNo == -1) { 57 | s->connectionNo = EM_ASM_INT({ 58 | const url = UTF8ToString($0); 59 | return Module.emscriptenhttpconnect(url, $1, 'POST', { 60 | 'Content-Type': url.indexOf('git-upload-pack') > 0 ? 61 | 'application/x-git-upload-pack-request' : 62 | 'application/x-git-receive-pack-request' 63 | }); 64 | }, s->service_url, DEFAULT_BUFSIZE); 65 | } 66 | 67 | EM_ASM({ 68 | return Module.emscriptenhttpwrite($0, $1, $2); 69 | }, s->connectionNo, buffer, len); 70 | 71 | return 0; 72 | } 73 | 74 | static void emscriptenhttp_stream_free(git_smart_subtransport_stream *stream) 75 | { 76 | emscriptenhttp_stream *s = (emscriptenhttp_stream *)stream; 77 | 78 | git__free(s); 79 | } 80 | 81 | static int emscriptenhttp_stream_alloc(emscriptenhttp_subtransport *t, emscriptenhttp_stream **stream) 82 | { 83 | emscriptenhttp_stream *s; 84 | 85 | if (!stream) 86 | return -1; 87 | 88 | s = git__calloc(1, sizeof(emscriptenhttp_stream)); 89 | GIT_ERROR_CHECK_ALLOC(s); 90 | 91 | s->parent.subtransport = &t->parent; 92 | s->parent.read = emscriptenhttp_stream_read; 93 | s->parent.write = emscriptenhttp_stream_write_single; 94 | s->parent.free = emscriptenhttp_stream_free; 95 | s->connectionNo = -1; 96 | 97 | *stream = s; 98 | 99 | return 0; 100 | } 101 | 102 | static int emscriptenhttp_action( 103 | git_smart_subtransport_stream **stream, 104 | git_smart_subtransport *subtransport, 105 | const char *url, 106 | git_smart_service_t action) 107 | { 108 | emscriptenhttp_subtransport *t = (emscriptenhttp_subtransport *)subtransport; 109 | emscriptenhttp_stream *s; 110 | 111 | if (emscriptenhttp_stream_alloc(t, &s) < 0) 112 | return -1; 113 | 114 | git_str buf = GIT_STR_INIT; 115 | 116 | switch(action) { 117 | case GIT_SERVICE_UPLOADPACK_LS: 118 | git_str_printf(&buf, "%s%s", url, upload_pack_ls_service_url); 119 | 120 | break; 121 | case GIT_SERVICE_UPLOADPACK: 122 | git_str_printf(&buf, "%s%s", url, upload_pack_service_url); 123 | break; 124 | case GIT_SERVICE_RECEIVEPACK_LS: 125 | git_str_printf(&buf, "%s%s", url, receive_pack_ls_service_url); 126 | break; 127 | case GIT_SERVICE_RECEIVEPACK: 128 | git_str_printf(&buf, "%s%s", url, receive_pack_service_url); 129 | break; 130 | } 131 | 132 | s->service_url = git_str_cstr(&buf); 133 | *stream = &s->parent; 134 | 135 | return 0; 136 | } 137 | 138 | static int emscriptenhttp_close(git_smart_subtransport *subtransport) 139 | { 140 | return 0; 141 | } 142 | 143 | static void emscriptenhttp_free(git_smart_subtransport *subtransport) 144 | { 145 | emscriptenhttp_subtransport *t = (emscriptenhttp_subtransport *)subtransport; 146 | 147 | emscriptenhttp_close(subtransport); 148 | 149 | git__free(t); 150 | } 151 | 152 | int git_smart_subtransport_http(git_smart_subtransport **out, git_transport *owner, void *param) { 153 | emscriptenhttp_subtransport *t; 154 | 155 | GIT_UNUSED(param); 156 | 157 | if (!out) 158 | return -1; 159 | 160 | t = git__calloc(1, sizeof(emscriptenhttp_subtransport)); 161 | GIT_ERROR_CHECK_ALLOC(t); 162 | 163 | t->owner = (transport_smart *)owner; 164 | t->parent.action = emscriptenhttp_action; 165 | t->parent.close = emscriptenhttp_close; 166 | t->parent.free = emscriptenhttp_free; 167 | 168 | *out = (git_smart_subtransport *) t; 169 | 170 | return 0; 171 | } 172 | 173 | #endif /* __EMSCRIPTEN__ */ -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wasm-git", 3 | "version": "0.0.13", 4 | "type": "module", 5 | "author": { 6 | "name": "Peter Salomonsen", 7 | "url": "https://petersalomonsen.com" 8 | }, 9 | "repository": { 10 | "url": "https://github.com/petersalomonsen/wasm-git" 11 | }, 12 | "files": [ 13 | "lg2.js", 14 | "lg2.wasm", 15 | "lg2_async.js", 16 | "lg2_async.wasm", 17 | "README.md" 18 | ], 19 | "scripts": { 20 | "test": "mocha test/**/*.spec.js", 21 | "test-browser": "wtr test-browser/**/*.spec.js", 22 | "test-browser-watch": "wtr test-browser/**/*.spec.js --watch", 23 | "test-browser-async": "wtr test-browser-async/**/*.spec.js", 24 | "patch-version": "npm --no-git-tag-version version patch" 25 | }, 26 | "devDependencies": { 27 | "@web/test-runner": "^0.18.2", 28 | "@web/test-runner-playwright": "^0.11.0", 29 | "cgi": "^0.3.1", 30 | "chai": "^4.3.7", 31 | "mocha": "^10.2.0" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /preparepublishnpm.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | echo "copy lg2.wasm and lg2.js from build folder" 4 | cp emscriptenbuild/libgit2/examples/lg2.wasm . 5 | cp emscriptenbuild/libgit2/examples/lg2.js . 6 | cp emscriptenbuild/libgit2/examples/lg2_async.wasm . 7 | cp emscriptenbuild/libgit2/examples/lg2_async.js . 8 | echo "publish --dry-run (run npm publish to finalize)" 9 | npm publish --dry-run 10 | -------------------------------------------------------------------------------- /setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | curl -L https://github.com/libgit2/libgit2/archive/refs/tags/v1.7.1.tar.gz --output libgit2.tar.gz 4 | tar -xzf libgit2.tar.gz 5 | mv libgit2-1.7.1 libgit2 6 | rm libgit2.tar.gz 7 | rm libgit2/src/libgit2/transports/http.c 8 | cp -r libgit2patchedfiles/examples/* libgit2/examples/ 9 | cp -r libgit2patchedfiles/src/* libgit2/src/libgit2/ 10 | echo 'set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=gnu90")' >> libgit2/examples/CMakeLists.txt 11 | echo 'set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=gnu90")' >> libgit2/src/libgit2/CMakeLists.txt 12 | echo 'set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=gnu90")' >> libgit2/src/util/CMakeLists.txt 13 | sed -i 's/GIT_PACK_FILE_MODE 0444/GIT_PACK_FILE_MODE 0644/g' libgit2/src/libgit2/pack.h 14 | sed -i 's/GIT_OBJECT_FILE_MODE 0444/GIT_OBJECT_FILE_MODE 0644/g' libgit2/src/libgit2/odb.h 15 | -------------------------------------------------------------------------------- /test-browser-async/lg2_async.js: -------------------------------------------------------------------------------- 1 | ../emscriptenbuild/libgit2/examples/lg2_async.js -------------------------------------------------------------------------------- /test-browser-async/lg2_async.wasm: -------------------------------------------------------------------------------- 1 | ../emscriptenbuild/libgit2/examples/lg2_async.wasm -------------------------------------------------------------------------------- /test-browser-async/test.spec.js: -------------------------------------------------------------------------------- 1 | describe('wasm-git', function() { 2 | this.timeout(20000); 3 | 4 | it('should have window', () => { 5 | assert(window !== undefined); 6 | }); 7 | 8 | let lg, FS; 9 | before(async () => { 10 | const lgMod = await import(new URL('lg2_async.js', import.meta.url)); 11 | lg = await lgMod.default(); 12 | FS = lg.FS; 13 | }); 14 | 15 | let APPFS; 16 | it('should create an in memory filesystem, APPFS', () => { 17 | APPFS = FS.filesystems.MEMFS; 18 | assert(typeof(APPFS) === 'object' ); 19 | }); 20 | 21 | it('should make a working directory', () => { 22 | FS.mkdir(workingDir); 23 | }); 24 | 25 | it('should mount the filesystem on the working directory', () => { 26 | FS.mount(APPFS, { root: '.' }, workingDir); 27 | }); 28 | 29 | it('should make a directory and mount a memory filesystem on it', () => { 30 | FS.chdir(workingDir); 31 | }); 32 | 33 | it('should write a .gitconfig file', () => { 34 | FS.writeFile('/home/web_user/.gitconfig', '[user]\n' + 35 | 'name = Test User\n' + 36 | 'email = test@example.com'); 37 | }); 38 | 39 | it('should ping the gitserver', async () => { 40 | const result = await fetch('/testrepo.git/ping').then(res => res.text()); 41 | assert(result === 'pong'); 42 | }); 43 | 44 | let workingDir, url, currentRepoRootDir, testFile, testContents; 45 | beforeEach(() => { 46 | workingDir = "/working"; 47 | url = `${location.origin}/testrepo.git`; 48 | currentRepoRootDir = url.substring(url.lastIndexOf('/') + 1); 49 | testFile = "test.txt"; 50 | testContents = "hello-world!"; 51 | }); 52 | 53 | it('should clone a bare repository and push commits', async () => { 54 | console.log(`git clone ${url}`); 55 | await lg.callMain(['clone', url, currentRepoRootDir]); 56 | FS.chdir(currentRepoRootDir); 57 | 58 | let dircontents = FS.readdir('.'); 59 | console.log(dircontents); 60 | assert(dircontents.length > 2); 61 | assert(dircontents.find(entry => entry === '.git')); 62 | 63 | FS.writeFile(testFile, testContents); 64 | await lg.callMain(['add', '--verbose', testFile]); 65 | await lg.callMain(['commit','-m', `edited ${testFile}`]); 66 | await lg.callMain(['push']); 67 | 68 | dircontents = FS.readdir('.'); 69 | console.log(dircontents); 70 | assert(dircontents.length > 2); 71 | assert(dircontents.find(entry => entry === testFile)); 72 | }); 73 | 74 | it('rename the local clone of the repository', async () => { 75 | FS.chdir(workingDir); 76 | FS.rename(currentRepoRootDir, 'junk'); 77 | const dircontents = FS.readdir('.'); 78 | assert(dircontents.find(entry => entry !== currentRepoRootDir)); 79 | console.log(`renamed ${currentRepoRootDir}`); 80 | }); 81 | 82 | it('should clone the repository with contents', async () => { 83 | let dircontents = FS.readdir('.'); 84 | assert(dircontents.find(entry => entry !== testFile)); 85 | 86 | await lg.callMain(['clone', url, currentRepoRootDir]); 87 | dircontents = FS.readdir(currentRepoRootDir); 88 | assert(dircontents.length > 2); 89 | assert(dircontents.find(entry => entry === '.git')); 90 | assert(dircontents.find(entry => entry === testFile)); 91 | 92 | console.log(`${currentRepoRootDir}/${testFile}`) 93 | const filecontents = FS.readFile(`${currentRepoRootDir}/${testFile}`, {encoding: 'utf8'}); 94 | console.log('contents:', filecontents); 95 | assert(String(filecontents) === testContents); 96 | }); 97 | }); -------------------------------------------------------------------------------- /test-browser/githttpserver.js: -------------------------------------------------------------------------------- 1 | import http from 'http'; 2 | import fs from 'fs'; 3 | import cgi from 'cgi'; 4 | import { tmpdir } from 'os'; 5 | import { execSync } from 'child_process'; 6 | 7 | 8 | /** 9 | * This example will create a git http server to repositories on your local disk. 10 | * Set the GIT_PROJECT_ROOT environment variable to point to location of your git repositories. 11 | */ 12 | 13 | export function startServer() { 14 | const testrepodir = `${tmpdir()}/testrepo.git`; 15 | fs.rmSync(testrepodir, {recursive: true, force: true}); 16 | execSync(`git init --initial-branch=master --bare ${tmpdir()}/testrepo.git`); 17 | fs.rmSync(`${tmpdir()}/testremote.git`, {recursive: true, force: true}); 18 | execSync(`git init --initial-branch=master --bare ${tmpdir()}/testremote.git`); 19 | 20 | const script = 'git'; 21 | 22 | const gitcgi = cgi(script, {args: ['http-backend'], 23 | stderr: process.stderr, 24 | env: { 25 | 'GIT_PROJECT_ROOT': tmpdir(), 26 | 'GIT_HTTP_EXPORT_ALL': '1', 27 | 'REMOTE_USER': 'test@example.com' // Push requires authenticated users by default 28 | } 29 | }); 30 | 31 | return http.createServer( (request, response) => { 32 | let path = request.url.substring(1); 33 | 34 | console.log('git http server request', request.url); 35 | 36 | if (path.indexOf('ping') > -1) { 37 | response.statusCode = 200; 38 | response.end('pong'); 39 | } else if( path.indexOf('git-upload') > -1 || 40 | path.indexOf('git-receive') > -1) { 41 | gitcgi(request, response); 42 | } else { 43 | response.statusCode = 404; 44 | response.end('not found'); 45 | } 46 | }).listen(8080); 47 | } 48 | 49 | export default { 50 | startServer: startServer 51 | } -------------------------------------------------------------------------------- /test-browser/lg2.js: -------------------------------------------------------------------------------- 1 | ../emscriptenbuild/libgit2/examples/lg2.js -------------------------------------------------------------------------------- /test-browser/lg2.wasm: -------------------------------------------------------------------------------- 1 | ../emscriptenbuild/libgit2/examples/lg2.wasm -------------------------------------------------------------------------------- /test-browser/manycommits.spec.js: -------------------------------------------------------------------------------- 1 | describe('many commits and error creating signature', function () { 2 | it('should not get error creating signature on many repeated commits', async () => { 3 | const worker = new Worker(new URL('manycommits.worker.js', import.meta.url), {type: "module"}); 4 | const result = await new Promise(resolve => worker.onmessage = (msg) => resolve(msg.data)); 5 | expect(result).not.contain(`Error creating signature [-3] - config value 'user.name' was not found`); 6 | }); 7 | }); -------------------------------------------------------------------------------- /test-browser/manycommits.worker.js: -------------------------------------------------------------------------------- 1 | let stdout = []; 2 | let stderr = []; 3 | 4 | globalThis.wasmGitModuleOverrides = { 5 | 'print': (text) => { 6 | console.log(text); 7 | stdout.push(text) 8 | }, 9 | 'printErr': (text) => { 10 | console.error(text); 11 | stderr.push(text); 12 | } 13 | }; 14 | 15 | const lg2mod = await import(new URL('lg2.js', import.meta.url)); 16 | const lg2 = await lg2mod.default(); 17 | const FS = lg2.FS; 18 | const MEMFS = lg2.MEMFS; 19 | 20 | FS.mkdir('/working'); 21 | FS.mount(MEMFS, {}, '/working'); 22 | FS.chdir('/working'); 23 | 24 | FS.writeFile('/home/web_user/.gitconfig', '[user]\n' + 25 | 'name = Test User\n' + 26 | 'email = test@example.com'); 27 | 28 | FS.mkdir('/working/testrepo'); 29 | FS.chdir('/working/testrepo'); 30 | lg2.callMain(['init', '.']); 31 | lg2.callMain(['config', 'user.name', 'Test']); 32 | lg2.callMain(['config', 'user.email', 'test@example.com']); 33 | let text = ''; 34 | for (let i = 0; i < 10; i++) { 35 | console.log(i); 36 | text += 'x'; 37 | FS.writeFile('./test.txt', text); 38 | lg2.callMain(['add', '.']); 39 | lg2.callMain(['commit', '-m', 'commit ' + (i + 1)]); 40 | } 41 | postMessage(stderr); 42 | -------------------------------------------------------------------------------- /test-browser/remote.spec.js: -------------------------------------------------------------------------------- 1 | describe('remotes', function () { 2 | this.timeout(20000); 3 | 4 | let worker; 5 | 6 | const createWorker = async () => { 7 | worker = new Worker(new URL('worker.js', import.meta.url), {type: 'module'}); 8 | await new Promise(resolve => { 9 | worker.onmessage = msg => { 10 | if (msg.data.ready) { 11 | resolve(msg); 12 | } 13 | } 14 | }); 15 | } 16 | 17 | const callWorker = async (command, params) => { 18 | return await new Promise(resolve => { 19 | worker.onmessage = msg => resolve(msg.data); 20 | worker.postMessage(Object.assign({ 21 | command: command 22 | }, params)); 23 | }); 24 | }; 25 | const callWorkerWithArgs = async (command, ...args) => { 26 | return await new Promise(resolve => { 27 | worker.onmessage = msg => resolve(msg.data) 28 | worker.postMessage({ 29 | command: command, 30 | args: args 31 | }); 32 | }); 33 | }; 34 | 35 | this.beforeAll(async () => { 36 | await createWorker(); 37 | await callWorker('synclocal', {url: `${location.origin}/testremote.git`, newrepo: true }); 38 | }); 39 | 40 | this.afterAll(async () => { 41 | assert.equal((await callWorker('deletelocal')).deleted, 'testremote.git'); 42 | worker.terminate(); 43 | }); 44 | 45 | it('should be possible to create a new repo locally, set remotes and push', async () => { 46 | await callWorkerWithArgs('init', '.'); 47 | await callWorkerWithArgs('config', 'user.name', 'Test'); 48 | await callWorkerWithArgs('config', 'user.email', 'test@example.com'); 49 | 50 | await callWorker( 51 | 'writefile', { 52 | filename: 'test.txt', 53 | contents: 'blabla' 54 | }); 55 | await callWorkerWithArgs('add', 'test.txt'); 56 | await callWorkerWithArgs('commit', '-m', 'first commit'); 57 | await callWorker( 58 | 'writefile', { 59 | filename: 'test2.txt', 60 | contents: 'blabla' 61 | }); 62 | await callWorkerWithArgs('add', 'test2.txt'); 63 | await callWorkerWithArgs('commit', '-m', 'second commit'); 64 | assert.isTrue((await callWorker('push')).stderr.indexOf("remote 'origin' does not exist") > -1); 65 | await callWorkerWithArgs('remote', 'add', 'origin', `${location.origin}/testremote.git`); 66 | assert.equal((await callWorker('push')).stderr, ''); 67 | assert.equal((await callWorkerWithArgs('fetch', 'origin')).stderr, ''); 68 | }); 69 | }); -------------------------------------------------------------------------------- /test-browser/stashpop.spec.js: -------------------------------------------------------------------------------- 1 | /* 2 | Expected output with regular git (the difference is in the last status): 3 | 4 | peter@MacBook-Air wgtest % echo "hei" > test.txt 5 | peter@MacBook-Air wgtest % git add test.txt 6 | peter@MacBook-Air wgtest % git commit -m "hei" 7 | [master (root-commit) 6059cdd] hei 8 | 1 file changed, 1 insertion(+) 9 | create mode 100644 test.txt 10 | peter@MacBook-Air wgtest % git checkout -b testbranch 11 | Switched to a new branch 'testbranch' 12 | peter@MacBook-Air wgtest % echo "hei" > test2.txt 13 | peter@MacBook-Air wgtest % git add test2.txt 14 | peter@MacBook-Air wgtest % git commit -m "heia" 15 | [testbranch 4892397] heia 16 | 1 file changed, 1 insertion(+) 17 | create mode 100644 test2.txt 18 | peter@MacBook-Air wgtest % echo "hei2" > test2.txt 19 | peter@MacBook-Air wgtest % git checkout master 20 | error: Your local changes to the following files would be overwritten by checkout: 21 | test2.txt 22 | Please commit your changes or stash them before you switch branches. 23 | Aborting 24 | peter@MacBook-Air wgtest % git stash 25 | Saved working directory and index state WIP on testbranch: 4892397 heia 26 | peter@MacBook-Air wgtest % git checkout master 27 | Switched to branch 'master' 28 | peter@MacBook-Air wgtest % git stash pop 29 | CONFLICT (modify/delete): test2.txt deleted in Updated upstream and modified in Stashed changes. Version Stashed changes of test2.txt left in tree. 30 | The stash entry is kept in case you need it again. 31 | peter@MacBook-Air wgtest % git status --short 32 | DU test2.txt 33 | peter@MacBook-Air wgtest % git status 34 | On branch master 35 | Unmerged paths: 36 | (use "git restore --staged ..." to unstage) 37 | (use "git add/rm ..." as appropriate to mark resolution) 38 | deleted by us: test2.txt 39 | 40 | no changes added to commit (use "git add" and/or "git commit -a") 41 | peter@MacBook-Air wgtest % git status --short 42 | DU test2.txt 43 | 44 | */ 45 | 46 | describe('wasm-git-stash-pop', function () { 47 | this.timeout(20000); 48 | 49 | let worker; 50 | 51 | const createWorker = async () => { 52 | worker = new Worker(new URL('worker.js', import.meta.url), {type: 'module'}); 53 | await new Promise(resolve => { 54 | worker.onmessage = msg => { 55 | if (msg.data.ready) { 56 | resolve(msg); 57 | } 58 | } 59 | }); 60 | } 61 | 62 | const callWorker = async (command, params) => { 63 | return await new Promise(resolve => { 64 | worker.onmessage = msg => resolve(msg.data); 65 | worker.postMessage(Object.assign({ 66 | command: command 67 | }, params)); 68 | }); 69 | }; 70 | const callWorkerWithArgs = async (command, ...args) => { 71 | return await new Promise(resolve => { 72 | worker.onmessage = msg => resolve(msg.data) 73 | worker.postMessage({ 74 | command: command, 75 | args: args 76 | }); 77 | }); 78 | }; 79 | 80 | this.beforeAll(async () => { 81 | await createWorker(); 82 | await callWorker('synclocal', {url: `${location.origin}/teststash.git`, newrepo: true }); 83 | }); 84 | 85 | this.afterAll(async () => { 86 | assert.equal((await callWorker('deletelocal')).deleted, 'teststash.git'); 87 | worker.terminate(); 88 | }); 89 | 90 | it('should create repo pop and stash, and show conflict', async () => { 91 | await callWorkerWithArgs('init', '.'); 92 | await callWorker( 93 | 'writefile', { 94 | filename: 'test.txt', 95 | contents: 'blabla' 96 | }); 97 | await callWorkerWithArgs('add', 'test.txt'); 98 | await callWorkerWithArgs('commit', '-m', 'first commit'); 99 | await callWorkerWithArgs('checkout', '-b', 'testbranch'); 100 | await callWorker( 101 | 'writefile', { 102 | filename: 'test2.txt', 103 | contents: 'blabla' 104 | }); 105 | await callWorkerWithArgs('add', 'test2.txt'); 106 | await callWorkerWithArgs('commit', '-m', 'second commit'); 107 | await callWorker( 108 | 'writefile', { 109 | filename: 'test2.txt', 110 | contents: 'blabla2' 111 | }); 112 | assert.isTrue((await callWorkerWithArgs('checkout', 'master')).stderr.indexOf('1 conflict prevents checkout')>-1); 113 | await callWorkerWithArgs('stash'); 114 | assert.equal((await callWorkerWithArgs('checkout', 'master')).stderr,''); 115 | assert.equal((await callWorker('dir')).dircontents.findIndex(f => f==='test2.txt'), -1); 116 | await callWorkerWithArgs('stash', 'pop'); 117 | assert.isTrue((await callWorker('dir')).dircontents.findIndex(f => f==='test2.txt')>-1); 118 | // This part is different in libgit2 status from cmd line git 119 | // assert.equal((await callWorker('status')).stdout, 'DU test2.txt'); 120 | console.log((await callWorker('status')).stdout); 121 | assert.isTrue((await callWorker('status')).stdout.indexOf('conflict: a:test2.txt o:NULL t:test2.txt') >0 ); 122 | }); 123 | }); -------------------------------------------------------------------------------- /test-browser/test.spec.js: -------------------------------------------------------------------------------- 1 | describe('wasm-git', function () { 2 | this.timeout(20000); 3 | 4 | let worker; 5 | 6 | const createWorker = async () => { 7 | worker = new Worker(new URL('worker.js', import.meta.url), {type: 'module'}); 8 | await new Promise(resolve => { 9 | worker.onmessage = msg => { 10 | if (msg.data.ready) { 11 | resolve(msg); 12 | } 13 | } 14 | }); 15 | } 16 | 17 | const callWorker = async (command, params) => { 18 | return await new Promise(resolve => { 19 | worker.onmessage = msg => resolve(msg.data); 20 | worker.postMessage(Object.assign({ 21 | command: command 22 | }, params)); 23 | }); 24 | }; 25 | const callWorkerWithArgs = async (command, ...args) => { 26 | return await new Promise(resolve => { 27 | worker.onmessage = msg => resolve(msg.data) 28 | worker.postMessage({ 29 | command: command, 30 | args: args 31 | }); 32 | }); 33 | }; 34 | 35 | this.afterAll(async () => { 36 | assert.equal((await callWorker('deletelocal')).deleted, 'testrepo.git'); 37 | worker.terminate(); 38 | }); 39 | 40 | it('should get ready message from web worker', async () => { 41 | await createWorker(); 42 | }); 43 | 44 | it('should ping the gitserver', async () => { 45 | const result = await fetch('/testrepo.git/ping').then(res => res.text()); 46 | assert.equal(result, 'pong'); 47 | }); 48 | 49 | it('should sync local idbfs and find no repository', async () => { 50 | worker.postMessage({ command: 'synclocal', url: `${location.origin}/testrepo.git` }); 51 | let result = await new Promise(resolve => 52 | worker.onmessage = msg => { 53 | if (msg.data.notfound) { 54 | resolve(msg); 55 | } else { 56 | console.log(msg.data); 57 | } 58 | } 59 | ); 60 | assert(result.data.notfound); 61 | }); 62 | 63 | it('should clone a bare repository and push commits', async () => { 64 | worker.postMessage({ command: 'clone', url: `${location.origin}/testrepo.git` }); 65 | let result = await new Promise(resolve => 66 | worker.onmessage = msg => { 67 | if (msg.data.dircontents) { 68 | resolve(msg); 69 | } else { 70 | console.log(msg.data); 71 | } 72 | } 73 | ); 74 | assert(result.data.dircontents.length > 2); 75 | assert(result.data.dircontents.find(entry => entry === '.git')); 76 | 77 | worker.postMessage({ 78 | command: 'writecommitandpush', 79 | filename: 'test.txt', 80 | contents: 'hello world!' 81 | }); 82 | result = await new Promise(resolve => 83 | worker.onmessage = msg => { 84 | if (msg.data.dircontents) { 85 | resolve(msg); 86 | } else { 87 | console.log(msg.data); 88 | } 89 | } 90 | ); 91 | assert(result.data.dircontents.find(entry => entry === 'test.txt')); 92 | console.log(`1 second pause to make sure we don't get another log entry in the same second`); 93 | await new Promise(r => setTimeout(r, 1000)); 94 | }); 95 | 96 | it('remove the local clone of the repository', async () => { 97 | assert.equal((await callWorker('deletelocal')).deleted, 'testrepo.git'); 98 | worker.terminate(); 99 | }); 100 | it('should clone the repository with contents', async () => { 101 | await createWorker(); 102 | assert.isTrue((await callWorker('synclocal', {url: `${location.origin}/testrepo.git` })).notfound); 103 | 104 | let result = await callWorker('readfile', { filename: 'test.txt' }); 105 | assert.exists(result.stderr); 106 | 107 | worker.postMessage({ command: 'clone', url: `${location.origin}/testrepo.git` }); 108 | result = await new Promise(resolve => 109 | worker.onmessage = msg => { 110 | if (msg.data.dircontents) { 111 | resolve(msg); 112 | } else { 113 | console.log(msg.data); 114 | } 115 | } 116 | ); 117 | assert(result.data.dircontents.length > 2); 118 | assert(result.data.dircontents.find(entry => entry === '.git')); 119 | assert(result.data.dircontents.find(entry => entry === 'test.txt')); 120 | 121 | worker.postMessage({ command: 'readfile', filename: 'test.txt' }); 122 | result = await new Promise(resolve => 123 | worker.onmessage = msg => { 124 | if (msg.data.filecontents) { 125 | resolve(msg); 126 | } else { 127 | console.log(msg.data); 128 | } 129 | } 130 | ); 131 | assert.equal(result.data.filecontents, 'hello world!'); 132 | }); 133 | it('should create new branch', async () => { 134 | await callWorkerWithArgs('checkout', 'testbranch'); 135 | assert.equal((await callWorker('status')).stdout.split('\n')[0], '# On branch master'); 136 | await callWorkerWithArgs('checkout', '-b', 'testbranch'); 137 | assert.equal((await callWorker('status')).stdout.split('\n')[0], '# On branch testbranch'); 138 | }); 139 | it('should reset to HEAD~1', async () => { 140 | await callWorker( 141 | 'writecommitandpush', { 142 | filename: 'test2.txt', 143 | contents: 'hello world2!' 144 | }); 145 | const commitLogBeforeReset = (await callWorker('log')).stdout.split('\n').filter(l => l.indexOf('commit ')===0); 146 | await callWorkerWithArgs('reset', 'HEAD~1'); 147 | const commitLogAfterReset = (await callWorker('log')).stdout.split('\n').filter(l => l.indexOf('commit ')===0); 148 | assert.equal(commitLogAfterReset[0],commitLogBeforeReset[1]); 149 | assert.isTrue((await callWorker('dir')).dircontents.indexOf('test2.txt')>-1); 150 | }); 151 | it('should show 1 ahead', async() => { 152 | await callWorkerWithArgs('checkout', 'master'); 153 | await callWorkerWithArgs('status'); 154 | await callWorkerWithArgs('add', 'test2.txt'); 155 | await callWorkerWithArgs('commit', '-m', 'add test2'); 156 | const aheadbehind = (await callWorkerWithArgs('status')).stdout.split('\n')[1]; 157 | assert.equal('# Your branch is ahead by 1, behind by 0 commits.',aheadbehind); 158 | }); 159 | it('should find the new branch after cloning', async() => { 160 | assert.equal((await callWorker('deletelocal')).deleted, 'testrepo.git'); 161 | worker.terminate(); 162 | await createWorker(); 163 | assert.isTrue((await callWorker('synclocal', {url: `${location.origin}/testrepo.git` })).notfound); 164 | await callWorker('clone', {url: `${location.origin}/testrepo.git` }); 165 | await callWorkerWithArgs('checkout', 'testbranch'); 166 | assert.equal((await callWorker('status')).stdout.split('\n')[0], '# On branch testbranch'); 167 | }); 168 | it('the new branch should have been set up with remote tracking', async() => { 169 | let config = (await callWorker('readfile', { filename: '.git/config' })).filecontents; 170 | assert.isTrue(config.indexOf(`[branch "testbranch"]`) > -1) 171 | }); 172 | it('should reset hard to HEAD~1', async () => { 173 | const commitLogBeforeCommit = (await callWorker('log')).stdout.split('\n').filter(l => l.indexOf('commit ')===0); 174 | console.log('before commit', commitLogBeforeCommit[0], commitLogBeforeCommit[1], commitLogBeforeCommit[2]); 175 | let result = await callWorker( 176 | 'writecommitandpush', { 177 | filename: 'testResetHard.txt', 178 | contents: 'hello world! reset hard' 179 | }); 180 | assert.isTrue(result.dircontents.indexOf('testResetHard.txt')>0); 181 | const commitLogBeforeReset = (await callWorker('log')).stdout.split('\n').filter(l => l.indexOf('commit ')===0); 182 | console.log('before reset', commitLogBeforeReset[0], commitLogBeforeReset[1], commitLogBeforeReset[2]); 183 | result = await callWorkerWithArgs('reset', '--hard', 'HEAD~1'); 184 | console.log('stderr after reset',result.stderr); 185 | const commitLogAfterReset = (await callWorker('log')).stdout.split('\n').filter(l => l.indexOf('commit ')===0); 186 | console.log('after reset', commitLogAfterReset[0], commitLogAfterReset[1]); 187 | assert.equal(commitLogAfterReset[0],commitLogBeforeReset[1]); 188 | assert.equal((await callWorker('dir')).dircontents.indexOf('testResetHard.txt'),-1); 189 | }); 190 | it('should show 1 behind after previous hard reset', async() => { 191 | const aheadbehind = (await callWorkerWithArgs('status')).stdout.split('\n')[1]; 192 | assert.equal(aheadbehind, '# Your branch is ahead by 0, behind by 1 commits.'); 193 | }); 194 | it('should be able to create a new branch on a new repo that is not cloned', async() => { 195 | assert.equal((await callWorker('deletelocal')).deleted, 'testrepo.git'); 196 | worker.terminate(); 197 | await createWorker(); 198 | assert.isTrue((await callWorker('synclocal', {url: `${location.origin}/testrepo.git`, newrepo: true })).empty); 199 | 200 | await callWorkerWithArgs('init', '.'); 201 | await callWorker( 202 | 'writefile', { 203 | filename: 'test44.txt', 204 | contents: 'hello world5!' 205 | }); 206 | await callWorkerWithArgs('add', 'test44.txt'); 207 | await callWorkerWithArgs('commit', '-m', 'another test commit'); 208 | assert.equal((await callWorkerWithArgs('checkout', '-b', 'testbranch')).stderr, ''); 209 | assert.equal((await callWorker('status')).stdout.split('\n')[0], '# On branch testbranch'); 210 | }); 211 | it('should be able to apply and drop specific stash index', async() => { 212 | assert.equal((await callWorker('deletelocal')).deleted, 'testrepo.git'); 213 | worker.terminate(); 214 | await createWorker(); 215 | assert.isTrue((await callWorker('synclocal', {url: `${location.origin}/testrepo.git`, newrepo: true })).empty); 216 | 217 | await callWorkerWithArgs('init', '.'); 218 | await callWorker( 219 | 'writefile', { 220 | filename: 'test.txt', 221 | contents: 'hello world' 222 | }); 223 | await callWorkerWithArgs('add', 'test.txt'); 224 | await callWorkerWithArgs('commit', '-m', 'initial commit'); 225 | 226 | await callWorker( 227 | 'writefile', { 228 | filename: 'test2.txt', 229 | contents: 'test2' 230 | }); 231 | await callWorkerWithArgs('add', 'test2.txt'); 232 | assert.isTrue((await callWorker('dir')).dircontents.includes('test2.txt')); 233 | await callWorker('stash'); 234 | assert.isFalse((await callWorker('dir')).dircontents.includes('test2.txt')); 235 | 236 | await callWorker( 237 | 'writefile', { 238 | filename: 'test3.txt', 239 | contents: 'test3' 240 | }); 241 | await callWorkerWithArgs('add', 'test3.txt'); 242 | 243 | assert.isTrue((await callWorker('dir')).dircontents.includes('test3.txt')); 244 | await callWorker('stash'); 245 | assert.isFalse((await callWorker('dir')).dircontents.includes('test3.txt')); 246 | assert.isTrue((await callWorkerWithArgs('stash', 'list')).stdout.split('\n').length === 2); 247 | 248 | await callWorkerWithArgs('stash', 'apply', '1'); 249 | await callWorkerWithArgs('stash', 'drop', '1'); 250 | 251 | assert.isTrue((await callWorker('dir')).dircontents.includes('test2.txt')); 252 | assert.isFalse((await callWorker('dir')).dircontents.includes('test3.txt')); 253 | 254 | const stashListOutput = (await callWorkerWithArgs('stash', 'list')).stdout; 255 | assert.isTrue(stashListOutput.split('\n').length === 1); 256 | assert.isTrue(stashListOutput.startsWith('stash@{0}:')); 257 | }); 258 | }); 259 | -------------------------------------------------------------------------------- /test-browser/worker.js: -------------------------------------------------------------------------------- 1 | let stdout = []; 2 | let stderr = []; 3 | 4 | globalThis.wasmGitModuleOverrides = { 5 | 'print': (text) => { 6 | console.log(text); 7 | stdout.push(text) 8 | }, 9 | 'printErr': (text) => { 10 | console.error(text); 11 | stderr.push(text); 12 | } 13 | }; 14 | 15 | const lg2mod = await import(new URL('lg2.js', import.meta.url)); 16 | const lg = await lg2mod.default(); 17 | 18 | const FS = lg.FS; 19 | const IDBFS = lg.IDBFS; 20 | 21 | const username = 'Test User'; 22 | const useremail = 'test@example.com'; 23 | 24 | FS.writeFile('/home/web_user/.gitconfig', 25 | `[user] 26 | name = ${username} 27 | email = ${useremail}`); 28 | 29 | let currentRepoRootDir; 30 | 31 | onmessage = (msg) => { 32 | stderr = []; 33 | stdout = []; 34 | if (msg.data.command === 'writecommitandpush') { 35 | FS.writeFile(msg.data.filename, msg.data.contents); 36 | lg.callMain(['add', '--verbose', msg.data.filename]); 37 | lg.callMain(['commit', '-m', `edited ${msg.data.filename}`]); 38 | lg.callMain(['log']); 39 | FS.syncfs(false, () => { 40 | console.log(currentRepoRootDir, 'stored to indexeddb'); 41 | lg.callMain(['push']); 42 | postMessage({ dircontents: FS.readdir('.') }); 43 | }); 44 | } else if (msg.data.command === 'writefile') { 45 | FS.writeFile(msg.data.filename, msg.data.contents); 46 | FS.syncfs(false, () => { 47 | console.log(currentRepoRootDir, 'stored to indexeddb'); 48 | postMessage({ dircontents: FS.readdir('.') }); 49 | }); 50 | } else if (msg.data.command === 'synclocal') { 51 | currentRepoRootDir = msg.data.url.substring(msg.data.url.lastIndexOf('/') + 1); 52 | console.log('synclocal', currentRepoRootDir); 53 | 54 | FS.mkdir(`/${currentRepoRootDir}`); 55 | FS.mount(IDBFS, {}, `/${currentRepoRootDir}`); 56 | 57 | FS.syncfs(true, () => { 58 | if (FS.readdir(`/${currentRepoRootDir}`).find(file => file === '.git')) { 59 | FS.chdir(`/${currentRepoRootDir}`); 60 | postMessage({ dircontents: FS.readdir('.') }); 61 | console.log(currentRepoRootDir, 'restored from indexeddb'); 62 | } else if (msg.data.newrepo) { 63 | FS.chdir(`/${currentRepoRootDir}`); 64 | postMessage({ empty: true }); 65 | } else { 66 | FS.chdir('/'); 67 | postMessage({ notfound: true }); 68 | } 69 | }); 70 | } else if (msg.data.command === 'deletelocal') { 71 | FS.unmount(`/${currentRepoRootDir}`); 72 | self.indexedDB.deleteDatabase('/' + currentRepoRootDir); 73 | postMessage({ deleted: currentRepoRootDir }); 74 | } else if (msg.data.command === 'dir') { 75 | postMessage({ dircontents: FS.readdir('.') }); 76 | } else if (msg.data.command === 'clone') { 77 | currentRepoRootDir = msg.data.url.substring(msg.data.url.lastIndexOf('/') + 1); 78 | 79 | lg.callMain(['clone', msg.data.url, currentRepoRootDir]); 80 | FS.chdir(currentRepoRootDir); 81 | 82 | FS.syncfs(false, () => { 83 | console.log(currentRepoRootDir, 'stored to indexeddb'); 84 | postMessage({ dircontents: FS.readdir('.') }); 85 | }); 86 | } else if (msg.data.command === 'pull') { 87 | lg.callMain(['fetch', 'origin']); 88 | lg.callMain(['merge', 'origin/master']); 89 | FS.syncfs(false, () => { 90 | console.log(currentRepoRootDir, 'stored to indexeddb'); 91 | }); 92 | } else if (msg.data.command === 'readfile') { 93 | try { 94 | postMessage({ 95 | filename: msg.data.filename, 96 | filecontents: FS.readFile(msg.data.filename, { encoding: 'utf8' }) 97 | }); 98 | } catch (e) { 99 | postMessage({ 'stderr': JSON.stringify(e) }); 100 | } 101 | } else { 102 | const args = msg.data.args || []; 103 | lg.callMain([msg.data.command, ...args]); 104 | postMessage({ stdout: stdout.join('\n'), stderr: stderr.join('\n'), }); 105 | } 106 | 107 | }; 108 | 109 | postMessage({ 'ready': true }); 110 | -------------------------------------------------------------------------------- /test/.gitignore: -------------------------------------------------------------------------------- 1 | nodefsclonetest -------------------------------------------------------------------------------- /test/checkout.spec.js: -------------------------------------------------------------------------------- 1 | import { lgPromise } from './common.js'; 2 | import assert from 'assert'; 3 | 4 | describe('git checkout', () => { 5 | beforeEach(async () => { 6 | const lg = await lgPromise; 7 | const FS = lg.FS; 8 | console.log('cwd', FS.cwd()); 9 | }); 10 | it('should discard changes to a path', async () => { 11 | const lg = await lgPromise; 12 | const FS = lg.FS; 13 | FS.writeFile('/home/web_user/.gitconfig', '[user]\n' + 14 | 'name = Test User\n' + 15 | 'email = test@example.com'); 16 | 17 | FS.mkdir('test'); 18 | FS.chdir('test'); 19 | lg.callMain(['init', '.']); 20 | 21 | FS.writeFile('test.txt', 'abcdef'); 22 | lg.callMain(['add', 'test.txt']); 23 | lg.callMain(['commit', '-m', 'test commit']); 24 | assert.equal(FS.readFile('test.txt', {encoding: 'utf8'}), 'abcdef'); 25 | FS.writeFile('test.txt', 'abcdefg'); 26 | lg.callMain(['checkout', '--', 'test.txt']); 27 | lg.callMain(['status']); 28 | assert.equal(FS.readFile('test.txt', {encoding: 'utf8'}), 'abcdef', 29 | 'expecting file content to be reverted'); 30 | }); 31 | it('should show error message if no path arguments are given', async () => { 32 | const lg = await lgPromise; 33 | const FS = lg.FS; 34 | 35 | FS.writeFile('/home/web_user/.gitconfig', '[user]\n' + 36 | 'name = Test User\n' + 37 | 'email = test@example.com'); 38 | 39 | FS.mkdir('test99'); 40 | FS.chdir('test99'); 41 | lg.callMain(['init', '.']); 42 | 43 | FS.writeFile('test.txt', 'abcdef'); 44 | lg.callMain(['add', 'test.txt']); 45 | 46 | lg.callMain(['commit', '-m', 'test commit']); 47 | assert.equal(FS.readFile('test.txt', {encoding: 'utf8'}), 'abcdef'); 48 | 49 | FS.writeFile('test.txt', 'abcdefg'); 50 | 51 | let errormessage; 52 | try { 53 | lg.callWithOutput(['checkout', '--']); 54 | } catch (err) { 55 | errormessage = err; 56 | } 57 | assert.equal(errormessage, '1: error: no paths specified'); 58 | }); 59 | }); 60 | -------------------------------------------------------------------------------- /test/common.js: -------------------------------------------------------------------------------- 1 | export const lgPromise = await import('./lg2.js').then(r => r.default()); 2 | -------------------------------------------------------------------------------- /test/conflict.spec.js: -------------------------------------------------------------------------------- 1 | import { lgPromise } from './common.js'; 2 | import assert from 'assert'; 3 | 4 | describe('conflicts', function() { 5 | beforeEach(async () => { 6 | console.log('cwd', (await lgPromise).FS.cwd()); 7 | }); 8 | it('should create 1 bare and 2 clones and create/resolve conflicts', async () => { 9 | const lg = await lgPromise; 10 | const FS = lg.FS; 11 | 12 | FS.mkdir('bareconflicts'); 13 | FS.chdir('bareconflicts'); 14 | lg.callMain(['init', '--bare', '.']); 15 | 16 | lg.callMain(['config', 'user.name', 'The Tester']); 17 | lg.callMain(['config', 'user.email', 'test@testing.com']); 18 | 19 | FS.chdir('..'); 20 | lg.callMain(['clone', 'bareconflicts', 'testconflicts1']); 21 | 22 | FS.chdir('testconflicts1'); 23 | 24 | lg.callMain(['config', 'user.name', 'The Tester']); 25 | lg.callMain(['config', 'user.email', 'test@testing.com']); 26 | 27 | FS.writeFile('test.txt', 'abcdef'); 28 | lg.callMain(['add', 'test.txt']); 29 | lg.callMain(['commit', '-m', 'test commit 1']); 30 | lg.callMain(['push']); 31 | FS.chdir('..'); 32 | 33 | lg.callMain(['clone', 'bareconflicts', 'testconflicts2']); 34 | 35 | FS.chdir('testconflicts1'); 36 | FS.writeFile('test.txt', 'abc'); 37 | lg.callMain(['add', 'test.txt']); 38 | lg.callMain(['commit', '-m', 'test commit 2']); 39 | lg.callMain(['push']); 40 | FS.chdir('..'); 41 | 42 | FS.chdir('testconflicts2'); 43 | 44 | lg.callMain(['config', 'user.name', 'The Tester']); 45 | lg.callMain(['config', 'user.email', 'test@testing.com']); 46 | 47 | FS.writeFile('test.txt', 'hijklmn'); 48 | lg.callMain(['add', 'test.txt']); 49 | lg.callMain(['commit', '-m', 'test commit 3']); 50 | 51 | try { 52 | lg.callWithOutput(['push']); 53 | assert.fail('should reject pushing'); 54 | } catch(e) { 55 | assert.match(e, /cannot push because a reference that you are trying to update on the remote contains commits that are not present locally/) 56 | } 57 | 58 | lg.callMain(['fetch','origin']); 59 | lg.callMain(['merge', 'origin/master']); 60 | 61 | assert.match(lg.callWithOutput(['status']), /conflict\: a\:test\.txt o\:test\.txt t\:test\.txt/); 62 | 63 | FS.writeFile('test.txt', 'abcxyz'); 64 | lg.callMain(['add', 'test.txt']); 65 | lg.callMain(['commit', '-m', 'resolved conflict']); 66 | 67 | assert.match(lg.callWithOutput(['log']), /resolved conflict/); 68 | assert.match(lg.callWithOutput(['push']),/pushed/); 69 | console.log('status', lg.callWithOutput(['status'])); 70 | assert.equal('abcxyz', FS.readFile('test.txt', {encoding: 'utf8'})); 71 | }); 72 | }); -------------------------------------------------------------------------------- /test/fetch.spec.js: -------------------------------------------------------------------------------- 1 | import { lgPromise } from './common.js'; 2 | import assert from 'assert'; 3 | 4 | describe('git fetch', () => { 5 | it('should create 1 bare and 2 clones and fetch changes', async () => { 6 | const lg = await lgPromise; 7 | const FS = lg.FS; 8 | 9 | FS.mkdir('bare'); 10 | FS.chdir('bare'); 11 | lg.callMain(['init', '--bare', '.']); 12 | 13 | lg.callMain(['config', 'user.name', 'The Tester']); 14 | lg.callMain(['config', 'user.email', 'test@testing.com']); 15 | 16 | FS.chdir('..'); 17 | lg.callMain(['clone', 'bare', 'test1']); 18 | 19 | FS.chdir('test1'); 20 | 21 | lg.callMain(['config', 'user.name', 'The Tester']); 22 | lg.callMain(['config', 'user.email', 'test@testing.com']); 23 | 24 | FS.writeFile('test.txt', 'abcdef'); 25 | lg.callMain(['add', 'test.txt']); 26 | lg.callMain(['commit', '-m', 'test commit 1']); 27 | lg.callMain(['push']); 28 | FS.chdir('..'); 29 | 30 | lg.callMain(['clone', 'bare', 'test2']); 31 | FS.chdir('test2'); 32 | 33 | lg.callMain(['config', 'user.name', 'The Tester']); 34 | lg.callMain(['config', 'user.email', 'test@testing.com']); 35 | 36 | FS.writeFile('test2.txt', 'abcdef'); 37 | lg.callMain(['add', 'test2.txt']); 38 | lg.callMain(['commit', '-m', 'test commit 2']); 39 | 40 | lg.callMain(['push']); 41 | 42 | lg.callMain(['log']); 43 | FS.chdir('..'); 44 | 45 | FS.chdir('test1'); 46 | 47 | lg.callMain(['fetch', 'origin']); 48 | lg.callMain(['merge', 'origin/master']); 49 | 50 | const result = lg.callWithOutput(['log']); 51 | assert.ok(result.indexOf('test commit 2') > 0); 52 | assert.ok(result.indexOf('test commit 1') > result.indexOf('test commit 2') > 0); 53 | 54 | lg.callMain(['checkout', '-b', 'testbranch']); 55 | FS.writeFile('testinbranch.txt', 'abcdef'); 56 | lg.callMain(['add', 'testinbranch.txt']); 57 | lg.callMain(['commit', '-m', 'test in branch']); 58 | lg.callMain(['push']); 59 | 60 | FS.chdir('..'); 61 | 62 | FS.chdir('test2'); 63 | 64 | assert.equal(FS.analyzePath('testinbranch.txt').exists, false); 65 | lg.callMain(['fetch', 'origin']); 66 | lg.callMain(['checkout', 'testbranch']); 67 | 68 | assert.match(lg.callWithOutput(['status']), /On branch testbranch/); 69 | assert.equal(FS.analyzePath('testinbranch.txt').exists, true); 70 | assert.equal(FS.readFile('testinbranch.txt', {encoding: 'utf8'}), 'abcdef'); 71 | }); 72 | }); 73 | -------------------------------------------------------------------------------- /test/lg2.js: -------------------------------------------------------------------------------- 1 | ../emscriptenbuild/libgit2/examples/lg2.js -------------------------------------------------------------------------------- /test/lg2.wasm: -------------------------------------------------------------------------------- 1 | ../emscriptenbuild/libgit2/examples/lg2.wasm -------------------------------------------------------------------------------- /test/nodefs.spec.js: -------------------------------------------------------------------------------- 1 | import { lgPromise } from './common.js'; 2 | import assert from 'assert'; 3 | import {rmSync} from 'fs'; 4 | 5 | describe('nodefs', function () { 6 | this.timeout(20000); 7 | 8 | it('should clone using nodefs', async () => { 9 | const lg = await lgPromise; 10 | 11 | const FS = lg.FS; 12 | const NODEFS = FS.filesystems.NODEFS; 13 | const clonedir = 'nodefsclonetest'; 14 | 15 | FS.mkdir('/nodefs'); 16 | FS.mount(NODEFS, { root: '.' }, '/nodefs'); 17 | FS.chdir('/nodefs'); 18 | 19 | FS.writeFile('/home/web_user/.gitconfig', ` 20 | [safe] 21 | directory = nodefsclonetest 22 | 23 | [user] 24 | name = Test User 25 | email = test@example.com 26 | `); 27 | 28 | // clone a repository from github 29 | lg.callMain(['clone', 'https://github.com/petersalomonsen/wasm-git.git', clonedir]); 30 | 31 | FS.chdir(clonedir); 32 | console.log(FS.readdir('.')); 33 | lg.callMain(['log']); 34 | 35 | assert(FS.readdir('.').indexOf('README.md') > -1); 36 | FS.chdir('..'); 37 | rmSync('clonedir', {recursive: true, force: true}); 38 | console.log('clone to nodefs suceeded'); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /test/revert.spec.js: -------------------------------------------------------------------------------- 1 | import { lgPromise } from './common.js'; 2 | import assert from 'assert'; 3 | 4 | describe('git revert', () => { 5 | it('should revert commit', async () => { 6 | const lg = await lgPromise; 7 | const FS = lg.FS; 8 | FS.mkdir('/memfs'); 9 | FS.mount(lg.MEMFS, { root: '.' }, '/memfs'); 10 | FS.chdir('/memfs'); 11 | 12 | 13 | FS.writeFile('/home/web_user/.gitconfig', '[user]\n' + 14 | 'name = Test User\n' + 15 | 'email = test@example.com'); 16 | 17 | FS.mkdir('testrevert'); 18 | FS.chdir('testrevert'); 19 | lg.callMain(['init', '.']); 20 | 21 | FS.writeFile('test.txt', 'text 1'); 22 | lg.callMain(['add', 'test.txt']); 23 | lg.callMain(['commit', '-m', 'test commit']); 24 | 25 | assert.equal(FS.readFile('test.txt', { encoding: 'utf8' }), 'text 1'); 26 | FS.writeFile('test.txt', 'text 2'); 27 | lg.callMain(['add', 'test.txt']); 28 | lg.callMain(['commit', '-m', 'test commit 2']); 29 | 30 | lg.callMain(['revert', 'HEAD']); 31 | 32 | assert.equal(FS.readFile('test.txt', { encoding: 'utf8' }), 'text 1', 33 | 'expecting file content to be reverted'); 34 | 35 | assert.match(lg.callWithOutput(['status']),/modified:\s+test.txt/); 36 | 37 | lg.callMain(['commit', '-m', 'reverted to commit 1']); 38 | assert.equal(lg.callWithOutput(['status']),'# On branch master'); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /web-test-runner.config.js: -------------------------------------------------------------------------------- 1 | import { playwrightLauncher } from '@web/test-runner-playwright'; 2 | import { startServer } from './test-browser/githttpserver.js'; 3 | 4 | startServer(); 5 | 6 | export default { 7 | files: [ 8 | '**/*.spec.js', // include `.spec.ts` files 9 | '!./node_modules/**/*', // exclude any node modules 10 | ], 11 | concurrency: 1, 12 | watch: false, 13 | testFramework: { 14 | config: { 15 | ui: 'bdd', 16 | timeout: '5000', 17 | }, 18 | }, 19 | testRunnerHtml: testRunnerImport => 20 | ` 21 | 22 | 27 | 28 | 29 | `, 30 | browsers: [ 31 | playwrightLauncher({ product: 'chromium', createBrowserContext: async ({ browser }) => { 32 | 33 | const ctx = await browser.newContext({}); 34 | await ctx.route(/http:\/\/localhost:8000\/.*\.git\/.*/, async (route) => { 35 | const url = route.request().url(); 36 | const response = await route.fetch({url: url.replace(':8000/', ':8080/')}); 37 | const body = await response.body(); 38 | await route.fulfill({ body }); 39 | }); 40 | return ctx; 41 | }, }), 42 | /*playwrightLauncher({ 43 | product: 'firefox', launchOptions: { 44 | headless: false, 45 | firefoxUserPrefs: { 46 | 'media.autoplay.block-webaudio': false 47 | } 48 | } 49 | }),*/ 50 | /*playwrightLauncher({ 51 | product: 'webkit',launchOptions: { 52 | headless: false 53 | } 54 | })*/ 55 | ], 56 | }; 57 | --------------------------------------------------------------------------------