├── .coveragerc ├── .dockerignore ├── .gitignore ├── AUTHORS ├── ChangeLog ├── Dockerfile ├── LICENSE ├── MANIFEST.in ├── Makefile ├── PKG-INFO ├── README.rst ├── bin └── github2gitlab ├── github2gitlab ├── __init__.py └── main.py ├── requirements.txt ├── setup.cfg ├── setup.py ├── test-requirements.txt ├── tests ├── integration.py ├── setup-gitlab.sh └── test_github2gitlab.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = */test/* 3 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | github2gitlab.egg-info 2 | *.pyc 3 | hub2lab.egg-info 4 | build/ 5 | dist/ 6 | .eggs/ 7 | .idea/ 8 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Pan Luo 2 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | CHANGES 2 | ======= 3 | 4 | v1.6.1 5 | ------ 6 | 7 | * Use header for github auth and strip \r for validation 8 | * Update README for 1.6.0 9 | 10 | v1.6.0 11 | ------ 12 | 13 | * Bump version to 1.6.0 14 | * Use gitlab API v4 15 | * Fix the missing version complained by pbr 16 | * Update readme 17 | * Rename to hub2lab and add Makefile 18 | 19 | v1.5.6 20 | ------ 21 | 22 | * Bump version to 1.5.6 23 | * Add --clean option and fix issue using gitlab token from others 24 | * Add note in readme 25 | * Add docker support 26 | * Add support for https, token push and ssh key optional 27 | * Add missing six dependency 28 | * Strip out extract space 29 | * Fix gitlab remote invalid url 30 | * Original github2gitlab 1.5.5 31 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:2.7-alpine3.7 2 | 3 | ENV PBR_VERSION=1.5.6 4 | 5 | RUN apk add --update --no-cache git 6 | 7 | WORKDIR /src 8 | 9 | COPY . . 10 | 11 | RUN pip install --no-cache-dir -e . 12 | 13 | CMD [ "github2gitlab" ] 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS 2 | include ChangeLog 3 | 4 | exclude .gitignore 5 | 6 | global-exclude *.pyc 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: docs 2 | 3 | env: 4 | pip install virtualenv && \ 5 | virtualenv venv && \ 6 | . venv/bin/activate && \ 7 | make deps 8 | 9 | deps: 10 | pip install -r requirements.txt 11 | pip install -r test-requirements.txt 12 | npm install 13 | 14 | clean: 15 | find . -name '*.pyc' -exec rm -f {} \; 16 | find . -name '*.pyo' -exec rm -f {} \; 17 | find . -name '*~' -exec rm -f {} \; 18 | 19 | release: 20 | rm -rf dist/* 21 | python setup.py bdist_egg 22 | python setup.py sdist 23 | twine upload dist/* 24 | -------------------------------------------------------------------------------- /PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 1.1 2 | Name: github2gitlab 3 | Version: 1.5.5 4 | Summary: command line tool to migrate projects from GitHub to GitLab 5 | Home-page: http://workbench.dachary.org/dachary/github2gitlab 6 | Author: Loic Dachary 7 | Author-email: loic@dachary.org 8 | License: UNKNOWN 9 | Description: github2gitlab 10 | ============= 11 | 12 | github2gitlab is a command line tool to mirror projects from GitHub 13 | to GitLab. It does the following, in sequence: 14 | 15 | * Upload the ~/.ssh/id_rsa.pub ssh key to gitlab if not found 16 | * Create the gitlab project if it does not exist 17 | * Mirror the github git repository to the gitlab git repository 18 | * Create or update the GitLab merge requests to match the 19 | GitHub pull requests 20 | 21 | Examples 22 | ======== 23 | 24 | Mirror http://github.com/dachary/test to http://workbench.dachary.org/dachary/test 25 | 26 | .. code:: sh 27 | 28 | github2gitlab \ 29 | --gitlab-url http://workbench.dachary.org \ 30 | --gitlab-token sxQJ67SQKihMrGWVf \ 31 | --github-repo dachary/test 32 | 33 | Mirror http://github.com/ceph/ceph to 34 | http://workbench.dachary.org/ceph/ceph-backports and use the GitHub 35 | token to be allowed to do more requests than when anonymous. 36 | Use --ignore-closed to get rid of pull requests that are closed and 37 | were never merged. 38 | 39 | .. code:: sh 40 | 41 | github2gitlab \ 42 | --gitlab-url http://workbench.dachary.org \ 43 | --gitlab-token sxQJ67SQKihMrGWVf \ 44 | --gitlab-repo ceph/ceph-backports \ 45 | --github-token 64933d355fda9844aadd4e224d \ 46 | --github-repo ceph/ceph \ 47 | --ignore-closed 48 | 49 | Mirroring details 50 | ================= 51 | 52 | The GitHub git repository contains a reference for each pull requests. 53 | For instance the pull request 483 has the refs/pull/483/head reference 54 | which is the tip of the branch that was pushed. If the pull request is 55 | open and can be merged on the destination, the reference 56 | refs/pull/483/merge also exists and is the result of the merge. 57 | 58 | Instead of mirroring the refs/pull/\* references to GitLab, they are 59 | moved to refs/heads/pull/\* so they become branches. If GitLab CI is 60 | watching the project, it will run a job each time the pull/\*/head 61 | reference is updated. 62 | 63 | The pull requests title and description are mirrored exactly. The 64 | state of the pull request cannot be mapped exactly and is translated 65 | as follows:: 66 | 67 | if the pull request is opened, the merge request is opened 68 | if the pull request is closed, 69 | if the pull request merged_at field is null, 70 | the merge request is closed 71 | else 72 | the merge request is merged 73 | 74 | If a merge request is opened to mirror a pull request that has been 75 | merged already, GitLab will refuse to set it to the merged state 76 | because it notices that there would be nothing to merge. In this case 77 | the merge request is set to the closed state and the :MERGED: string 78 | is append to the description. 79 | 80 | * GitLab API http://doc.gitlab.com/ce/api/ 81 | * GitHub API https://developer.github.com/v3/ 82 | 83 | Hacking 84 | ======= 85 | 86 | * Get the code : git clone http://workbench.dachary.org/dachary/github2gitlab.git 87 | * Run the unit tests : tox 88 | * Run the integration tests. They require a gitlab token and a github token from 89 | actual users with permissions to delete and create projects. The github project 90 | specified with --github-repo and the github project specified with --gitlab-repo 91 | will be removed and all their data and git repository lost during the test. 92 | 93 | PYTHONPATH=. tests/integration.py \ 94 | --gitlab-url http://workbench.dachary.org \ 95 | --gitlab-token XXXXXXXXX \ 96 | --gitlab-repo dachary/testrepo2 \ 97 | --github-token XXXXXXXXX \ 98 | --github-repo dachary/testrepo \ 99 | --ssh-public-key ~/.ssh/id_rsa.pub \ 100 | --verbose 101 | 102 | * Tag a version 103 | 104 | - version=1.3.0 ; perl -pi -e "s/^version.*/version = $version/" setup.cfg ; for i in 1 2 ; do python setup.py sdist ; amend=$(git log -1 --oneline | grep --quiet "version $version" && echo --amend) ; git commit $amend -m "version $version" ChangeLog setup.cfg ; git tag -a -f -m "version $version" $version ; done 105 | 106 | * Check the documentation : rst2html < README.rst > /tmp/a.html 107 | 108 | * Publish a new version 109 | 110 | - python setup.py sdist upload --sign 111 | - git push ; git push --tags 112 | 113 | * pypi maintenance 114 | 115 | - python setup.py register # if the project does not yet exist 116 | - trim old versions at https://pypi.python.org/pypi/github2gitlab 117 | 118 | 119 | Platform: UNKNOWN 120 | Classifier: Environment :: No Input/Output (Daemon) 121 | Classifier: Intended Audience :: Information Technology 122 | Classifier: Intended Audience :: System Administrators 123 | Classifier: Operating System :: POSIX :: Linux 124 | Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+) 125 | Classifier: Programming Language :: Python 126 | Classifier: Programming Language :: Python :: 2.7 127 | Classifier: Topic :: Utilities 128 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | github2gitlab 2 | ============= 3 | 4 | NOTE: This is based on the work of https://pypi.python.org/pypi/github2gitlab. 5 | However, the original repo http://workbench.dachary.org/dachary/github2gitlab 6 | is not accessible anymore. This is a clone with some improvements. 7 | 8 | github2gitlab is a command line tool to mirror projects from GitHub 9 | to GitLab. It does the following, in sequence: 10 | 11 | * Upload the ~/.ssh/id_rsa.pub ssh key to gitlab if not found 12 | * Create the gitlab project if it does not exist 13 | * Mirror the github git repository to the gitlab git repository 14 | * Create or update the GitLab merge requests to match the 15 | GitHub pull requests 16 | 17 | Examples 18 | ======== 19 | 20 | Mirror http://github.com/dachary/test to http://workbench.dachary.org/dachary/test 21 | 22 | .. code:: sh 23 | 24 | github2gitlab \ 25 | --gitlab-url http://workbench.dachary.org \ 26 | --gitlab-token sxQJ67SQKihMrGWVf \ 27 | --github-repo dachary/test 28 | 29 | Mirror http://github.com/ceph/ceph to 30 | http://workbench.dachary.org/ceph/ceph-backports and use the GitHub 31 | token to be allowed to do more requests than when anonymous. 32 | Use --ignore-closed to get rid of pull requests that are closed and 33 | were never merged. 34 | 35 | .. code:: sh 36 | 37 | github2gitlab \ 38 | --gitlab-url http://workbench.dachary.org \ 39 | --gitlab-token sxQJ67SQKihMrGWVf \ 40 | --gitlab-repo ceph/ceph-backports \ 41 | --github-token 64933d355fda9844aadd4e224d \ 42 | --github-repo ceph/ceph \ 43 | --ignore-closed 44 | 45 | Mirroring details 46 | ================= 47 | 48 | The GitHub git repository contains a reference for each pull requests. 49 | For instance the pull request 483 has the refs/pull/483/head reference 50 | which is the tip of the branch that was pushed. If the pull request is 51 | open and can be merged on the destination, the reference 52 | refs/pull/483/merge also exists and is the result of the merge. 53 | 54 | Instead of mirroring the refs/pull/\* references to GitLab, they are 55 | moved to refs/heads/pull/\* so they become branches. If GitLab CI is 56 | watching the project, it will run a job each time the pull/\*/head 57 | reference is updated. 58 | 59 | The pull requests title and description are mirrored exactly. The 60 | state of the pull request cannot be mapped exactly and is translated 61 | as follows:: 62 | 63 | if the pull request is opened, the merge request is opened 64 | if the pull request is closed, 65 | if the pull request merged_at field is null, 66 | the merge request is closed 67 | else 68 | the merge request is merged 69 | 70 | If a merge request is opened to mirror a pull request that has been 71 | merged already, GitLab will refuse to set it to the merged state 72 | because it notices that there would be nothing to merge. In this case 73 | the merge request is set to the closed state and the :MERGED: string 74 | is append to the description. 75 | 76 | * GitLab API http://doc.gitlab.com/ce/api/ 77 | * GitHub API https://developer.github.com/v3/ 78 | 79 | Hacking 80 | ======= 81 | 82 | * Get the code : git clone http://workbench.dachary.org/dachary/github2gitlab.git 83 | * Run the unit tests : tox 84 | * Run the integration tests. They require a gitlab token and a github token from 85 | actual users with permissions to delete and create projects. The github project 86 | specified with --github-repo and the github project specified with --gitlab-repo 87 | will be removed and all their data and git repository lost during the test. 88 | 89 | PYTHONPATH=. tests/integration.py \ 90 | --gitlab-url http://workbench.dachary.org \ 91 | --gitlab-token XXXXXXXXX \ 92 | --gitlab-repo dachary/testrepo2 \ 93 | --github-token XXXXXXXXX \ 94 | --github-repo dachary/testrepo \ 95 | --ssh-public-key ~/.ssh/id_rsa.pub \ 96 | --verbose 97 | 98 | * Tag a version 99 | 100 | - version=1.3.0 ; perl -pi -e "s/^version.*/version = $version/" setup.cfg ; for i in 1 2 ; do python setup.py sdist ; amend=$(git log -1 --oneline | grep --quiet "version $version" && echo --amend) ; git commit $amend -m "version $version" ChangeLog setup.cfg ; git tag -a -f -m "version $version" $version ; done 101 | 102 | * Check the documentation : rst2html < README.rst > /tmp/a.html 103 | 104 | * Publish a new version 105 | 106 | - python setup.py sdist upload --sign 107 | - git push ; git push --tags 108 | 109 | * pypi maintenance 110 | 111 | - python setup.py register # if the project does not yet exist 112 | - trim old versions at https://pypi.python.org/pypi/github2gitlab 113 | -------------------------------------------------------------------------------- /bin/github2gitlab: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- mode: python; coding: utf-8 -*- 3 | # 4 | # Copyright (C) 2015 5 | # 6 | # Author: Loic Dachary 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Affero General Public License as 10 | # published by the Free Software Foundation, either version 3 of the 11 | # License, or (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Affero General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Affero General Public License 19 | # along with this program. If not, see ``. 20 | # 21 | import sys 22 | from github2gitlab.main import GitHub2GitLab 23 | 24 | if __name__ == "__main__": 25 | sys.exit(GitHub2GitLab.factory(sys.argv[1:]).run()) 26 | -------------------------------------------------------------------------------- /github2gitlab/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubc/github2gitlab/66508306175c04cef37945183fd89942fc2dab72/github2gitlab/__init__.py -------------------------------------------------------------------------------- /github2gitlab/main.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python; coding: utf-8 -*- 2 | # 3 | # Copyright (C) 2015 4 | # 5 | # Author: Loic Dachary 6 | # 7 | # This program is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU Affero General Public License as 9 | # published by the Free Software Foundation, either version 3 of the 10 | # License, or (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU Affero General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU Affero General Public License 18 | # along with this program. If not, see ``. 19 | # 20 | import argparse 21 | import git 22 | import gitdb 23 | import hashlib 24 | import json 25 | import logging 26 | import os 27 | import re 28 | import requests 29 | import six 30 | from six.moves.urllib import parse 31 | import subprocess 32 | import time 33 | import shutil 34 | 35 | DESCRIPTION_MAX = 1024 36 | 37 | logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s') 38 | 39 | log = logging.getLogger(__name__) 40 | 41 | 42 | class GitHub2GitLab(object): 43 | TAG_MERGED = ":MERGED:" 44 | 45 | STATE_EVENT2MERGE_STATE = { 46 | 'merge': 'merged', 47 | 'reopen': 'opened', 48 | 'close': 'closed', 49 | } 50 | 51 | def __init__(self, args): 52 | self.args = args 53 | 54 | self.args.ssh_public_key = os.path.expanduser( 55 | self.args.ssh_public_key 56 | ) 57 | 58 | if not self.args.gitlab_repo: 59 | self.args.gitlab_repo = self.args.github_repo 60 | (self.args.gitlab_namespace, 61 | self.args.gitlab_name) = self.args.gitlab_repo.split('/') 62 | self.args.gitlab_repo = parse.quote_plus(self.args.gitlab_repo) 63 | 64 | self.github = { 65 | 'url': "https://api.github.com", 66 | 'git': "https://github.com", 67 | 'repo': self.args.github_repo, 68 | 'token': self.args.github_token, 69 | } 70 | if self.args.branches: 71 | self.github['branches'] = self.args.branches.split(',') 72 | self.gitlab = { 73 | 'git': self.args.gitlab_url.replace('http://', 'git@'), 74 | 'host': self.args.gitlab_url, 75 | 'name': self.args.gitlab_name, 76 | 'namespace': self.args.gitlab_namespace, 77 | 'url': self.args.gitlab_url + "/api/v4", 78 | 'repo': self.args.gitlab_repo, 79 | 'token': self.args.gitlab_token, 80 | } 81 | 82 | if self.args.verbose: 83 | level = logging.DEBUG 84 | else: 85 | level = logging.INFO 86 | 87 | logging.getLogger('github2gitlab').setLevel(level) 88 | 89 | self.tmpdir = "/tmp" 90 | 91 | @staticmethod 92 | def get_parser(): 93 | parser = argparse.ArgumentParser( 94 | description="migrate projects from GitHub to GitLab") 95 | 96 | parser.add_argument('--gitlab-url', 97 | help='Gitlab url', 98 | required=True) 99 | parser.add_argument('--gitlab-token', 100 | help='Gitlab authentication token', 101 | required=True) 102 | parser.add_argument('--gitlab-repo', 103 | help='Gitlab repo (for instance ceph/ceph)') 104 | parser.add_argument('--github-token', 105 | help='GitHub authentication token') 106 | parser.add_argument('--github-repo', 107 | help='GitHub repo (for instance ceph/ceph)', 108 | required=True) 109 | parser.add_argument('--ssh-public-key', 110 | default='~/.ssh/id_rsa.pub', 111 | help='SSH public key') 112 | parser.add_argument('--branches', 113 | help=('comma separated list of git branches ' 114 | 'to mirror (defaults to all)')) 115 | parser.add_argument('--ignore-closed', action='store_const', 116 | const=True, 117 | help='ignore pull requests closed and not merged') 118 | parser.add_argument('--skip-pull-requests', action='store_const', 119 | const=True, 120 | help='do not mirror PR to MR') 121 | parser.add_argument('--verbose', action='store_const', 122 | const=True, 123 | help='enable verbose (debug) logging') 124 | parser.add_argument('--cache', action='store_const', 125 | const=True, 126 | help='cache GitHub pull requests list') 127 | parser.add_argument('--clean', action='store_const', 128 | const=True, 129 | help='Remove the repo after sync') 130 | return parser 131 | 132 | @staticmethod 133 | def factory(argv): 134 | return GitHub2GitLab(GitHub2GitLab.get_parser().parse_args(argv)) 135 | 136 | def run(self): 137 | self.add_key() 138 | if self.add_project(): 139 | self.unprotect_branches() 140 | self.git_mirror() 141 | if not self.args.skip_pull_requests: 142 | self.pull_requests = self.get_pull_requests() 143 | self.merge_requests = self.get_merge_requests() 144 | self.update_merge_pull() 145 | self.sync() 146 | if self.args.clean: 147 | self.clean() 148 | return 0 149 | 150 | def sh(self, command): 151 | log.debug(":sh: " + command) 152 | proc = subprocess.Popen( 153 | args=command, 154 | stdout=subprocess.PIPE, 155 | stderr=subprocess.STDOUT, 156 | shell=True, 157 | bufsize=1) 158 | lines = [] 159 | with proc.stdout: 160 | for line in iter(proc.stdout.readline, b''): 161 | line = line.decode('utf-8') 162 | lines.append(line) 163 | log.debug(str(line.strip())) 164 | if proc.wait() != 0: 165 | raise subprocess.CalledProcessError( 166 | returncode=proc.returncode, 167 | cmd=command 168 | ) 169 | return "".join(lines) 170 | 171 | def gitlab_create_remote(self, repo): 172 | # when using access token, gitlab doesn't care the username 173 | url = self.gitlab['git'].replace( 174 | 'https://', 'https://user:{}@'.format(self.gitlab['token'])) 175 | repo.create_remote('gitlab', 176 | url + ("/" if url.startswith('http') else ':') + 177 | self.gitlab['namespace'] + "/" + 178 | self.gitlab['name'] + ".git") 179 | 180 | def git_mirror(self): 181 | name = self.gitlab['name'] 182 | if not os.path.exists(name): 183 | self.sh("git clone --bare " + self.github['git'] + 184 | "/" + self.github['repo'] + " " + name) 185 | repo = git.Repo(name) 186 | os.chdir(name) 187 | if not hasattr(repo.remotes, 'gitlab'): 188 | self.gitlab_create_remote(repo) 189 | if 'branches' in self.github: 190 | branches_ref = " ".join([ 191 | "+refs/heads/{b}:refs/heads/{b}".format(b=b) 192 | for b in self.github['branches'] 193 | ]) 194 | else: 195 | branches_ref = "+refs/heads/*:refs/heads/*" 196 | # 197 | # Fetch 198 | # 199 | self.sh("git fetch --force origin " + 200 | branches_ref + 201 | " +refs/tags/*:refs/tags/*") 202 | # 203 | # Track refs 204 | # 205 | if self.args.skip_pull_requests: 206 | self.git_mirror_optimize(repo) 207 | else: 208 | self.sh("git fetch origin +refs/pull/*:refs/heads/pull/*") 209 | # 210 | # Push 211 | # 212 | self.sh("git push --prune --force gitlab " + 213 | branches_ref + " " + 214 | "+refs/heads/pull/*:refs/heads/pull/* " + 215 | "+refs/tags/*:refs/tags/* ") 216 | os.chdir("..") 217 | self.revision2commit = {} 218 | 219 | def git_mirror_optimize(self, repo): 220 | self.sh("git fetch origin +refs/pull/*:refs/remotes/origin/pull/*") 221 | for head in repo.refs: 222 | pr = re.search('^origin/pull/(\d+)/head$', head.name) 223 | if not pr: 224 | continue 225 | pr = pr.group(1) 226 | merge_name = 'origin/pull/' + pr + '/merge' 227 | if merge_name not in repo.refs: 228 | log.debug(head.name + " cannot merge, ignore") 229 | continue 230 | merge = repo.commit(merge_name) 231 | if merge.parents[1] != head.commit: 232 | log.debug(head.name + " merge is obsolete, skip") 233 | continue 234 | known_head_name = 'pull/' + pr + '/head' 235 | try: 236 | known_head = repo.commit(known_head_name) 237 | if known_head == head.commit: 238 | log.debug(head.name + " head has not moved, skip") 239 | continue 240 | action = 'update' 241 | except gitdb.exc.BadName: 242 | action = 'create' 243 | log.debug(action + " ref " + known_head_name + "==" + 244 | head.commit.hexsha) 245 | repo.git.update_ref('refs/' + known_head_name, head.commit) 246 | log.info(action + " branch " + 'pull/' + pr + "/merge == " + 247 | merge.hexsha) 248 | repo.git.update_ref('refs/heads/pull/' + pr + '/merge', merge) 249 | 250 | def clean(self): 251 | log.info('Removing cloned repo...') 252 | shutil.rmtree(self.gitlab['name']) 253 | 254 | def add_key(self): 255 | "Add ssh key to gitlab if necessary" 256 | try: 257 | with open(self.args.ssh_public_key) as f: 258 | public_key = f.read().strip() 259 | except: 260 | log.debug("No key found in {}".format(self.args.ssh_public_key)) 261 | return None 262 | g = self.gitlab 263 | url = g['url'] + "/user/keys" 264 | query = {'private_token': g['token']} 265 | keys = requests.get(url, params=query).json() 266 | log.debug("looking for '" + public_key + "' in " + str(keys)) 267 | if (list(filter(lambda key: key['key'] == public_key, keys))): 268 | log.debug(self.args.ssh_public_key + " already exists") 269 | return None 270 | else: 271 | name = 'github2gitlab' 272 | log.info("add " + name + " ssh public key from " + 273 | self.args.ssh_public_key) 274 | query['title'] = name 275 | query['key'] = public_key 276 | result = requests.post(url, query) 277 | if result.status_code != requests.codes.created: 278 | log.warn('Key {} already in GitLab. ' 279 | 'Possible under a different user. Skipping...' 280 | .format(self.args.ssh_public_key)) 281 | return public_key 282 | 283 | def add_project(self): 284 | "Create project in gitlab if it does not exist" 285 | g = self.gitlab 286 | url = g['url'] + "/projects/" + g['repo'] 287 | query = {'private_token': g['token']} 288 | if (requests.get(url, params=query).status_code == requests.codes.ok): 289 | log.debug("project " + url + " already exists") 290 | return None 291 | else: 292 | log.info("add project " + g['repo']) 293 | url = g['url'] + "/projects" 294 | query['public'] = 'true' 295 | query['namespace'] = g['namespace'] 296 | query['name'] = g['name'] 297 | result = requests.post(url, params=query) 298 | if result.status_code != requests.codes.created: 299 | raise ValueError(result.text) 300 | log.debug("project " + g['repo'] + " added: " + 301 | result.text) 302 | return result.json() 303 | 304 | def unprotect_branches(self): 305 | "Unprotect branches of the GitLab project" 306 | g = self.gitlab 307 | url = g['url'] + "/projects/" + g['repo'] + "/repository/branches" 308 | query = {'private_token': g['token']} 309 | unprotected = 0 310 | r = requests.get(url, params=query) 311 | r.raise_for_status() 312 | for branch in r.json(): 313 | if branch['protected']: 314 | r = requests.put(url + "/" + branch['name'] + 315 | "/unprotect", params=query) 316 | r.raise_for_status() 317 | unprotected += 1 318 | return unprotected 319 | 320 | def update_merge_pull(self): 321 | self.merge2pull = {} 322 | self.pull2merge = {} 323 | for (id, merge) in six.iteritems(self.merge_requests): 324 | pull = merge['source_branch'].split('/') 325 | if len(pull) == 3: 326 | number = pull[1] 327 | if number in self.pull_requests: 328 | self.merge2pull[id] = self.pull_requests[number] 329 | self.pull2merge[number] = self.merge_requests[id] 330 | 331 | @staticmethod 332 | def field_equal(pull, pull_field, pull_value, 333 | merge, merge_field, merge_value): 334 | if pull_field == 'state': 335 | return ((pull_value == 'open' and 336 | merge_value == 'opened') or 337 | (pull_value == 'closed' and 338 | merge_value in ('closed', 'merged'))) 339 | if pull_field == 'body': 340 | if merge_value is None: 341 | merge_value = '' 342 | if pull_value is None: 343 | pull_value = '' 344 | merge_value = merge_value.replace(GitHub2GitLab.TAG_MERGED, '') 345 | return (pull_value[:DESCRIPTION_MAX] == 346 | merge_value[:DESCRIPTION_MAX]) 347 | else: 348 | return pull_value == merge_value 349 | 350 | @staticmethod 351 | def field_update(pull, pull_field, pull_value, 352 | merge, merge_field, merge_value): 353 | if pull_value is None: 354 | pull_value = '' 355 | if pull_field == 'state': 356 | if pull_value == 'open': 357 | value = 'reopen' 358 | elif pull_value == 'closed': 359 | if pull.get('merged_at'): 360 | value = 'merge' 361 | else: 362 | value = 'close' 363 | return ('state_event', value) 364 | elif pull_field == 'body': 365 | return (merge_field, pull_value[:DESCRIPTION_MAX]) 366 | else: 367 | return (merge_field, pull_value) 368 | 369 | def sync(self): 370 | pull_f2merge_f = { 371 | 'state': 'state', 372 | 'body': 'description', 373 | 'title': 'title', 374 | } 375 | for number in sorted(self.pull_requests.keys()): 376 | pull = self.pull_requests[number] 377 | merge = None 378 | if number in self.pull2merge: 379 | merge = self.pull2merge[number] 380 | else: 381 | source_branch = 'pull/' + number + '/head' 382 | target_branch = pull['base']['ref'] 383 | if (self.rev_parse(pull, source_branch) and 384 | self.rev_parse(pull, target_branch)): 385 | data = {'title': pull['title'], 386 | 'source_branch': source_branch, 387 | 'target_branch': target_branch} 388 | if pull['body']: 389 | data['description'] = pull['body'][:DESCRIPTION_MAX] 390 | merge = self.create_merge_request(data) 391 | 392 | if merge: 393 | updates = {} 394 | for (pull_field, merge_field) in six.iteritems(pull_f2merge_f): 395 | if not self.field_equal(pull, 396 | pull_field, 397 | pull[pull_field], 398 | merge, 399 | merge_field, 400 | merge[merge_field]): 401 | (key, value) = self.field_update(pull, 402 | pull_field, 403 | pull[pull_field], 404 | merge, 405 | merge_field, 406 | merge[merge_field]) 407 | updates[key] = value 408 | if updates: 409 | self.update_merge_request(merge, updates) 410 | else: 411 | log.debug("https://github.com/" + 412 | self.github['repo'] + "/" + 413 | "pull/" + number + " == " + 414 | self.gitlab['host'] + "/" + 415 | parse.unquote(self.gitlab['repo']) + "/" + 416 | "merge_requests/" + str(merge['iid'])) 417 | 418 | def rev_parse(self, pull, revision): 419 | if revision in self.revision2commit: 420 | return True 421 | else: 422 | repo = git.Repo(self.gitlab['name']) 423 | try: 424 | repo.rev_parse("heads/" + revision) 425 | return True 426 | except gitdb.exc.BadName: 427 | log.debug("ignore https://github.com/" + 428 | self.github['repo'] + "/pull/" + 429 | str(pull['number']) + " because " + 430 | revision + " is not a known revision") 431 | return False 432 | 433 | @staticmethod 434 | def json_loads(payload): 435 | "Log the payload that cannot be parsed" 436 | try: 437 | return json.loads(payload) 438 | except ValueError as e: 439 | log.error("unable to json.loads(" + payload + ")") 440 | raise e 441 | 442 | def get(self, url, query, cache): 443 | payloads_file = (self.tmpdir + "/" + 444 | hashlib.sha1(url.encode('utf-8')).hexdigest() + 445 | ".json") 446 | if 'access_token' in query: 447 | headers = {"Accept": "application/vnd.github.v3+json", 448 | "Authorization": f'token {query["access_token"]}' 449 | } 450 | q = query 451 | del q['access_token'] 452 | else: 453 | headers = None 454 | q = query 455 | if (not cache or not os.access(payloads_file, 0) or 456 | time.time() - os.stat(payloads_file).st_mtime > 24 * 60 * 60): 457 | payloads = [] 458 | next_query = q 459 | while next_query: 460 | log.debug(str(next_query)) 461 | result = requests.get(url, params=next_query, headers=headers) 462 | payloads += result.json() 463 | next_query = None 464 | for link in result.headers.get('Link', '').split(','): 465 | if 'rel="next"' in link: 466 | m = re.search('<(.*)>', link) 467 | if m: 468 | parsed_url = parse.urlparse(m.group(1)) 469 | # append query in case it was not preserved 470 | # (gitlab has that problem) 471 | next_query = q 472 | next_query.update( 473 | dict(parse.parse_qsl(parsed_url.query)) 474 | ) 475 | if cache: 476 | with open(payloads_file, 'w') as f: 477 | json.dump(payloads, f) 478 | else: 479 | with open(payloads_file, 'r') as f: 480 | payloads = json.load(f) 481 | return payloads 482 | 483 | def get_pull_requests(self): 484 | "https://developer.github.com/v3/pulls/#list-pull-requests" 485 | g = self.github 486 | query = {'state': 'all'} 487 | if self.args.github_token: 488 | query['access_token'] = g['token'] 489 | 490 | def f(pull): 491 | if self.args.ignore_closed: 492 | return (pull['state'] == 'opened' or 493 | (pull['state'] == 'closed' and pull['merged_at'])) 494 | else: 495 | return True 496 | pulls = filter(f, 497 | self.get(g['url'] + "/repos/" + g['repo'] + "/pulls", 498 | query, self.args.cache)) 499 | return dict([(str(pull['number']), pull) for pull in pulls]) 500 | 501 | def get_merge_requests(self): 502 | "http://doc.gitlab.com/ce/api/merge_requests.html" 503 | g = self.gitlab 504 | merges = self.get(g['url'] + "/projects/" + 505 | g['repo'] + "/merge_requests", 506 | {'private_token': g['token'], 507 | 'state': 'all'}, cache=False) 508 | return dict([(str(merge['id']), merge) for merge in merges]) 509 | 510 | def create_merge_request(self, query): 511 | g = self.gitlab 512 | query['private_token'] = g['token'] 513 | url = g['url'] + "/projects/" + g['repo'] + "/merge_requests" 514 | log.info('create_merge_request: ' + str(query)) 515 | result = requests.post(url, params=query) 516 | if result.status_code != requests.codes.created: 517 | raise ValueError(result.text) 518 | merge = result.json() 519 | log.debug('merge ' + str(merge)) 520 | for (key, value) in six.iteritems(query): 521 | if key == 'private_token': 522 | continue 523 | if value.strip().replace('\n', '').replace('\r', '') != merge.get(key).strip().replace('\n', '').replace('\r', ''): 524 | raise ValueError(url + " " + key + " expected " + 525 | value + " but is " + merge.get(key, 'None')) 526 | return merge 527 | 528 | def update_merge_request(self, merge_request, updates): 529 | state_event = updates.pop('state_event', None) 530 | if len(updates) == 0 or (len(updates) == 1 and 'private_token' in updates): 531 | result = merge_request 532 | else: 533 | result = self.put_merge_request(merge_request, updates) 534 | if (state_event == 'merge' and 535 | result['state'] == 'opened'): 536 | description = result['description'] or '' 537 | updates = { 538 | 'state_event': 'close', 539 | 'description': description + self.TAG_MERGED, 540 | } 541 | result = self.put_merge_request(merge_request, updates) 542 | self.verify_merge_update(updates, result) 543 | return result 544 | 545 | def put_merge_request(self, merge_request, updates): 546 | g = self.gitlab 547 | updates['private_token'] = g['token'] 548 | url = (g['url'] + "/projects/" + g['repo'] + "/merge_requests/" + 549 | str(merge_request['iid'])) 550 | log.info('update_merge_request: ' + url + ' <= ' + str(updates)) 551 | return requests.put(url, params=updates).json() 552 | 553 | def verify_merge_update(self, updates, result): 554 | g = self.gitlab 555 | for (key, value) in six.iteritems(updates): 556 | if key == 'private_token': 557 | continue 558 | if key == 'state_event': 559 | key = 'state' 560 | value = self.STATE_EVENT2MERGE_STATE[updates['state_event']] 561 | result_value = result.get(key) or '' 562 | if value.strip().replace('\r', '') != result_value.strip(): 563 | url = (g['host'] + "/" + parse.unquote(g['repo']) + "/" + 564 | "merge_requests/" + str(result['iid'])) 565 | raise ValueError("{url}: {key} value expected to be {value}" 566 | " but is {result}".format( 567 | url=url, 568 | key=key, 569 | value=value, 570 | result=result_value)) 571 | 572 | # Local Variables: 573 | # compile-command: "cd .. ; virtualenv/bin/tox -e flake8" 574 | # End: 575 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | d2to1 2 | pbr 3 | GitPython 4 | requests 5 | six 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = hub2lab 3 | version = 1.6.0 4 | summary = command line tool to migrate projects from GitHub to GitLab 5 | description-file = 6 | README.rst 7 | author = Pan Luo 8 | author-email = pan.luo@ubc.ca 9 | home-page = https://github.com/ubc/github2gitlab 10 | classifier = 11 | Environment :: No Input/Output (Daemon) 12 | Intended Audience :: Information Technology 13 | Intended Audience :: System Administrators 14 | Operating System :: POSIX :: Linux 15 | License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+) 16 | Programming Language :: Python 17 | Programming Language :: Python :: 2.7 18 | Topic :: Utilities 19 | 20 | [files] 21 | scripts = bin/github2gitlab 22 | 23 | [global] 24 | setup-hooks = 25 | pbr.hooks.setup_hook 26 | 27 | [egg_info] 28 | tag_build = 29 | tag_date = 0 30 | tag_svn_revision = 0 31 | 32 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2015 3 | # 4 | # Author: Loic Dachary 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Affero General Public License as 8 | # published by the Free Software Foundation, either version 3 of the 9 | # License, or (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Affero General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public License 17 | # along with this program. If not, see ``. 18 | # 19 | import setuptools 20 | 21 | setuptools.setup( 22 | setup_requires=['d2to1', 'pbr'], 23 | d2to1=True, 24 | packages=setuptools.find_packages(exclude=['contrib', 'docs', 'tests']), 25 | ) 26 | -------------------------------------------------------------------------------- /test-requirements.txt: -------------------------------------------------------------------------------- 1 | hacking 2 | coverage>=3.6 3 | sphinx>=1.1.2 4 | docutils==0.9.1 5 | discover 6 | fixtures>=0.3.14 7 | python-subunit 8 | testrepository>=0.0.17 9 | mock 10 | pytest 11 | 12 | -------------------------------------------------------------------------------- /tests/integration.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- mode: python; coding: utf-8 -*- 3 | # 4 | # Copyright (C) 2015 5 | # 6 | # Author: Loic Dachary 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Affero General Public License as 10 | # published by the Free Software Foundation, either version 3 of the 11 | # License, or (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Affero General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Affero General Public License 19 | # along with this program. If not, see ``. 20 | # 21 | from github2gitlab import main 22 | import json 23 | import logging 24 | import os 25 | import requests 26 | import shutil 27 | import sys 28 | import tempfile 29 | 30 | log = logging.getLogger('github2gitlab') 31 | 32 | 33 | class Integration(object): 34 | 35 | def __init__(self, argv): 36 | self.g = main.GitHub2GitLab.factory(argv) 37 | self.remove_gitlab() 38 | d = tempfile.mkdtemp() 39 | try: 40 | os.chdir(d) 41 | self.reset_github() 42 | 43 | log.debug("---------- initial sync") 44 | self.create_pull_request() 45 | self.g.run() 46 | self.verify_create_pull_request() 47 | 48 | log.debug("---------- merged pull (not sync'ed when open, " 49 | "sync'ed after it was merged)") 50 | number = self.create_pull_request_and_merge() 51 | self.g.run() 52 | self.verify_create_pull_request_and_merge(number) 53 | 54 | log.debug("---------- closed pull") 55 | self.close_pull_1() 56 | self.rebase_branches() 57 | self.modify_master() 58 | self.g = main.GitHub2GitLab.factory(argv + 59 | ['--branches=master,branch2']) 60 | self.g.run() 61 | self.verify_closed_pull() 62 | 63 | log.debug("---------- deleted branch") 64 | self.add_deleted_branch() 65 | self.g.run() 66 | self.verify_deleted_branch() 67 | 68 | log.debug("---------- merged pull (sync'ed when open, merged, " 69 | "then sync'ed after merge)") 70 | self.merge_pull_4() 71 | self.g.run() 72 | self.verify_merge_pull() 73 | 74 | finally: 75 | shutil.rmtree(d) 76 | 77 | def create_pull_request(self): 78 | g = self.g.github 79 | url = g['url'] + "/repos/" + g['repo'] + "/pulls" 80 | query = {'access_token': g['token']} 81 | for i in (1, 2, 3, 4): 82 | data = { 83 | 'title': u'title branch é {i}'.format(i=i), 84 | 'head': 'branch' + str(i), 85 | 'base': 'master', 86 | 'body': u'body branch ëà {i}'.format(i=i), 87 | } 88 | r = requests.post(url, params=query, data=json.dumps(data)) 89 | if r.status_code != 201: 90 | raise Exception(r.text) 91 | 92 | def rebase_branches(self): 93 | self.g.sh(""" 94 | git fetch origin 95 | git commit -m "rebased branch1" --amend 96 | git push --force origin master:branch1 97 | git checkout branch2 98 | git rebase origin/master 99 | git push --force origin branch2 100 | git checkout master 101 | """) 102 | 103 | def modify_master(self): 104 | self.g.sh(""" 105 | git fetch origin 106 | git reset --hard origin/master 107 | echo "# changed" >> README.md 108 | git commit -m "add to master" README.md 109 | git push origin master 110 | """) 111 | 112 | def verify_create_pull_request(self): 113 | g = self.g.gitlab 114 | merges = self.g.get(g['url'] + "/projects/" + g['repo'] + 115 | "/merge_requests", 116 | {'private_token': g['token'], 117 | 'state': 'open'}, 118 | cache=False) 119 | log.debug("merges " + str(merges)) 120 | assert len(merges) == 4 121 | for merge in merges: 122 | assert 'pull/' in merge['source_branch'] 123 | 124 | def create_pull_request_and_merge(self): 125 | g = self.g.github 126 | url = g['url'] + "/repos/" + g['repo'] + "/pulls" 127 | query = {'access_token': g['token']} 128 | i = 6 129 | data = { 130 | 'title': u'title branch é {i}'.format(i=i), 131 | 'head': 'branch' + str(i), 132 | 'base': 'master', 133 | 'body': u'body branch ëà {i}'.format(i=i), 134 | } 135 | r = requests.post(url, params=query, data=json.dumps(data)) 136 | if r.status_code != 201: 137 | raise Exception(r.text) 138 | pull = r.json() 139 | number = str(pull['number']) 140 | url = g['url'] + "/repos/" + g['repo'] + "/pulls/" + number + "/merge" 141 | data = {'commit_message': 'COMMIT MESSAGE'} 142 | r = requests.put(url, params=query, data=json.dumps(data)) 143 | log.debug("merge output for PR " + str(number) + ": " + r.text) 144 | r.raise_for_status() 145 | return number 146 | 147 | def verify_create_pull_request_and_merge(self, number): 148 | g = self.g.gitlab 149 | merges = self.g.get(g['url'] + "/projects/" + g['repo'] + 150 | "/merge_requests", 151 | {'private_token': g['token'], 152 | 'state': 'open'}, 153 | cache=False) 154 | log.debug("merges " + str(merges)) 155 | merge = filter(lambda merge: (merge['source_branch'] == 'pull/' + 156 | number + '/head'), 157 | merges) 158 | log.debug("merge " + str(merge)) 159 | assert 'closed' == merge[0]['state'] 160 | assert main.GitHub2GitLab.TAG_MERGED in merge[0]['description'] 161 | 162 | def close_pull_1(self): 163 | g = self.g.github 164 | url = g['url'] + "/repos/" + g['repo'] + "/pulls/1" 165 | query = {'access_token': g['token']} 166 | data = {'state': 'closed'} 167 | requests.patch(url, params=query, data=json.dumps(data)) 168 | 169 | def verify_closed_pull(self): 170 | g = self.g.gitlab 171 | merges = self.g.get(g['url'] + "/projects/" + g['repo'] + 172 | "/merge_requests", 173 | {'private_token': g['token'], 174 | 'state': 'all'}, 175 | cache=False) 176 | log.debug("merges " + str(merges)) 177 | assert len(merges) == 5 178 | for merge in merges: 179 | log.debug("source_branch " + merge['source_branch'] + 180 | " state " + merge['state']) 181 | if merge['source_branch'] in ('pull/1/head', 'pull/5/head'): 182 | assert merge['state'] == 'closed' 183 | else: 184 | assert merge['state'] == 'opened' 185 | 186 | def add_deleted_branch(self): 187 | g = self.g.github 188 | url = g['url'] + "/repos/" + g['repo'] + "/pulls" 189 | query = {'access_token': g['token']} 190 | data = { 191 | 'title': u'title branch 5 on 3', 192 | 'head': 'branch5', 193 | 'base': 'branch3', 194 | 'body': u'body branch ', 195 | } 196 | r = requests.post(url, params=query, data=json.dumps(data)) 197 | if r.status_code != 201: 198 | raise Exception(r.text) 199 | self.g.sh("git push origin --delete branch3") 200 | self.g.sh("cd " + self.g.gitlab['name'] + " ; git branch -D branch3") 201 | 202 | def verify_deleted_branch(self): 203 | g = self.g.gitlab 204 | merges = self.g.get(g['url'] + "/projects/" + g['repo'] + 205 | "/merge_requests", 206 | {'private_token': g['token'], 207 | 'state': 'all'}, 208 | cache=False) 209 | log.debug("merges " + str(merges)) 210 | assert len(merges) == 5 211 | 212 | def merge_pull_4(self): 213 | g = self.g.github 214 | url = g['url'] + "/repos/" + g['repo'] + "/pulls/4/merge" 215 | query = {'access_token': g['token']} 216 | data = {'commit_message': 'COMMIT MESSAGE'} 217 | r = requests.put(url, params=query, data=json.dumps(data)) 218 | log.debug("merge output " + r.text) 219 | r.raise_for_status() 220 | 221 | def verify_merge_pull(self): 222 | g = self.g.gitlab 223 | merges = self.g.get(g['url'] + "/projects/" + g['repo'] + 224 | "/merge_requests", 225 | {'private_token': g['token'], 226 | 'state': 'all'}, 227 | cache=False) 228 | log.debug("merges " + str(merges)) 229 | assert len(merges) == 5 230 | for merge in merges: 231 | if merge['source_branch'] in ('pull/1/head', 232 | 'pull/3/head', 233 | 'pull/5/head'): 234 | assert merge['state'] == 'closed' 235 | elif merge['source_branch'] == 'pull/4/head': 236 | assert merge['state'] == 'merged' 237 | else: 238 | assert merge['state'] == 'opened' 239 | 240 | def remove_gitlab(self): 241 | g = self.g.gitlab 242 | url = g['url'] + "/projects/" + g['repo'] 243 | query = {'private_token': g['token']} 244 | assert requests.delete(url, params=query).status_code in (200, 404) 245 | 246 | def reset_github(self): 247 | g = self.g.github 248 | url = g['url'] + "/repos/" + g['repo'] 249 | query = {'access_token': g['token']} 250 | assert requests.delete(url, params=query).status_code in (204, 404) 251 | url = g['url'] + "/user/repos" 252 | data = {'name': g['repo'].split('/')[1]} 253 | requests.post(url, 254 | params=query, 255 | data=json.dumps(data)).raise_for_status() 256 | self.g.sh(""" 257 | echo "# testrepo" >> README.md 258 | git init 259 | git add README.md 260 | git commit -m "first commit" 261 | git remote add origin git@github.com:{repo}.git 262 | git push -u origin master 263 | for i in $(seq 1 6) ; do 264 | touch file$i.txt 265 | git add file$i.txt 266 | git commit -m "commit $i" 267 | git push origin master:branch$i 268 | git reset --hard origin/master 269 | done 270 | """.format(repo=g['repo'])) 271 | 272 | Integration(sys.argv[1:]) 273 | -------------------------------------------------------------------------------- /tests/setup-gitlab.sh: -------------------------------------------------------------------------------- 1 | set -ex 2 | DATA=$(pwd)/data 3 | for i in test-gitlab test-mysql test-redis ; do sudo docker stop $i || true ; sudo docker rm $i || true ; done 4 | mkdir -p $DATA 5 | sudo docker run --name=test-redis -d sameersbn/redis:latest 6 | sudo rm -fr $DATA/mysql 7 | mkdir -p $DATA/mysql 8 | sudo docker run --name=test-mysql -d -e 'DB_NAME=gitlabhq_production' -e 'DB_USER=gitlab' -e 'DB_PASS=Wrobyak4' -v $DATA/mysql/data:/var/lib/mysql sameersbn/mysql:latest 9 | sudo rm -fr $DATA/gitlab 10 | mkdir -p $DATA/gitlab 11 | sudo docker run --name='test-gitlab' -it -d --link test-mysql:mysql --link test-redis:redisio -e 'GITLAB_SIGNUP=true' -e 'GITLAB_PORT=80' -e 'GITLAB_HOST=localhost' -e 'GITLAB_SSH_PORT=2222' -p 2222:22 -p 8181:80 -e GITLAB_SECRETS_DB_KEY_BASE=4W44tm7bJFRPWNMVzKngffxVWXRpVs49dxhFwgpx7FbCj3wXCMmsz47LzWsdr7nM -v /var/run/docker.sock:/run/docker.sock -v $DATA/gitlab/data:/home/git/data -v $(which docker):/bin/docker sameersbn/gitlab 12 | sleep 60 13 | -------------------------------------------------------------------------------- /tests/test_github2gitlab.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python; coding: utf-8 -*- 2 | # 3 | # Copyright (C) 2015 4 | # 5 | # Author: Loic Dachary 6 | # 7 | # This program is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU Affero General Public License as 9 | # published by the Free Software Foundation, either version 3 of the 10 | # License, or (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU Affero General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU Affero General Public License 18 | # along with this program. If not, see ``. 19 | # 20 | import git 21 | import gitdb 22 | import logging 23 | import mock 24 | import os 25 | import pytest 26 | import shutil 27 | import tempfile 28 | 29 | from github2gitlab import main 30 | 31 | logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', 32 | level=logging.DEBUG) 33 | 34 | 35 | class TestGitHub2GitLab(object): 36 | 37 | def setup(self): 38 | self.gitlab_url = 'http://gitlab' 39 | self.gitlab_token = 'token' 40 | self.github_repo = 'user/repo' 41 | self.g = main.GitHub2GitLab.factory([ 42 | '--verbose', 43 | '--gitlab-url', self.gitlab_url, 44 | '--gitlab-token', self.gitlab_token, 45 | '--github-repo', self.github_repo, 46 | ]) 47 | self.d = tempfile.mkdtemp() 48 | 49 | def teardown(self): 50 | shutil.rmtree(self.d) 51 | 52 | def test_init(self): 53 | with pytest.raises(SystemExit): 54 | main.GitHub2GitLab.factory([]) 55 | assert os.environ['HOME'] in self.g.args.ssh_public_key 56 | assert self.github_repo == self.g.github['repo'] 57 | assert self.gitlab_url in self.g.gitlab['url'] 58 | 59 | @mock.patch('requests.get') 60 | def test_get(self, m_requests_get): 61 | g = self.g 62 | 63 | class Request(object): 64 | def __init__(self, params): 65 | if params.get('page') == '1': 66 | self.payload = [1] 67 | self.headers = {} 68 | else: 69 | self.payload = [0] 70 | self.headers = { 71 | "Link": ("<" + g.gitlab['url'] + 72 | '?page=1> rel="next"'), 73 | } 74 | 75 | def json(self): 76 | return self.payload 77 | 78 | m_requests_get.side_effect = lambda url, params: Request(params) 79 | result = self.g.get(self.g.gitlab['url'], {'key': 'value'}, 80 | cache=False) 81 | assert m_requests_get.called 82 | assert [0, 1] == result 83 | other_result = self.g.get(self.g.gitlab['url'], {'key': 'value'}, 84 | cache=False) 85 | assert result == other_result 86 | 87 | @mock.patch('requests.get') 88 | def test_get_pull_requests(self, m_requests_get): 89 | number1 = 1 90 | number2 = 2 91 | 92 | class Request(object): 93 | def __init__(self): 94 | self.headers = {} 95 | 96 | def json(self): 97 | return [{"number": number1}, 98 | {"number": number2}] 99 | 100 | m_requests_get.side_effect = lambda url, params: Request() 101 | result = self.g.get_pull_requests() 102 | assert { 103 | str(number1): {u'number': number1}, 104 | str(number2): {u'number': number2}, 105 | } == result 106 | 107 | @mock.patch('requests.get') 108 | def test_get_merge_requests(self, m_requests_get): 109 | id1 = 100 110 | id2 = 200 111 | 112 | class Request(object): 113 | def __init__(self): 114 | self.headers = {} 115 | 116 | def json(self): 117 | return [{"id": id1}, 118 | {"id": id2}] 119 | 120 | m_requests_get.side_effect = lambda url, params: Request() 121 | result = self.g.get_merge_requests() 122 | assert { 123 | str(id1): {u'id': id1}, 124 | str(id2): {u'id': id2}, 125 | } == result 126 | 127 | @mock.patch('requests.put') 128 | @mock.patch('requests.get') 129 | def test_unprotect_branches(self, 130 | m_requests_get, 131 | m_requests_put): 132 | class Get(object): 133 | def raise_for_status(self): 134 | pass 135 | 136 | def json(self): 137 | return [ 138 | { 139 | 'name': 'master', 140 | 'protected': True, 141 | }, 142 | { 143 | 'name': 'branch1', 144 | 'protected': False, 145 | }, 146 | ] 147 | m_requests_get.side_effect = lambda url, params: Get() 148 | 149 | class Put(object): 150 | def raise_for_status(self): 151 | pass 152 | m_requests_put.side_effect = lambda url, params: Put() 153 | assert 1 == self.g.unprotect_branches() 154 | assert m_requests_get.called 155 | assert m_requests_put.called 156 | 157 | def test_update_merge_pull(self): 158 | id1 = '100' 159 | id2 = '200' 160 | number1 = '1' 161 | number2 = '2' 162 | self.g.pull_requests = { 163 | number1: {u'number': int(number1)}, 164 | number2: {u'number': int(number2)}, 165 | } 166 | self.g.merge_requests = { 167 | id1: { 168 | u'id': int(id1), 169 | u'source_branch': 'pull/' + number1 + '/head', 170 | }, 171 | id2: { 172 | u'id': int(id2), 173 | u'source_branch': 'UNEXPECTED', 174 | }, 175 | } 176 | self.g.update_merge_pull() 177 | assert self.g.merge2pull == {'100': {u'number': 1}} 178 | assert (self.g.pull2merge == 179 | {'1': {u'id': 100, u'source_branch': 'pull/1/head'}}) 180 | 181 | @mock.patch('requests.post') 182 | def test_create_merge_request(self, m_requests_post): 183 | data = {'title': u'TITLE é'} 184 | 185 | class Request(object): 186 | def __init__(self): 187 | self.status_code = 201 188 | 189 | def json(self): 190 | return data 191 | 192 | m_requests_post.side_effect = lambda url, params: Request() 193 | self.g.create_merge_request(data) 194 | assert m_requests_post.called 195 | 196 | @mock.patch('requests.post') 197 | def test_create_merge_request_fail(self, m_requests_post): 198 | data = {'title': u'TITLE é'} 199 | 200 | class Request(object): 201 | def __init__(self): 202 | self.status_code = 400 203 | self.text = 'FAIL' 204 | 205 | m_requests_post.side_effect = lambda *args, **kwargs: Request() 206 | with pytest.raises(ValueError): 207 | self.g.create_merge_request(data) 208 | assert m_requests_post.called 209 | 210 | @mock.patch('requests.put') 211 | def test_update_merge_request(self, m_requests_put): 212 | data = { 213 | 'title': u'TITLE é', 214 | 'state_event': 'close', 215 | } 216 | 217 | class Request(object): 218 | def json(self): 219 | data['state'] = 'closed' 220 | return data 221 | 222 | m_requests_put.side_effect = lambda url, params: Request() 223 | merge_request = {'id': 3} 224 | self.g.update_merge_request(merge_request, data) 225 | assert m_requests_put.called 226 | 227 | @mock.patch('requests.put') 228 | def test_update_merge_request_fail_state(self, m_requests_put): 229 | data = {'state_event': 'close'} 230 | 231 | class Request(object): 232 | def json(self): 233 | return { 234 | 'state': 'UNEXPECTED', 235 | 'iid': 1, 236 | 'merged': False, 237 | } 238 | 239 | m_requests_put.side_effect = lambda url, params: Request() 240 | merge_request = {'id': 3} 241 | with pytest.raises(ValueError) as e: 242 | self.g.update_merge_request(merge_request, data) 243 | assert 'UNEXPECTED' in str(e) 244 | assert m_requests_put.called 245 | 246 | @mock.patch('github2gitlab.main.GitHub2GitLab.put_merge_request') 247 | @mock.patch('github2gitlab.main.GitHub2GitLab.verify_merge_update') 248 | def test_update_merge_request_merge(self, 249 | m_verify_merge_update, 250 | m_put_merge_request): 251 | description = 'DESCRIPTION' 252 | 253 | def put(merge_request, updates): 254 | if updates['state_event'] == 'merge': 255 | updates['state'] = 'opened' 256 | updates['description'] = description 257 | else: 258 | updates['state'] = 'closed' 259 | return updates 260 | 261 | m_put_merge_request.side_effect = put 262 | merge_request = {'id': 3} 263 | result = self.g.update_merge_request(merge_request, 264 | {'state_event': 'merge'}) 265 | assert self.g.TAG_MERGED in result['description'] 266 | assert m_verify_merge_update.called 267 | 268 | @mock.patch('requests.get') 269 | @mock.patch('requests.post') 270 | def test_add_project_create(self, 271 | m_requests_post, 272 | m_requests_get): 273 | class Get(object): 274 | 275 | def __init__(self): 276 | self.status_code = 404 277 | m_requests_get.side_effect = lambda url, params: Get() 278 | 279 | class Post(object): 280 | def __init__(self): 281 | self.status_code = 201 282 | self.text = 'true' 283 | 284 | def json(self): 285 | return {} 286 | m_requests_post.side_effect = lambda url, params: Post() 287 | assert {} == self.g.add_project() 288 | assert m_requests_get.called 289 | assert m_requests_post.called 290 | 291 | @mock.patch('requests.get') 292 | @mock.patch('requests.post') 293 | def test_add_project_create_400(self, 294 | m_requests_post, 295 | m_requests_get): 296 | class Get(object): 297 | 298 | def __init__(self): 299 | self.status_code = 404 300 | m_requests_get.side_effect = lambda url, params: Get() 301 | error_message = 'ERROR MESSAGE' 302 | 303 | class Post(object): 304 | def __init__(self): 305 | self.status_code = 400 306 | self.text = error_message 307 | m_requests_post.side_effect = lambda url, params: Post() 308 | with pytest.raises(ValueError) as e: 309 | self.g.add_project() 310 | assert error_message in str(e) 311 | assert m_requests_get.called 312 | assert m_requests_post.called 313 | 314 | @mock.patch('requests.get') 315 | def test_add_project_noop(self, m_requests_get): 316 | class Get(object): 317 | def __init__(self): 318 | self.status_code = 200 319 | m_requests_get.side_effect = lambda url, params: Get() 320 | assert None == self.g.add_project() 321 | assert m_requests_get.called 322 | 323 | @mock.patch('requests.get') 324 | @mock.patch('requests.post') 325 | def test_add_key_create(self, 326 | m_requests_post, 327 | m_requests_get): 328 | public_key = 'PUBLIC KEY' 329 | ssh_public_key = self.d + "/key.pub" 330 | with open(ssh_public_key, 'w') as f: 331 | f.write(public_key) 332 | self.g.args.ssh_public_key = ssh_public_key 333 | 334 | class Get(object): 335 | def json(self): 336 | return [] 337 | m_requests_get.side_effect = lambda url, params: Get() 338 | 339 | class Post(object): 340 | def __init__(self): 341 | self.status_code = 201 342 | m_requests_post.side_effect = lambda url, params: Post() 343 | assert public_key == self.g.add_key() 344 | assert m_requests_get.called 345 | assert m_requests_post.called 346 | 347 | @mock.patch('requests.get') 348 | @mock.patch('requests.post') 349 | def test_add_key_create_400(self, 350 | m_requests_post, 351 | m_requests_get): 352 | public_key = 'PUBLIC KEY' 353 | ssh_public_key = self.d + "/key.pub" 354 | with open(ssh_public_key, 'w') as f: 355 | f.write(public_key) 356 | self.g.args.ssh_public_key = ssh_public_key 357 | 358 | class Get(object): 359 | def json(self): 360 | return [] 361 | m_requests_get.side_effect = lambda url, params: Get() 362 | error_message = 'ERROR MESSAGE' 363 | 364 | class Post(object): 365 | def __init__(self): 366 | self.status_code = 400 367 | self.text = error_message 368 | m_requests_post.side_effect = lambda url, params: Post() 369 | with pytest.raises(ValueError) as e: 370 | self.g.add_key() 371 | assert error_message in str(e) 372 | assert m_requests_get.called 373 | assert m_requests_post.called 374 | 375 | @mock.patch('requests.get') 376 | def test_add_key_noop(self, m_requests_get): 377 | public_key = 'PUBLIC KEY' 378 | ssh_public_key = self.d + "/key.pub" 379 | with open(ssh_public_key, 'w') as f: 380 | f.write(public_key) 381 | self.g.args.ssh_public_key = ssh_public_key 382 | 383 | class Get(object): 384 | def json(self): 385 | return [{'key': public_key}] 386 | m_requests_get.side_effect = lambda url, params: Get() 387 | assert None == self.g.add_key() 388 | assert m_requests_get.called 389 | 390 | @mock.patch('github2gitlab.main.GitHub2GitLab.update_merge_request') 391 | @mock.patch('github2gitlab.main.GitHub2GitLab.create_merge_request') 392 | @mock.patch('github2gitlab.main.GitHub2GitLab.rev_parse') 393 | def test_sync(self, 394 | m_rev_parse, 395 | m_create_merge_request, 396 | m_update_merge_request): 397 | m_rev_parse.side_effect = lambda pull, revision: True 398 | self.g.pull_requests = { 399 | '1': { 400 | 'number': 1, 401 | 'state': 'open', 402 | 'title': u'TITLE é', 403 | 'body': 'DESCRIPTION è', 404 | 'base': { 405 | 'ref': 'master', 406 | }, 407 | 'merged_at': None, 408 | }, 409 | '2': { 410 | 'number': 2, 411 | 'state': 'closed', 412 | 'title': 'OTHER_TITLE', 413 | 'body': 'DESCRIPTION è', 414 | 'merged_at': 'today', 415 | }, 416 | } 417 | self.g.merge_requests = { 418 | '100': { 419 | 'id': 100, 420 | 'state': 'opened', 421 | 'title': u'TITLE é', 422 | 'description': 'DESCRIPTION è', 423 | 'source_branch': 'pull/2/head', 424 | 'target_branch': 'master', 425 | } 426 | } 427 | self.g.update_merge_pull() 428 | assert 1 == len(self.g.merge2pull) 429 | assert 2 == self.g.merge2pull['100']['number'] 430 | assert 100 == self.g.pull2merge['2']['id'] 431 | 432 | self.g.sync() 433 | m_update_merge_request.assert_called_with( 434 | self.g.merge_requests['100'], 435 | { 436 | 'title': 'OTHER_TITLE', 437 | 'state_event': 'merge', 438 | }) 439 | pull = self.g.pull_requests['1'] 440 | m_create_merge_request.assert_called_with({ 441 | 'title': pull['title'], 442 | 'description': pull['body'], 443 | 'target_branch': pull['base']['ref'], 444 | 'source_branch': 'pull/' + str(pull['number']) + '/head', 445 | }) 446 | 447 | @mock.patch('github2gitlab.main.GitHub2GitLab.gitlab_create_remote') 448 | def test_gitmirror(self, m_gitlab_create_remote): 449 | self.g.args.skip_pull_requests = True 450 | 451 | self.g.sh(""" 452 | cd {dir} 453 | mkdir github 454 | cd github 455 | git init 456 | echo a > a ; git add a ; git commit -m "a" a 457 | """.format(dir=self.d)) 458 | 459 | self.g.sh(""" 460 | cd {dir} 461 | mkdir gitlab 462 | cd gitlab 463 | git init --bare 464 | """.format(dir=self.d)) 465 | 466 | def gitlab_create_remote(repo): 467 | repo.create_remote('gitlab', self.d + "/gitlab") 468 | m_gitlab_create_remote.side_effect = gitlab_create_remote 469 | 470 | self.g.github['git'] = self.d 471 | self.g.github['repo'] = 'github' 472 | self.g.gitlab['name'] = 'project' 473 | 474 | cwd = os.getcwd() 475 | os.chdir(self.d) 476 | gitlab = git.Repo(self.d + '/gitlab') 477 | github = git.Repo(self.d + '/github') 478 | 479 | # 480 | # A pull request newly created only has pull/1/head 481 | # and will not be pushed to gitlab. 482 | # 483 | self.g.sh(""" 484 | cd {dir}/github 485 | git branch pr-1 486 | git checkout pr-1 487 | echo 1 > 1 ; git add 1 ; git commit -m "1" 1 488 | git update-ref refs/pull/1/head HEAD 489 | git checkout master 490 | """.format(dir=self.d)) 491 | 492 | self.g.git_mirror() 493 | 494 | with pytest.raises(gitdb.exc.BadName): 495 | gitlab.commit('pull/1/merge') 496 | 497 | # 498 | # After github successfully test a merge of a pull 499 | # request, the pull/1/merge reference exists and 500 | # it is pushed to gitlab 501 | # 502 | self.g.sh(""" 503 | cd {dir}/github 504 | git branch pr-1-merge master 505 | git checkout pr-1-merge 506 | git merge --no-ff pr-1 507 | git update-ref refs/pull/1/merge HEAD 508 | git checkout master 509 | """.format(dir=self.d)) 510 | 511 | self.g.git_mirror() 512 | assert gitlab.commit('pull/1/merge') == github.commit('pull/1/merge') 513 | 514 | # 515 | # When the base (master in this case) changes, github 516 | # may decide to re-try a merge. We ignore that because we're 517 | # only interested in pushing to gitlab when the head changes, 518 | # not every time the base changes and a merge is attempted. 519 | # 520 | self.g.sh(""" 521 | cd {dir}/github 522 | git checkout master 523 | echo b > b ; git add b ; git commit -m "b" b 524 | git checkout pr-1-merge 525 | git reset --hard master 526 | git merge --no-ff pr-1 527 | git update-ref refs/pull/1/merge HEAD 528 | git checkout master 529 | """.format(dir=self.d)) 530 | 531 | self.g.git_mirror() 532 | assert gitlab.commit('pull/1/merge') != github.commit('pull/1/merge') 533 | 534 | # 535 | # After a rebase and repush, pull/2/merge may reference the 536 | # previous pull/2/head and there is no point in pushing 537 | # it to gitlab: it would show an outdated state of the 538 | # pull request 539 | # 540 | self.g.sh(""" 541 | cd {dir}/github 542 | # new pr 543 | git branch pr-2 544 | git checkout pr-2 545 | echo 2 > 2 ; git add 2 ; git commit -m "2" 2 546 | git update-ref refs/pull/2/head HEAD 547 | git checkout master 548 | # merge test 549 | git branch pr-2-merge master 550 | git checkout pr-2-merge 551 | git merge --no-ff pr-2 552 | git update-ref refs/pull/2/merge HEAD 553 | git checkout master 554 | # repush the pr 555 | git checkout pr-2 556 | echo 2.5 > 2.5 ; git add 2.5 ; git commit -m "2.5" 2.5 557 | git update-ref refs/pull/2/head HEAD 558 | git checkout master 559 | """.format(dir=self.d)) 560 | 561 | self.g.git_mirror() 562 | with pytest.raises(gitdb.exc.BadName): 563 | gitlab.commit('pull/2/merge') 564 | 565 | # 566 | # After a rebase and repush, pull/3/merge is updated 567 | # if the merge check is successful. 568 | # 569 | self.g.sh(""" 570 | cd {dir}/github 571 | # new pr 572 | git branch pr-3 573 | git checkout pr-3 574 | echo 3 > 3 ; git add 3 ; git commit -m "3" 3 575 | git update-ref refs/pull/3/head HEAD 576 | git checkout master 577 | # merge test 578 | git branch pr-3-merge master 579 | git checkout pr-3-merge 580 | git merge --no-ff pr-3 581 | git update-ref refs/pull/3/merge HEAD 582 | git checkout master 583 | """.format(dir=self.d)) 584 | 585 | self.g.git_mirror() 586 | merge_1 = gitlab.commit('pull/3/merge') 587 | assert merge_1 == github.commit('pull/3/merge') 588 | 589 | self.g.sh(""" 590 | cd {dir}/github 591 | # repush the pr 592 | git checkout pr-3 593 | echo 3.5 > 3.5 ; git add 3.5 ; git commit -m "3.5" 3.5 594 | git update-ref refs/pull/3/head HEAD 595 | git checkout master 596 | # re-verify merge 597 | git checkout pr-3-merge 598 | git reset --hard master 599 | git merge --no-ff pr-3 600 | git update-ref refs/pull/3/merge HEAD 601 | git checkout master 602 | """.format(dir=self.d)) 603 | 604 | self.g.git_mirror() 605 | merge_2 = gitlab.commit('pull/3/merge') 606 | assert merge_1 != merge_2 607 | assert merge_2 == github.commit('pull/3/merge') 608 | 609 | # 610 | # All branches are pushed to gitlab by default 611 | # 612 | self.g.sh(""" 613 | cd {dir}/github 614 | git branch b master 615 | git checkout b 616 | echo b > b ; git add b ; git commit -m "b" b 617 | git branch c master 618 | git checkout c 619 | echo c > c ; git add c ; git commit -m "c" c 620 | """.format(dir=self.d)) 621 | 622 | self.g.git_mirror() 623 | assert gitlab.commit('b') == github.commit('b') 624 | assert gitlab.commit('c') == github.commit('c') 625 | 626 | # 627 | # If branches are given in argument, only those 628 | # are pushed to gitlab 629 | # 630 | self.g.sh(""" 631 | cd {dir}/github 632 | git branch d master 633 | git checkout d 634 | echo d > d ; git add d ; git commit -m "d" d 635 | git branch e master 636 | git checkout e 637 | echo e > e ; git add e ; git commit -m "e" e 638 | git branch f master 639 | git checkout f 640 | echo f > f ; git add f ; git commit -m "f" f 641 | """.format(dir=self.d)) 642 | 643 | self.g.github['branches'] = ['e', 'f'] 644 | self.g.git_mirror() 645 | with pytest.raises(gitdb.exc.BadName): 646 | gitlab.commit('d') 647 | assert gitlab.commit('e') == github.commit('e') 648 | assert gitlab.commit('f') == github.commit('f') 649 | 650 | os.chdir(cwd) 651 | 652 | 653 | class TestGitHub2GitLabNoSetup(object): 654 | 655 | def test_json_loads(self): 656 | r = main.GitHub2GitLab.json_loads('{}') 657 | assert {} == r 658 | with pytest.raises(ValueError): 659 | main.GitHub2GitLab.json_loads(']') 660 | 661 | # Local Variables: 662 | # compile-command: "../.tox/py27/bin/py.test test_github2gitlab.py" 663 | # End: 664 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = flake8,py27,py33 3 | 4 | [testenv] 5 | setenv = VIRTUAL_ENV={envdir} 6 | passenv = HOME 7 | usedevelop = true 8 | deps = -r{toxinidir}/requirements.txt 9 | -r{toxinidir}/test-requirements.txt 10 | 11 | commands = coverage run --source=github2gitlab {envbindir}/py.test -v {posargs:tests} 12 | coverage report --omit=*test*,*tox* --show-missing --fail-under=75 13 | 14 | [testenv:flake8] 15 | commands = flake8 --ignore=H105,H405 bin github2gitlab tests 16 | --------------------------------------------------------------------------------