Federated via graft
0

Configure Feed

Select the types of activity you want to include in your feed.

Initial commit: Forgejo <-> Radicle sync daemon

author
jeanbaptiste
date (Sep 12, 2026, 5:03 PM +0200) commit 2a0867f9
+2191
+2
.gitignore
··· 1 + /graft 2 + *.db
+674
LICENSE
··· 1 + GNU GENERAL PUBLIC LICENSE 2 + Version 3, 29 June 2007 3 + 4 + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> 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 General Public License is a free, copyleft license for 11 + software and other kinds of works. 12 + 13 + The licenses for most software and other practical works are designed 14 + to take away your freedom to share and change the works. By contrast, 15 + the GNU General Public License is intended to guarantee your freedom to 16 + share and change all versions of a program--to make sure it remains free 17 + software for all its users. We, the Free Software Foundation, use the 18 + GNU General Public License for most of our software; it applies also to 19 + any other work released this way by its authors. You can apply it to 20 + your programs, too. 21 + 22 + When we speak of free software, we are referring to freedom, not 23 + price. Our General Public Licenses are designed to make sure that you 24 + have the freedom to distribute copies of free software (and charge for 25 + them if you wish), that you receive source code or can get it if you 26 + want it, that you can change the software or use pieces of it in new 27 + free programs, and that you know you can do these things. 28 + 29 + To protect your rights, we need to prevent others from denying you 30 + these rights or asking you to surrender the rights. Therefore, you have 31 + certain responsibilities if you distribute copies of the software, or if 32 + you modify it: responsibilities to respect the freedom of others. 33 + 34 + For example, if you distribute copies of such a program, whether 35 + gratis or for a fee, you must pass on to the recipients the same 36 + freedoms that you received. You must make sure that they, too, receive 37 + or can get the source code. And you must show them these terms so they 38 + know their rights. 39 + 40 + Developers that use the GNU GPL protect your rights with two steps: 41 + (1) assert copyright on the software, and (2) offer you this License 42 + giving you legal permission to copy, distribute and/or modify it. 43 + 44 + For the developers' and authors' protection, the GPL clearly explains 45 + that there is no warranty for this free software. For both users' and 46 + authors' sake, the GPL requires that modified versions be marked as 47 + changed, so that their problems will not be attributed erroneously to 48 + authors of previous versions. 49 + 50 + Some devices are designed to deny users access to install or run 51 + modified versions of the software inside them, although the manufacturer 52 + can do so. This is fundamentally incompatible with the aim of 53 + protecting users' freedom to change the software. The systematic 54 + pattern of such abuse occurs in the area of products for individuals to 55 + use, which is precisely where it is most unacceptable. Therefore, we 56 + have designed this version of the GPL to prohibit the practice for those 57 + products. If such problems arise substantially in other domains, we 58 + stand ready to extend this provision to those domains in future versions 59 + of the GPL, as needed to protect the freedom of users. 60 + 61 + Finally, every program is threatened constantly by software patents. 62 + States should not allow patents to restrict development and use of 63 + software on general-purpose computers, but in those that do, we wish to 64 + avoid the special danger that patents applied to a free program could 65 + make it effectively proprietary. To prevent this, the GPL assures that 66 + patents cannot be used to render the program non-free. 67 + 68 + The precise terms and conditions for copying, distribution and 69 + modification follow. 70 + 71 + TERMS AND CONDITIONS 72 + 73 + 0. Definitions. 74 + 75 + "This License" refers to version 3 of the GNU General Public License. 76 + 77 + "Copyright" also means copyright-like laws that apply to other kinds of 78 + works, such as semiconductor masks. 79 + 80 + "The Program" refers to any copyrightable work licensed under this 81 + License. Each licensee is addressed as "you". "Licensees" and 82 + "recipients" may be individuals or organizations. 83 + 84 + To "modify" a work means to copy from or adapt all or part of the work 85 + in a fashion requiring copyright permission, other than the making of an 86 + exact copy. The resulting work is called a "modified version" of the 87 + earlier work or a work "based on" the earlier work. 88 + 89 + A "covered work" means either the unmodified Program or a work based 90 + on the Program. 91 + 92 + To "propagate" a work means to do anything with it that, without 93 + permission, would make you directly or secondarily liable for 94 + infringement under applicable copyright law, except executing it on a 95 + computer or modifying a private copy. Propagation includes copying, 96 + distribution (with or without modification), making available to the 97 + public, and in some countries other activities as well. 98 + 99 + To "convey" a work means any kind of propagation that enables other 100 + parties to make or receive copies. Mere interaction with a user through 101 + a computer network, with no transfer of a copy, is not conveying. 102 + 103 + An interactive user interface displays "Appropriate Legal Notices" 104 + to the extent that it includes a convenient and prominently visible 105 + feature that (1) displays an appropriate copyright notice, and (2) 106 + tells the user that there is no warranty for the work (except to the 107 + extent that warranties are provided), that licensees may convey the 108 + work under this License, and how to view a copy of this License. If 109 + the interface presents a list of user commands or options, such as a 110 + menu, a prominent item in the list meets this criterion. 111 + 112 + 1. Source Code. 113 + 114 + The "source code" for a work means the preferred form of the work 115 + for making modifications to it. "Object code" means any non-source 116 + form of a work. 117 + 118 + A "Standard Interface" means an interface that either is an official 119 + standard defined by a recognized standards body, or, in the case of 120 + interfaces specified for a particular programming language, one that 121 + is widely used among developers working in that language. 122 + 123 + The "System Libraries" of an executable work include anything, other 124 + than the work as a whole, that (a) is included in the normal form of 125 + packaging a Major Component, but which is not part of that Major 126 + Component, and (b) serves only to enable use of the work with that 127 + Major Component, or to implement a Standard Interface for which an 128 + implementation is available to the public in source code form. A 129 + "Major Component", in this context, means a major essential component 130 + (kernel, window system, and so on) of the specific operating system 131 + (if any) on which the executable work runs, or a compiler used to 132 + produce the work, or an object code interpreter used to run it. 133 + 134 + The "Corresponding Source" for a work in object code form means all 135 + the source code needed to generate, install, and (for an executable 136 + work) run the object code and to modify the work, including scripts to 137 + control those activities. However, it does not include the work's 138 + System Libraries, or general-purpose tools or generally available free 139 + programs which are used unmodified in performing those activities but 140 + which are not part of the work. For example, Corresponding Source 141 + includes interface definition files associated with source files for 142 + the work, and the source code for shared libraries and dynamically 143 + linked subprograms that the work is specifically designed to require, 144 + such as by intimate data communication or control flow between those 145 + subprograms and other parts of the work. 146 + 147 + The Corresponding Source need not include anything that users 148 + can regenerate automatically from other parts of the Corresponding 149 + Source. 150 + 151 + The Corresponding Source for a work in source code form is that 152 + same work. 153 + 154 + 2. Basic Permissions. 155 + 156 + All rights granted under this License are granted for the term of 157 + copyright on the Program, and are irrevocable provided the stated 158 + conditions are met. This License explicitly affirms your unlimited 159 + permission to run the unmodified Program. The output from running a 160 + covered work is covered by this License only if the output, given its 161 + content, constitutes a covered work. This License acknowledges your 162 + rights of fair use or other equivalent, as provided by copyright law. 163 + 164 + You may make, run and propagate covered works that you do not 165 + convey, without conditions so long as your license otherwise remains 166 + in force. You may convey covered works to others for the sole purpose 167 + of having them make modifications exclusively for you, or provide you 168 + with facilities for running those works, provided that you comply with 169 + the terms of this License in conveying all material for which you do 170 + not control copyright. Those thus making or running the covered works 171 + for you must do so exclusively on your behalf, under your direction 172 + and control, on terms that prohibit them from making any copies of 173 + your copyrighted material outside their relationship with you. 174 + 175 + Conveying under any other circumstances is permitted solely under 176 + the conditions stated below. Sublicensing is not allowed; section 10 177 + makes it unnecessary. 178 + 179 + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 + 181 + No covered work shall be deemed part of an effective technological 182 + measure under any applicable law fulfilling obligations under article 183 + 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 + similar laws prohibiting or restricting circumvention of such 185 + measures. 186 + 187 + When you convey a covered work, you waive any legal power to forbid 188 + circumvention of technological measures to the extent such circumvention 189 + is effected by exercising rights under this License with respect to 190 + the covered work, and you disclaim any intention to limit operation or 191 + modification of the work as a means of enforcing, against the work's 192 + users, your or third parties' legal rights to forbid circumvention of 193 + technological measures. 194 + 195 + 4. Conveying Verbatim Copies. 196 + 197 + You may convey verbatim copies of the Program's source code as you 198 + receive it, in any medium, provided that you conspicuously and 199 + appropriately publish on each copy an appropriate copyright notice; 200 + keep intact all notices stating that this License and any 201 + non-permissive terms added in accord with section 7 apply to the code; 202 + keep intact all notices of the absence of any warranty; and give all 203 + recipients a copy of this License along with the Program. 204 + 205 + You may charge any price or no price for each copy that you convey, 206 + and you may offer support or warranty protection for a fee. 207 + 208 + 5. Conveying Modified Source Versions. 209 + 210 + You may convey a work based on the Program, or the modifications to 211 + produce it from the Program, in the form of source code under the 212 + terms of section 4, provided that you also meet all of these conditions: 213 + 214 + a) The work must carry prominent notices stating that you modified 215 + it, and giving a relevant date. 216 + 217 + b) The work must carry prominent notices stating that it is 218 + released under this License and any conditions added under section 219 + 7. This requirement modifies the requirement in section 4 to 220 + "keep intact all notices". 221 + 222 + c) You must license the entire work, as a whole, under this 223 + License to anyone who comes into possession of a copy. This 224 + License will therefore apply, along with any applicable section 7 225 + additional terms, to the whole of the work, and all its parts, 226 + regardless of how they are packaged. This License gives no 227 + permission to license the work in any other way, but it does not 228 + invalidate such permission if you have separately received it. 229 + 230 + d) If the work has interactive user interfaces, each must display 231 + Appropriate Legal Notices; however, if the Program has interactive 232 + interfaces that do not display Appropriate Legal Notices, your 233 + work need not make them do so. 234 + 235 + A compilation of a covered work with other separate and independent 236 + works, which are not by their nature extensions of the covered work, 237 + and which are not combined with it such as to form a larger program, 238 + in or on a volume of a storage or distribution medium, is called an 239 + "aggregate" if the compilation and its resulting copyright are not 240 + used to limit the access or legal rights of the compilation's users 241 + beyond what the individual works permit. Inclusion of a covered work 242 + in an aggregate does not cause this License to apply to the other 243 + parts of the aggregate. 244 + 245 + 6. Conveying Non-Source Forms. 246 + 247 + You may convey a covered work in object code form under the terms 248 + of sections 4 and 5, provided that you also convey the 249 + machine-readable Corresponding Source under the terms of this License, 250 + in one of these ways: 251 + 252 + a) Convey the object code in, or embodied in, a physical product 253 + (including a physical distribution medium), accompanied by the 254 + Corresponding Source fixed on a durable physical medium 255 + customarily used for software interchange. 256 + 257 + b) Convey the object code in, or embodied in, a physical product 258 + (including a physical distribution medium), accompanied by a 259 + written offer, valid for at least three years and valid for as 260 + long as you offer spare parts or customer support for that product 261 + model, to give anyone who possesses the object code either (1) a 262 + copy of the Corresponding Source for all the software in the 263 + product that is covered by this License, on a durable physical 264 + medium customarily used for software interchange, for a price no 265 + more than your reasonable cost of physically performing this 266 + conveying of source, or (2) access to copy the 267 + Corresponding Source from a network server at no charge. 268 + 269 + c) Convey individual copies of the object code with a copy of the 270 + written offer to provide the Corresponding Source. This 271 + alternative is allowed only occasionally and noncommercially, and 272 + only if you received the object code with such an offer, in accord 273 + with subsection 6b. 274 + 275 + d) Convey the object code by offering access from a designated 276 + place (gratis or for a charge), and offer equivalent access to the 277 + Corresponding Source in the same way through the same place at no 278 + further charge. You need not require recipients to copy the 279 + Corresponding Source along with the object code. If the place to 280 + copy the object code is a network server, the Corresponding Source 281 + may be on a different server (operated by you or a third party) 282 + that supports equivalent copying facilities, provided you maintain 283 + clear directions next to the object code saying where to find the 284 + Corresponding Source. Regardless of what server hosts the 285 + Corresponding Source, you remain obligated to ensure that it is 286 + available for as long as needed to satisfy these requirements. 287 + 288 + e) Convey the object code using peer-to-peer transmission, provided 289 + you inform other peers where the object code and Corresponding 290 + Source of the work are being offered to the general public at no 291 + charge under subsection 6d. 292 + 293 + A separable portion of the object code, whose source code is excluded 294 + from the Corresponding Source as a System Library, need not be 295 + included in conveying the object code work. 296 + 297 + A "User Product" is either (1) a "consumer product", which means any 298 + tangible personal property which is normally used for personal, family, 299 + or household purposes, or (2) anything designed or sold for incorporation 300 + into a dwelling. In determining whether a product is a consumer product, 301 + doubtful cases shall be resolved in favor of coverage. For a particular 302 + product received by a particular user, "normally used" refers to a 303 + typical or common use of that class of product, regardless of the status 304 + of the particular user or of the way in which the particular user 305 + actually uses, or expects or is expected to use, the product. A product 306 + is a consumer product regardless of whether the product has substantial 307 + commercial, industrial or non-consumer uses, unless such uses represent 308 + the only significant mode of use of the product. 309 + 310 + "Installation Information" for a User Product means any methods, 311 + procedures, authorization keys, or other information required to install 312 + and execute modified versions of a covered work in that User Product from 313 + a modified version of its Corresponding Source. The information must 314 + suffice to ensure that the continued functioning of the modified object 315 + code is in no case prevented or interfered with solely because 316 + modification has been made. 317 + 318 + If you convey an object code work under this section in, or with, or 319 + specifically for use in, a User Product, and the conveying occurs as 320 + part of a transaction in which the right of possession and use of the 321 + User Product is transferred to the recipient in perpetuity or for a 322 + fixed term (regardless of how the transaction is characterized), the 323 + Corresponding Source conveyed under this section must be accompanied 324 + by the Installation Information. But this requirement does not apply 325 + if neither you nor any third party retains the ability to install 326 + modified object code on the User Product (for example, the work has 327 + been installed in ROM). 328 + 329 + The requirement to provide Installation Information does not include a 330 + requirement to continue to provide support service, warranty, or updates 331 + for a work that has been modified or installed by the recipient, or for 332 + the User Product in which it has been modified or installed. Access to a 333 + network may be denied when the modification itself materially and 334 + adversely affects the operation of the network or violates the rules and 335 + protocols for communication across the network. 336 + 337 + Corresponding Source conveyed, and Installation Information provided, 338 + in accord with this section must be in a format that is publicly 339 + documented (and with an implementation available to the public in 340 + source code form), and must require no special password or key for 341 + unpacking, reading or copying. 342 + 343 + 7. Additional Terms. 344 + 345 + "Additional permissions" are terms that supplement the terms of this 346 + License by making exceptions from one or more of its conditions. 347 + Additional permissions that are applicable to the entire Program shall 348 + be treated as though they were included in this License, to the extent 349 + that they are valid under applicable law. If additional permissions 350 + apply only to part of the Program, that part may be used separately 351 + under those permissions, but the entire Program remains governed by 352 + this License without regard to the additional permissions. 353 + 354 + When you convey a copy of a covered work, you may at your option 355 + remove any additional permissions from that copy, or from any part of 356 + it. (Additional permissions may be written to require their own 357 + removal in certain cases when you modify the work.) You may place 358 + additional permissions on material, added by you to a covered work, 359 + for which you have or can give appropriate copyright permission. 360 + 361 + Notwithstanding any other provision of this License, for material you 362 + add to a covered work, you may (if authorized by the copyright holders of 363 + that material) supplement the terms of this License with terms: 364 + 365 + a) Disclaiming warranty or limiting liability differently from the 366 + terms of sections 15 and 16 of this License; or 367 + 368 + b) Requiring preservation of specified reasonable legal notices or 369 + author attributions in that material or in the Appropriate Legal 370 + Notices displayed by works containing it; or 371 + 372 + c) Prohibiting misrepresentation of the origin of that material, or 373 + requiring that modified versions of such material be marked in 374 + reasonable ways as different from the original version; or 375 + 376 + d) Limiting the use for publicity purposes of names of licensors or 377 + authors of the material; or 378 + 379 + e) Declining to grant rights under trademark law for use of some 380 + trade names, trademarks, or service marks; or 381 + 382 + f) Requiring indemnification of licensors and authors of that 383 + material by anyone who conveys the material (or modified versions of 384 + it) with contractual assumptions of liability to the recipient, for 385 + any liability that these contractual assumptions directly impose on 386 + those licensors and authors. 387 + 388 + All other non-permissive additional terms are considered "further 389 + restrictions" within the meaning of section 10. If the Program as you 390 + received it, or any part of it, contains a notice stating that it is 391 + governed by this License along with a term that is a further 392 + restriction, you may remove that term. If a license document contains 393 + a further restriction but permits relicensing or conveying under this 394 + License, you may add to a covered work material governed by the terms 395 + of that license document, provided that the further restriction does 396 + not survive such relicensing or conveying. 397 + 398 + If you add terms to a covered work in accord with this section, you 399 + must place, in the relevant source files, a statement of the 400 + additional terms that apply to those files, or a notice indicating 401 + where to find the applicable terms. 402 + 403 + Additional terms, permissive or non-permissive, may be stated in the 404 + form of a separately written license, or stated as exceptions; 405 + the above requirements apply either way. 406 + 407 + 8. Termination. 408 + 409 + You may not propagate or modify a covered work except as expressly 410 + provided under this License. Any attempt otherwise to propagate or 411 + modify it is void, and will automatically terminate your rights under 412 + this License (including any patent licenses granted under the third 413 + paragraph of section 11). 414 + 415 + However, if you cease all violation of this License, then your 416 + license from a particular copyright holder is reinstated (a) 417 + provisionally, unless and until the copyright holder explicitly and 418 + finally terminates your license, and (b) permanently, if the copyright 419 + holder fails to notify you of the violation by some reasonable means 420 + prior to 60 days after the cessation. 421 + 422 + Moreover, your license from a particular copyright holder is 423 + reinstated permanently if the copyright holder notifies you of the 424 + violation by some reasonable means, this is the first time you have 425 + received notice of violation of this License (for any work) from that 426 + copyright holder, and you cure the violation prior to 30 days after 427 + your receipt of the notice. 428 + 429 + Termination of your rights under this section does not terminate the 430 + licenses of parties who have received copies or rights from you under 431 + this License. If your rights have been terminated and not permanently 432 + reinstated, you do not qualify to receive new licenses for the same 433 + material under section 10. 434 + 435 + 9. Acceptance Not Required for Having Copies. 436 + 437 + You are not required to accept this License in order to receive or 438 + run a copy of the Program. Ancillary propagation of a covered work 439 + occurring solely as a consequence of using peer-to-peer transmission 440 + to receive a copy likewise does not require acceptance. However, 441 + nothing other than this License grants you permission to propagate or 442 + modify any covered work. These actions infringe copyright if you do 443 + not accept this License. Therefore, by modifying or propagating a 444 + covered work, you indicate your acceptance of this License to do so. 445 + 446 + 10. Automatic Licensing of Downstream Recipients. 447 + 448 + Each time you convey a covered work, the recipient automatically 449 + receives a license from the original licensors, to run, modify and 450 + propagate that work, subject to this License. You are not responsible 451 + for enforcing compliance by third parties with this License. 452 + 453 + An "entity transaction" is a transaction transferring control of an 454 + organization, or substantially all assets of one, or subdividing an 455 + organization, or merging organizations. If propagation of a covered 456 + work results from an entity transaction, each party to that 457 + transaction who receives a copy of the work also receives whatever 458 + licenses to the work the party's predecessor in interest had or could 459 + give under the previous paragraph, plus a right to possession of the 460 + Corresponding Source of the work from the predecessor in interest, if 461 + the predecessor has it or can get it with reasonable efforts. 462 + 463 + You may not impose any further restrictions on the exercise of the 464 + rights granted or affirmed under this License. For example, you may 465 + not impose a license fee, royalty, or other charge for exercise of 466 + rights granted under this License, and you may not initiate litigation 467 + (including a cross-claim or counterclaim in a lawsuit) alleging that 468 + any patent claim is infringed by making, using, selling, offering for 469 + sale, or importing the Program or any portion of it. 470 + 471 + 11. Patents. 472 + 473 + A "contributor" is a copyright holder who authorizes use under this 474 + License of the Program or a work on which the Program is based. The 475 + work thus licensed is called the contributor's "contributor version". 476 + 477 + A contributor's "essential patent claims" are all patent claims 478 + owned or controlled by the contributor, whether already acquired or 479 + hereafter acquired, that would be infringed by some manner, permitted 480 + by this License, of making, using, or selling its contributor version, 481 + but do not include claims that would be infringed only as a 482 + consequence of further modification of the contributor version. For 483 + purposes of this definition, "control" includes the right to grant 484 + patent sublicenses in a manner consistent with the requirements of 485 + this License. 486 + 487 + Each contributor grants you a non-exclusive, worldwide, royalty-free 488 + patent license under the contributor's essential patent claims, to 489 + make, use, sell, offer for sale, import and otherwise run, modify and 490 + propagate the contents of its contributor version. 491 + 492 + In the following three paragraphs, a "patent license" is any express 493 + agreement or commitment, however denominated, not to enforce a patent 494 + (such as an express permission to practice a patent or covenant not to 495 + sue for patent infringement). To "grant" such a patent license to a 496 + party means to make such an agreement or commitment not to enforce a 497 + patent against the party. 498 + 499 + If you convey a covered work, knowingly relying on a patent license, 500 + and the Corresponding Source of the work is not available for anyone 501 + to copy, free of charge and under the terms of this License, through a 502 + publicly available network server or other readily accessible means, 503 + then you must either (1) cause the Corresponding Source to be so 504 + available, or (2) arrange to deprive yourself of the benefit of the 505 + patent license for this particular work, or (3) arrange, in a manner 506 + consistent with the requirements of this License, to extend the patent 507 + license to downstream recipients. "Knowingly relying" means you have 508 + actual knowledge that, but for the patent license, your conveying the 509 + covered work in a country, or your recipient's use of the covered work 510 + in a country, would infringe one or more identifiable patents in that 511 + country that you have reason to believe are valid. 512 + 513 + If, pursuant to or in connection with a single transaction or 514 + arrangement, you convey, or propagate by procuring conveyance of, a 515 + covered work, and grant a patent license to some of the parties 516 + receiving the covered work authorizing them to use, propagate, modify 517 + or convey a specific copy of the covered work, then the patent license 518 + you grant is automatically extended to all recipients of the covered 519 + work and works based on it. 520 + 521 + A patent license is "discriminatory" if it does not include within 522 + the scope of its coverage, prohibits the exercise of, or is 523 + conditioned on the non-exercise of one or more of the rights that are 524 + specifically granted under this License. You may not convey a covered 525 + work if you are a party to an arrangement with a third party that is 526 + in the business of distributing software, under which you make payment 527 + to the third party based on the extent of your activity of conveying 528 + the work, and under which the third party grants, to any of the 529 + parties who would receive the covered work from you, a discriminatory 530 + patent license (a) in connection with copies of the covered work 531 + conveyed by you (or copies made from those copies), or (b) primarily 532 + for and in connection with specific products or compilations that 533 + contain the covered work, unless you entered into that arrangement, 534 + or that patent license was granted, prior to 28 March 2007. 535 + 536 + Nothing in this License shall be construed as excluding or limiting 537 + any implied license or other defenses to infringement that may 538 + otherwise be available to you under applicable patent law. 539 + 540 + 12. No Surrender of Others' Freedom. 541 + 542 + If conditions are imposed on you (whether by court order, agreement or 543 + otherwise) that contradict the conditions of this License, they do not 544 + excuse you from the conditions of this License. If you cannot convey a 545 + covered work so as to satisfy simultaneously your obligations under this 546 + License and any other pertinent obligations, then as a consequence you may 547 + not convey it at all. For example, if you agree to terms that obligate you 548 + to collect a royalty for further conveying from those to whom you convey 549 + the Program, the only way you could satisfy both those terms and this 550 + License would be to refrain entirely from conveying the Program. 551 + 552 + 13. Use with the GNU Affero General Public License. 553 + 554 + Notwithstanding any other provision of this License, you have 555 + permission to link or combine any covered work with a work licensed 556 + under version 3 of the GNU Affero General Public License into a single 557 + combined work, and to convey the resulting work. The terms of this 558 + License will continue to apply to the part which is the covered work, 559 + but the special requirements of the GNU Affero General Public License, 560 + section 13, concerning interaction through a network will apply to the 561 + combination as such. 562 + 563 + 14. Revised Versions of this License. 564 + 565 + The Free Software Foundation may publish revised and/or new versions of 566 + the GNU General Public License from time to time. Such new versions will 567 + be similar in spirit to the present version, but may differ in detail to 568 + address new problems or concerns. 569 + 570 + Each version is given a distinguishing version number. If the 571 + Program specifies that a certain numbered version of the GNU General 572 + Public License "or any later version" applies to it, you have the 573 + option of following the terms and conditions either of that numbered 574 + version or of any later version published by the Free Software 575 + Foundation. If the Program does not specify a version number of the 576 + GNU General Public License, you may choose any version ever published 577 + by the Free Software Foundation. 578 + 579 + If the Program specifies that a proxy can decide which future 580 + versions of the GNU General Public License can be used, that proxy's 581 + public statement of acceptance of a version permanently authorizes you 582 + to choose that version for the Program. 583 + 584 + Later license versions may give you additional or different 585 + permissions. However, no additional obligations are imposed on any 586 + author or copyright holder as a result of your choosing to follow a 587 + later version. 588 + 589 + 15. Disclaimer of Warranty. 590 + 591 + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 + APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 + HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 + OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 + PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 + IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 + ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 + 600 + 16. Limitation of Liability. 601 + 602 + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 + WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 + THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 + GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 + USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 + DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 + PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 + EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 + SUCH DAMAGES. 611 + 612 + 17. Interpretation of Sections 15 and 16. 613 + 614 + If the disclaimer of warranty and limitation of liability provided 615 + above cannot be given local legal effect according to their terms, 616 + reviewing courts shall apply local law that most closely approximates 617 + an absolute waiver of all civil liability in connection with the 618 + Program, unless a warranty or assumption of liability accompanies a 619 + copy of the Program in return for a fee. 620 + 621 + END OF TERMS AND CONDITIONS 622 + 623 + How to Apply These Terms to Your New Programs 624 + 625 + If you develop a new program, and you want it to be of the greatest 626 + possible use to the public, the best way to achieve this is to make it 627 + free software which everyone can redistribute and change under these terms. 628 + 629 + To do so, attach the following notices to the program. It is safest 630 + to attach them to the start of each source file to most effectively 631 + state the exclusion of warranty; and each file should have at least 632 + the "copyright" line and a pointer to where the full notice is found. 633 + 634 + <one line to give the program's name and a brief idea of what it does.> 635 + Copyright (C) <year> <name of author> 636 + 637 + This program is free software: you can redistribute it and/or modify 638 + it under the terms of the GNU General Public License as published by 639 + the Free Software Foundation, either version 3 of the License, or 640 + (at your option) any later version. 641 + 642 + This program is distributed in the hope that it will be useful, 643 + but WITHOUT ANY WARRANTY; without even the implied warranty of 644 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 + GNU General Public License for more details. 646 + 647 + You should have received a copy of the GNU General Public License 648 + along with this program. If not, see <https://www.gnu.org/licenses/>. 649 + 650 + Also add information on how to contact you by electronic and paper mail. 651 + 652 + If the program does terminal interaction, make it output a short 653 + notice like this when it starts in an interactive mode: 654 + 655 + <program> Copyright (C) <year> <name of author> 656 + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 + This is free software, and you are welcome to redistribute it 658 + under certain conditions; type `show c' for details. 659 + 660 + The hypothetical commands `show w' and `show c' should show the appropriate 661 + parts of the General Public License. Of course, your program's commands 662 + might be different; for a GUI interface, you would use an "about box". 663 + 664 + You should also get your employer (if you work as a programmer) or school, 665 + if any, to sign a "copyright disclaimer" for the program, if necessary. 666 + For more information on this, and how to apply and follow the GNU GPL, see 667 + <https://www.gnu.org/licenses/>. 668 + 669 + The GNU General Public License does not permit incorporating your program 670 + into proprietary programs. If your program is a subroutine library, you 671 + may consider it more useful to permit linking proprietary applications with 672 + the library. If this is what you want to do, use the GNU Lesser General 673 + Public License instead of this License. But first, please read 674 + <https://www.gnu.org/licenses/why-not-lgpl.html>.
+68
README.md
··· 1 + # graft 2 + 3 + A daemon that mirrors repositories between Forgejo and Radicle: git content, issues, and pull requests / patches. 4 + 5 + It runs on a timer, keeps state in a local SQLite file, and never force-pushes — a real divergence between the two sides is reported and left for a human to resolve. 6 + 7 + ## What it syncs 8 + 9 + - **Git content**: the default branch, fast-forward only. 10 + - **Issues**: Forgejo issues become Radicle issues and vice versa. Create-only for now — edits made after the first mirror aren't propagated yet. 11 + - **Patches / pull requests**: a Forgejo PR opens a Radicle patch (and back), by pushing the PR's head commit to `refs/patches` on the Radicle side, or as a branch + PR on the Forgejo side. 12 + 13 + ## Why 14 + 15 + Forgejo and Radicle solve the same problem — hosting and reviewing changes to a git repository — with opposite architectures: one is a server you point a browser at, the other is a peer-to-peer protocol with no server at all. `graft` lets a project exist properly on both without anyone choosing sides or doing the mirroring by hand. 16 + 17 + ## Requirements 18 + 19 + - Go 1.23+ to build 20 + - `git` 21 + - the `rad` CLI, with `git-remote-rad` on `PATH`, and a Radicle node already running with its own identity (`rad auth`) 22 + - a Forgejo access token scoped to `write:repository` and `write:issue` on the repo you're syncing 23 + 24 + ## Build 25 + 26 + ```sh 27 + go build -o graft ./cmd/sync 28 + ``` 29 + 30 + ## Config 31 + 32 + ```yaml 33 + sync_interval: 5m 34 + state_db: /var/lib/graft/state.db 35 + 36 + repos: 37 + - name: my-project 38 + forgejo: 39 + base_url: https://git.example.org 40 + owner: alice 41 + repo: my-project 42 + token_file: /etc/graft/my-project.token 43 + radicle: 44 + rid: rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5 45 + http_base_url: https://seed.example.org 46 + rad_home: /home/graft/.radicle 47 + sync: 48 + git: true 49 + issues: true 50 + patches: true 51 + ``` 52 + 53 + Tokens live in their own files, never inline in the config. `graft` reads them at startup and expects `chmod 600`. 54 + 55 + ## Run 56 + 57 + ```sh 58 + graft -config /etc/graft/config.yaml # loop forever, per sync_interval 59 + graft -config /etc/graft/config.yaml -once # one pass, then exit 60 + ``` 61 + 62 + A systemd unit is in `systemd/graft.service`. 63 + 64 + Full walkthrough, from a blank server to a running mirror: [TUTORIAL.md](TUTORIAL.md). 65 + 66 + ## License 67 + 68 + GPLv3. See [LICENSE](LICENSE).
+134
TUTORIAL.md
··· 1 + # Tutorial 2 + 3 + This walks through mirroring one repository between a Forgejo instance and a Radicle node, from nothing. Replace the names below with your own: 4 + 5 + | Placeholder | Stands for | 6 + |---|---| 7 + | `git.example.org` | your Forgejo instance | 8 + | `seed.example.org` | your Radicle node's `radicle-httpd` address | 9 + | `alice` | the Forgejo account that owns the repo | 10 + | `my-project` | the repository | 11 + 12 + ## Prerequisites 13 + 14 + - A Forgejo instance you can create repos and tokens on. 15 + - A machine with `git`, the `rad` CLI, and a running `radicle-node` — see [Radicle's own seeder guide](https://radicle.dev/guides/seeder) if you don't have one yet. 16 + - Go 1.23+, to build `graft`. 17 + 18 + ## 1. Build graft 19 + 20 + ```sh 21 + git clone https://git.example.org/alice/graft.git 22 + cd graft 23 + go build -o graft ./cmd/sync 24 + sudo mv graft /usr/local/bin/graft 25 + ``` 26 + 27 + ## 2. Create a Forgejo token 28 + 29 + `graft` needs a token scoped to `write:repository` and `write:issue` on the repo it syncs. 30 + 31 + ```sh 32 + curl -X POST -H "Authorization: token $ADMIN_TOKEN" \ 33 + -H "Content-Type: application/json" \ 34 + -d '{"name":"graft","scopes":["write:repository","write:issue"]}' \ 35 + https://git.example.org/api/v1/users/alice/tokens 36 + ``` 37 + 38 + Save the returned token somewhere `graft` can read and nowhere else can: 39 + 40 + ```sh 41 + mkdir -p /etc/graft 42 + echo "$TOKEN" > /etc/graft/my-project.token 43 + chmod 600 /etc/graft/my-project.token 44 + ``` 45 + 46 + ## 3. Create the repo on Forgejo 47 + 48 + ```sh 49 + curl -X POST -H "Authorization: token $TOKEN" \ 50 + -H "Content-Type: application/json" \ 51 + -d '{"name":"my-project","auto_init":true,"default_branch":"main"}' \ 52 + https://git.example.org/api/v1/user/repos 53 + ``` 54 + 55 + `auto_init` gives it one commit, so there's something to mirror. 56 + 57 + ## 4. Create the repo on Radicle 58 + 59 + Radicle repos are created from an existing git checkout. Clone the one you just made and initialize it: 60 + 61 + ```sh 62 + git clone https://git.example.org/alice/my-project.git 63 + cd my-project 64 + rad init --name my-project --default-branch main --public 65 + ``` 66 + 67 + This prints a Repository ID (RID), something like `rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5`. Write it down — the config needs it. 68 + 69 + If you have other Radicle nodes that should also carry this repo, tell them to seed it: 70 + 71 + ```sh 72 + rad seed rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5 73 + ``` 74 + 75 + ## 5. Write the config 76 + 77 + ```yaml 78 + # /etc/graft/config.yaml 79 + sync_interval: 5m 80 + state_db: /var/lib/graft/state.db 81 + 82 + repos: 83 + - name: my-project 84 + forgejo: 85 + base_url: https://git.example.org 86 + owner: alice 87 + repo: my-project 88 + token_file: /etc/graft/my-project.token 89 + radicle: 90 + rid: rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5 91 + http_base_url: https://seed.example.org 92 + rad_home: /home/graft/.radicle 93 + sync: 94 + git: true 95 + issues: true 96 + patches: true 97 + ``` 98 + 99 + `rad_home` is the `RAD_HOME` of the identity `graft` pushes as — usually a dedicated one, created with `rad auth` under whatever user runs `graft`. 100 + 101 + ## 6. Run it once 102 + 103 + ```sh 104 + mkdir -p /var/lib/graft 105 + graft -config /etc/graft/config.yaml -once 106 + ``` 107 + 108 + No output means no errors. Check both sides: 109 + 110 + ```sh 111 + curl -s https://seed.example.org/api/v1/repos/rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5 112 + ``` 113 + 114 + If you open an issue on the Forgejo repo and run `graft -once` again, it shows up on Radicle within that one pass. 115 + 116 + ## 7. Run it as a service 117 + 118 + ```sh 119 + sudo cp systemd/graft.service /etc/systemd/system/ 120 + sudo systemctl daemon-reload 121 + sudo systemctl enable --now graft 122 + ``` 123 + 124 + It now mirrors both repos every `sync_interval`, in both directions, on its own. 125 + 126 + ## Troubleshooting 127 + 128 + **"token does not have at least one of required scope(s)"** — the Forgejo token is missing `write:issue` or `write:repository`. Regenerate it with both. 129 + 130 + **"forgejo and rad diverged since last sync"** — both sides got commits since the last pass that aren't ancestors of each other. `graft` won't guess which one wins; merge them by hand on either side and it'll pick up cleanly next pass. 131 + 132 + **"'remote-rad' is not a git command"** — `git-remote-rad` (installed alongside `rad`) isn't on `PATH` for the user running `graft`. Add its directory to the systemd unit's `Environment=PATH=...`. 133 + 134 + **A patch/PR never shows up on the other side** — check that the corresponding repo isn't still empty on the destination. The first git sync has to land before patches/issues referencing that content can be mirrored.
+77
cmd/sync/main.go
··· 1 + // Command sync runs the Forgejo <-> Radicle sync daemon: on an interval, it 2 + // mirrors git content, issues and patches for every repo pair listed in the 3 + // config file, then sleeps until the next pass. 4 + package main 5 + 6 + import ( 7 + "flag" 8 + "log/slog" 9 + "os" 10 + "time" 11 + 12 + "graft/internal/config" 13 + "graft/internal/state" 14 + "graft/internal/sync" 15 + ) 16 + 17 + func main() { 18 + configPath := flag.String("config", "/etc/graft/config.yaml", "path to config.yaml") 19 + once := flag.Bool("once", false, "run a single pass and exit, instead of looping") 20 + flag.Parse() 21 + 22 + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) 23 + 24 + cfg, err := config.Load(*configPath) 25 + if err != nil { 26 + log.Error("load config", "err", err) 27 + os.Exit(1) 28 + } 29 + 30 + st, err := state.Open(cfg.StateDB) 31 + if err != nil { 32 + log.Error("open state db", "err", err) 33 + os.Exit(1) 34 + } 35 + defer st.Close() 36 + 37 + stateDir := cfg.StateDB 38 + if idx := lastSlash(stateDir); idx >= 0 { 39 + stateDir = stateDir[:idx] 40 + } 41 + 42 + syncers := make([]*sync.RepoSyncer, 0, len(cfg.Repos)) 43 + for _, pair := range cfg.Repos { 44 + rs, err := sync.New(pair, st, sync.WorkDirFor(stateDir, pair.Name)) 45 + if err != nil { 46 + log.Error("set up repo pair", "pair", pair.Name, "err", err) 47 + os.Exit(1) 48 + } 49 + syncers = append(syncers, rs) 50 + } 51 + 52 + runAll := func() { 53 + for _, rs := range syncers { 54 + rs.Run(log) 55 + } 56 + } 57 + 58 + runAll() 59 + if *once { 60 + return 61 + } 62 + 63 + ticker := time.NewTicker(cfg.SyncInterval) 64 + defer ticker.Stop() 65 + for range ticker.C { 66 + runAll() 67 + } 68 + } 69 + 70 + func lastSlash(s string) int { 71 + for i := len(s) - 1; i >= 0; i-- { 72 + if s[i] == '/' { 73 + return i 74 + } 75 + } 76 + return -1 77 + }
+22
config.example.yaml
··· 1 + # Copy to /etc/graft/config.yaml and adjust. 2 + # This file itself holds no secrets: tokens live in separate files 3 + # (token_file), owned by the sync user, mode 600. 4 + 5 + sync_interval: 5m 6 + state_db: /var/lib/graft/state.db 7 + 8 + repos: 9 + - name: testrepo 10 + forgejo: 11 + base_url: https://f1.cyberwild.org 12 + owner: forgeadmin 13 + repo: testrepo 14 + token_file: /etc/graft/f1-testrepo.token 15 + radicle: 16 + rid: rad:z2YWuPL53okTkr5mgb7WCKsfxG7h8 17 + http_base_url: https://r1.cyberwild.org 18 + rad_home: /home/sync/.radicle 19 + sync: 20 + git: true 21 + issues: true 22 + patches: true
+20
go.mod
··· 1 + module graft 2 + 3 + go 1.23 4 + 5 + require ( 6 + gopkg.in/yaml.v3 v3.0.1 7 + modernc.org/sqlite v1.34.5 8 + ) 9 + 10 + require ( 11 + github.com/dustin/go-humanize v1.0.1 // indirect 12 + github.com/google/uuid v1.6.0 // indirect 13 + github.com/mattn/go-isatty v0.0.20 // indirect 14 + github.com/ncruces/go-strftime v0.1.9 // indirect 15 + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect 16 + golang.org/x/sys v0.22.0 // indirect 17 + modernc.org/libc v1.55.3 // indirect 18 + modernc.org/mathutil v1.6.0 // indirect 19 + modernc.org/memory v1.8.0 // indirect 20 + )
+47
go.sum
··· 1 + github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= 2 + github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= 3 + github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= 4 + github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= 5 + github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 6 + github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 7 + github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 8 + github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 9 + github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= 10 + github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= 11 + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= 12 + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= 13 + golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= 14 + golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 15 + golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 16 + golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= 17 + golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 18 + golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw= 19 + golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= 20 + gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 21 + gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 22 + gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 23 + gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 24 + modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= 25 + modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= 26 + modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= 27 + modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s= 28 + modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= 29 + modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= 30 + modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= 31 + modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= 32 + modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= 33 + modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= 34 + modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= 35 + modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= 36 + modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= 37 + modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= 38 + modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= 39 + modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= 40 + modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= 41 + modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= 42 + modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g= 43 + modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE= 44 + modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= 45 + modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= 46 + modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= 47 + modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
+126
internal/config/config.go
··· 1 + // Package config loads and validates the sync daemon's configuration. 2 + package config 3 + 4 + import ( 5 + "fmt" 6 + "os" 7 + "time" 8 + 9 + "gopkg.in/yaml.v3" 10 + ) 11 + 12 + // Config is the top-level configuration for the sync daemon. 13 + type Config struct { 14 + SyncInterval time.Duration `yaml:"sync_interval"` 15 + StateDB string `yaml:"state_db"` 16 + Repos []RepoPair `yaml:"repos"` 17 + } 18 + 19 + // RepoPair links one Forgejo repository to one Radicle repository and 20 + // declares which content types are kept in sync between them. 21 + type RepoPair struct { 22 + Name string `yaml:"name"` 23 + Forgejo ForgejoTarget `yaml:"forgejo"` 24 + Radicle RadicleTarget `yaml:"radicle"` 25 + Sync SyncScope `yaml:"sync"` 26 + } 27 + 28 + // ForgejoTarget identifies a repository on a Forgejo instance and where to 29 + // read its access token from. The token is never stored inline in the 30 + // config file so the file itself can be handled as non-sensitive. 31 + type ForgejoTarget struct { 32 + BaseURL string `yaml:"base_url"` 33 + Owner string `yaml:"owner"` 34 + Repo string `yaml:"repo"` 35 + TokenFile string `yaml:"token_file"` 36 + } 37 + 38 + // RadicleTarget identifies a repository on a Radicle node. HTTPBaseURL is 39 + // that node's radicle-httpd endpoint (e.g. https://r1.cyberwild.org), used 40 + // for reads; RadHome is the local RAD_HOME whose keys the "rad" CLI uses 41 + // for writes — the two are only the same node when the daemon runs 42 + // alongside it, which is not assumed here. 43 + type RadicleTarget struct { 44 + RID string `yaml:"rid"` 45 + HTTPBaseURL string `yaml:"http_base_url"` 46 + RadHome string `yaml:"rad_home"` 47 + } 48 + 49 + // SyncScope selects which content types are synchronized for a repo pair. 50 + type SyncScope struct { 51 + Git bool `yaml:"git"` 52 + Issues bool `yaml:"issues"` 53 + Patches bool `yaml:"patches"` 54 + } 55 + 56 + // Load reads and validates the configuration file at path. 57 + func Load(path string) (*Config, error) { 58 + data, err := os.ReadFile(path) 59 + if err != nil { 60 + return nil, fmt.Errorf("read config: %w", err) 61 + } 62 + 63 + var cfg Config 64 + if err := yaml.Unmarshal(data, &cfg); err != nil { 65 + return nil, fmt.Errorf("parse config: %w", err) 66 + } 67 + 68 + if cfg.SyncInterval <= 0 { 69 + cfg.SyncInterval = 5 * time.Minute 70 + } 71 + if cfg.StateDB == "" { 72 + return nil, fmt.Errorf("state_db must be set") 73 + } 74 + if len(cfg.Repos) == 0 { 75 + return nil, fmt.Errorf("no repos configured") 76 + } 77 + for i, r := range cfg.Repos { 78 + if err := r.validate(); err != nil { 79 + return nil, fmt.Errorf("repos[%d] (%s): %w", i, r.Name, err) 80 + } 81 + } 82 + 83 + return &cfg, nil 84 + } 85 + 86 + func (r RepoPair) validate() error { 87 + if r.Name == "" { 88 + return fmt.Errorf("name is required") 89 + } 90 + if r.Forgejo.BaseURL == "" || r.Forgejo.Owner == "" || r.Forgejo.Repo == "" { 91 + return fmt.Errorf("forgejo.base_url, owner and repo are required") 92 + } 93 + if r.Forgejo.TokenFile == "" { 94 + return fmt.Errorf("forgejo.token_file is required") 95 + } 96 + if r.Radicle.RID == "" { 97 + return fmt.Errorf("radicle.rid is required") 98 + } 99 + if r.Radicle.HTTPBaseURL == "" { 100 + return fmt.Errorf("radicle.http_base_url is required") 101 + } 102 + if r.Radicle.RadHome == "" { 103 + return fmt.Errorf("radicle.rad_home is required") 104 + } 105 + if !r.Sync.Git && !r.Sync.Issues && !r.Sync.Patches { 106 + return fmt.Errorf("at least one of sync.git, sync.issues, sync.patches must be true") 107 + } 108 + return nil 109 + } 110 + 111 + // ReadToken reads a token from a file, trimming surrounding whitespace. 112 + // Token files are expected to be chmod 600 and owned by the service user. 113 + func ReadToken(path string) (string, error) { 114 + data, err := os.ReadFile(path) 115 + if err != nil { 116 + return "", fmt.Errorf("read token file %s: %w", path, err) 117 + } 118 + token := string(data) 119 + for len(token) > 0 && (token[len(token)-1] == '\n' || token[len(token)-1] == '\r' || token[len(token)-1] == ' ') { 120 + token = token[:len(token)-1] 121 + } 122 + if token == "" { 123 + return "", fmt.Errorf("token file %s is empty", path) 124 + } 125 + return token, nil 126 + }
+146
internal/forgejo/client.go
··· 1 + // Package forgejo is a minimal client for the subset of the Forgejo REST 2 + // API the sync daemon needs: reading/creating issues and pull requests, 3 + // and resolving a repository's clone URL and default branch. 4 + package forgejo 5 + 6 + import ( 7 + "bytes" 8 + "encoding/json" 9 + "fmt" 10 + "io" 11 + "net/http" 12 + "strings" 13 + "time" 14 + ) 15 + 16 + // Client talks to one Forgejo instance on behalf of one repository. 17 + type Client struct { 18 + baseURL string 19 + owner string 20 + repo string 21 + token string 22 + http *http.Client 23 + } 24 + 25 + func New(baseURL, owner, repo, token string) *Client { 26 + return &Client{ 27 + baseURL: strings.TrimRight(baseURL, "/"), 28 + owner: owner, 29 + repo: repo, 30 + token: token, 31 + http: &http.Client{Timeout: 30 * time.Second}, 32 + } 33 + } 34 + 35 + func (c *Client) do(method, path string, body any, out any) error { 36 + var reqBody io.Reader 37 + if body != nil { 38 + b, err := json.Marshal(body) 39 + if err != nil { 40 + return fmt.Errorf("encode request: %w", err) 41 + } 42 + reqBody = bytes.NewReader(b) 43 + } 44 + 45 + url := c.baseURL + "/api/v1" + path 46 + req, err := http.NewRequest(method, url, reqBody) 47 + if err != nil { 48 + return fmt.Errorf("build request: %w", err) 49 + } 50 + req.Header.Set("Authorization", "token "+c.token) 51 + req.Header.Set("Content-Type", "application/json") 52 + 53 + resp, err := c.http.Do(req) 54 + if err != nil { 55 + return fmt.Errorf("%s %s: %w", method, path, err) 56 + } 57 + defer resp.Body.Close() 58 + 59 + if resp.StatusCode >= 300 { 60 + respBody, _ := io.ReadAll(resp.Body) 61 + return fmt.Errorf("%s %s: HTTP %d: %s", method, path, resp.StatusCode, string(respBody)) 62 + } 63 + 64 + if out != nil { 65 + if err := json.NewDecoder(resp.Body).Decode(out); err != nil { 66 + return fmt.Errorf("decode response for %s %s: %w", method, path, err) 67 + } 68 + } 69 + return nil 70 + } 71 + 72 + // Repository is the subset of Forgejo's repository object the daemon uses. 73 + type Repository struct { 74 + CloneURL string `json:"clone_url"` 75 + DefaultBranch string `json:"default_branch"` 76 + } 77 + 78 + func (c *Client) GetRepository() (*Repository, error) { 79 + var repo Repository 80 + path := fmt.Sprintf("/repos/%s/%s", c.owner, c.repo) 81 + if err := c.do(http.MethodGet, path, nil, &repo); err != nil { 82 + return nil, err 83 + } 84 + return &repo, nil 85 + } 86 + 87 + // Issue is the subset of Forgejo's issue object the daemon reads and writes. 88 + type Issue struct { 89 + Index int64 `json:"number"` 90 + Title string `json:"title"` 91 + Body string `json:"body"` 92 + State string `json:"state"` 93 + } 94 + 95 + func (c *Client) ListIssues() ([]Issue, error) { 96 + var issues []Issue 97 + path := fmt.Sprintf("/repos/%s/%s/issues?type=issues&state=all&limit=50", c.owner, c.repo) 98 + if err := c.do(http.MethodGet, path, nil, &issues); err != nil { 99 + return nil, err 100 + } 101 + return issues, nil 102 + } 103 + 104 + func (c *Client) CreateIssue(title, body string) (*Issue, error) { 105 + var issue Issue 106 + path := fmt.Sprintf("/repos/%s/%s/issues", c.owner, c.repo) 107 + req := map[string]string{"title": title, "body": body} 108 + if err := c.do(http.MethodPost, path, req, &issue); err != nil { 109 + return nil, err 110 + } 111 + return &issue, nil 112 + } 113 + 114 + // PullRequest is the subset of Forgejo's pull request object the daemon 115 + // reads and writes. 116 + type PullRequest struct { 117 + Index int64 `json:"number"` 118 + Title string `json:"title"` 119 + Body string `json:"body"` 120 + State string `json:"state"` 121 + Head Branch `json:"head"` 122 + Base Branch `json:"base"` 123 + } 124 + 125 + type Branch struct { 126 + Ref string `json:"ref"` 127 + } 128 + 129 + func (c *Client) ListPullRequests() ([]PullRequest, error) { 130 + var prs []PullRequest 131 + path := fmt.Sprintf("/repos/%s/%s/pulls?state=all&limit=50", c.owner, c.repo) 132 + if err := c.do(http.MethodGet, path, nil, &prs); err != nil { 133 + return nil, err 134 + } 135 + return prs, nil 136 + } 137 + 138 + func (c *Client) CreatePullRequest(title, body, head, base string) (*PullRequest, error) { 139 + var pr PullRequest 140 + path := fmt.Sprintf("/repos/%s/%s/pulls", c.owner, c.repo) 141 + req := map[string]string{"title": title, "body": body, "head": head, "base": base} 142 + if err := c.do(http.MethodPost, path, req, &pr); err != nil { 143 + return nil, err 144 + } 145 + return &pr, nil 146 + }
+154
internal/radicle/client.go
··· 1 + // Package radicle talks to one local Radicle node: reads go through 2 + // radicle-httpd's JSON API (schema confirmed against a live v0.28.0 node — 3 + // see the field comments below), writes go through the "rad" CLI since 4 + // radicle-httpd exposes no write endpoints. 5 + package radicle 6 + 7 + import ( 8 + "bytes" 9 + "encoding/json" 10 + "fmt" 11 + "net/http" 12 + "os" 13 + "os/exec" 14 + "time" 15 + ) 16 + 17 + // Client operates on one repository (identified by its RID) tracked by one 18 + // local Radicle node. 19 + type Client struct { 20 + httpdBaseURL string // e.g. https://r1.cyberwild.org, used for reads 21 + rid string 22 + radHome string // RAD_HOME for the "rad" CLI, used for writes 23 + radBin string // path to the rad binary 24 + http *http.Client 25 + } 26 + 27 + func New(httpdBaseURL, rid, radHome, radBin string) *Client { 28 + return &Client{ 29 + httpdBaseURL: httpdBaseURL, 30 + rid: rid, 31 + radHome: radHome, 32 + radBin: radBin, 33 + http: &http.Client{Timeout: 30 * time.Second}, 34 + } 35 + } 36 + 37 + func (c *Client) getJSON(path string, out any) error { 38 + resp, err := c.http.Get(c.httpdBaseURL + "/api/v1/repos/" + c.rid + path) 39 + if err != nil { 40 + return fmt.Errorf("GET %s: %w", path, err) 41 + } 42 + defer resp.Body.Close() 43 + if resp.StatusCode >= 300 { 44 + return fmt.Errorf("GET %s: HTTP %d", path, resp.StatusCode) 45 + } 46 + return json.NewDecoder(resp.Body).Decode(out) 47 + } 48 + 49 + // rad runs the CLI against this client's repository and RAD_HOME, returning 50 + // combined stdout+stderr for logging on error. 51 + func (c *Client) rad(args ...string) (string, error) { 52 + args = append(args, "--repo", c.rid) 53 + cmd := exec.Command(c.radBin, args...) 54 + cmd.Env = append(os.Environ(), "RAD_HOME="+c.radHome) 55 + var out bytes.Buffer 56 + cmd.Stdout = &out 57 + cmd.Stderr = &out 58 + if err := cmd.Run(); err != nil { 59 + return out.String(), fmt.Errorf("rad %v: %w: %s", args, err, out.String()) 60 + } 61 + return out.String(), nil 62 + } 63 + 64 + // Actor identifies who authored an issue, comment, or patch revision. 65 + type Actor struct { 66 + ID string `json:"id"` // did:key:... 67 + Alias string `json:"alias"` 68 + } 69 + 70 + // IssueState mirrors radicle-httpd's issue state object. 71 + type IssueState struct { 72 + Status string `json:"status"` // "open" or "closed" 73 + } 74 + 75 + // Issue is the subset of radicle-httpd's issue JSON the daemon needs. 76 + // Verified against GET /api/v1/repos/:rid/issues?status=all on httpd 0.28.0. 77 + type Issue struct { 78 + ID string `json:"id"` 79 + Title string `json:"title"` 80 + State IssueState `json:"state"` 81 + Author Actor `json:"author"` 82 + Discussion []struct { 83 + Body string `json:"body"` 84 + } `json:"discussion"` 85 + } 86 + 87 + // Body returns the issue's opening comment, if any. 88 + func (i Issue) Body() string { 89 + if len(i.Discussion) == 0 { 90 + return "" 91 + } 92 + return i.Discussion[0].Body 93 + } 94 + 95 + func (c *Client) ListIssues() ([]Issue, error) { 96 + var issues []Issue 97 + if err := c.getJSON("/issues?status=all", &issues); err != nil { 98 + return nil, err 99 + } 100 + return issues, nil 101 + } 102 + 103 + // OpenIssue creates a new issue via the CLI (no write API exists on httpd). 104 + func (c *Client) OpenIssue(title, description string) (string, error) { 105 + out, err := c.rad("issue", "open", "-t", title, "-d", description, "--quiet") 106 + if err != nil { 107 + return "", err 108 + } 109 + // --quiet still prints the new issue id on its own line. 110 + id := trimLastLine(out) 111 + if id == "" { 112 + return "", fmt.Errorf("rad issue open: could not parse issue id from output: %q", out) 113 + } 114 + return id, nil 115 + } 116 + 117 + // PatchState mirrors radicle-httpd's patch state object. 118 + type PatchState struct { 119 + Status string `json:"status"` // "open", "draft", "archived", "merged" 120 + } 121 + 122 + // Patch is the subset of radicle-httpd's patch JSON the daemon needs. 123 + // Verified against GET /api/v1/repos/:rid/patches?status=all on httpd 0.28.0. 124 + type Patch struct { 125 + ID string `json:"id"` 126 + Title string `json:"title"` 127 + State PatchState `json:"state"` 128 + Author Actor `json:"author"` 129 + Revisions []struct { 130 + Description string `json:"description"` 131 + OID string `json:"oid"` // head commit of the revision 132 + Base string `json:"base"` // commit the patch is based on 133 + } `json:"revisions"` 134 + } 135 + 136 + func (c *Client) ListPatches() ([]Patch, error) { 137 + var patches []Patch 138 + if err := c.getJSON("/patches?status=all", &patches); err != nil { 139 + return nil, err 140 + } 141 + return patches, nil 142 + } 143 + 144 + func trimLastLine(s string) string { 145 + start := len(s) 146 + for start > 0 && s[start-1] == '\n' { 147 + start-- 148 + } 149 + end := start 150 + for start > 0 && s[start-1] != '\n' { 151 + start-- 152 + } 153 + return s[start:end] 154 + }
+128
internal/state/store.go
··· 1 + // Package state persists sync bookkeeping so the daemon can tell, across 2 + // restarts, what has already been mirrored and avoid duplicating issues, 3 + // patches or commits on every poll. 4 + package state 5 + 6 + import ( 7 + "database/sql" 8 + "fmt" 9 + 10 + _ "modernc.org/sqlite" 11 + ) 12 + 13 + // Store wraps the local SQLite database used to track sync state. 14 + type Store struct { 15 + db *sql.DB 16 + } 17 + 18 + // Open creates (if needed) and opens the state database at path. 19 + func Open(path string) (*Store, error) { 20 + db, err := sql.Open("sqlite", path) 21 + if err != nil { 22 + return nil, fmt.Errorf("open state db: %w", err) 23 + } 24 + if err := migrate(db); err != nil { 25 + db.Close() 26 + return nil, fmt.Errorf("migrate state db: %w", err) 27 + } 28 + return &Store{db: db}, nil 29 + } 30 + 31 + func (s *Store) Close() error { 32 + return s.db.Close() 33 + } 34 + 35 + func migrate(db *sql.DB) error { 36 + _, err := db.Exec(` 37 + CREATE TABLE IF NOT EXISTS git_cursor ( 38 + repo_pair TEXT PRIMARY KEY, 39 + forgejo_sha TEXT NOT NULL DEFAULT '', 40 + radicle_sha TEXT NOT NULL DEFAULT '' 41 + ); 42 + 43 + CREATE TABLE IF NOT EXISTS item_mapping ( 44 + repo_pair TEXT NOT NULL, 45 + kind TEXT NOT NULL, -- 'issue' or 'patch' 46 + forgejo_id INTEGER NOT NULL DEFAULT 0, 47 + radicle_id TEXT NOT NULL DEFAULT '', 48 + content_hash TEXT NOT NULL DEFAULT '', 49 + synced_at TEXT NOT NULL, 50 + PRIMARY KEY (repo_pair, kind, forgejo_id, radicle_id) 51 + ); 52 + 53 + CREATE INDEX IF NOT EXISTS idx_item_mapping_forgejo 54 + ON item_mapping (repo_pair, kind, forgejo_id); 55 + CREATE INDEX IF NOT EXISTS idx_item_mapping_radicle 56 + ON item_mapping (repo_pair, kind, radicle_id); 57 + `) 58 + return err 59 + } 60 + 61 + // GitCursor returns the last-synced commit SHAs on each side for a repo pair. 62 + func (s *Store) GitCursor(repoPair string) (forgejoSHA, radicleSHA string, err error) { 63 + row := s.db.QueryRow(`SELECT forgejo_sha, radicle_sha FROM git_cursor WHERE repo_pair = ?`, repoPair) 64 + err = row.Scan(&forgejoSHA, &radicleSHA) 65 + if err == sql.ErrNoRows { 66 + return "", "", nil 67 + } 68 + return forgejoSHA, radicleSHA, err 69 + } 70 + 71 + // SetGitCursor records the commit SHAs last observed on each side. 72 + func (s *Store) SetGitCursor(repoPair, forgejoSHA, radicleSHA string) error { 73 + _, err := s.db.Exec(` 74 + INSERT INTO git_cursor (repo_pair, forgejo_sha, radicle_sha) VALUES (?, ?, ?) 75 + ON CONFLICT (repo_pair) DO UPDATE SET forgejo_sha = excluded.forgejo_sha, radicle_sha = excluded.radicle_sha 76 + `, repoPair, forgejoSHA, radicleSHA) 77 + return err 78 + } 79 + 80 + // ItemMapping records the correspondence between a Forgejo issue/PR and its 81 + // mirrored Radicle issue/patch, plus a content hash used to detect edits 82 + // that need re-syncing. 83 + type ItemMapping struct { 84 + Kind string // "issue" or "patch" 85 + ForgejoID int64 86 + RadicleID string 87 + ContentHash string 88 + } 89 + 90 + // FindByForgejoID looks up an existing mapping created for a Forgejo item. 91 + func (s *Store) FindByForgejoID(repoPair, kind string, forgejoID int64) (*ItemMapping, error) { 92 + row := s.db.QueryRow(` 93 + SELECT radicle_id, content_hash FROM item_mapping 94 + WHERE repo_pair = ? AND kind = ? AND forgejo_id = ? 95 + `, repoPair, kind, forgejoID) 96 + m := &ItemMapping{Kind: kind, ForgejoID: forgejoID} 97 + err := row.Scan(&m.RadicleID, &m.ContentHash) 98 + if err == sql.ErrNoRows { 99 + return nil, nil 100 + } 101 + return m, err 102 + } 103 + 104 + // FindByRadicleID looks up an existing mapping created for a Radicle item. 105 + func (s *Store) FindByRadicleID(repoPair, kind, radicleID string) (*ItemMapping, error) { 106 + row := s.db.QueryRow(` 107 + SELECT forgejo_id, content_hash FROM item_mapping 108 + WHERE repo_pair = ? AND kind = ? AND radicle_id = ? 109 + `, repoPair, kind, radicleID) 110 + m := &ItemMapping{Kind: kind, RadicleID: radicleID} 111 + err := row.Scan(&m.ForgejoID, &m.ContentHash) 112 + if err == sql.ErrNoRows { 113 + return nil, nil 114 + } 115 + return m, err 116 + } 117 + 118 + // Upsert records or updates a mapping between a Forgejo item and its 119 + // Radicle counterpart. 120 + func (s *Store) Upsert(repoPair string, m ItemMapping) error { 121 + _, err := s.db.Exec(` 122 + INSERT INTO item_mapping (repo_pair, kind, forgejo_id, radicle_id, content_hash, synced_at) 123 + VALUES (?, ?, ?, ?, ?, datetime('now')) 124 + ON CONFLICT (repo_pair, kind, forgejo_id, radicle_id) 125 + DO UPDATE SET content_hash = excluded.content_hash, synced_at = excluded.synced_at 126 + `, repoPair, m.Kind, m.ForgejoID, m.RadicleID, m.ContentHash) 127 + return err 128 + }
+199
internal/sync/git.go
··· 1 + // Package sync is the actual synchronization brick: it takes a Forgejo 2 + // client and a Radicle client for one repo pair and mirrors content between 3 + // them, using the state store to stay idempotent across runs. 4 + // 5 + // Scope of this first version, deliberately: fast-forward-only git mirroring 6 + // (a real divergence is logged and skipped, never force-pushed), and 7 + // create-only issue/patch mirroring (edits made after the initial mirror are 8 + // not propagated — that needs per-item diffing, left for a follow-up once 9 + // the create path is proven in practice). 10 + package sync 11 + 12 + import ( 13 + "bytes" 14 + "fmt" 15 + "os" 16 + "os/exec" 17 + "path/filepath" 18 + "strings" 19 + 20 + "graft/internal/state" 21 + ) 22 + 23 + // GitSyncer mirrors a repository's default branch between Forgejo and 24 + // Radicle using a local working clone with two remotes. 25 + type GitSyncer struct { 26 + RepoPair string // key used in the state store 27 + WorkDir string // local clone, created on first run if absent 28 + ForgejoURL string // authenticated clone URL (token embedded) 29 + ForgejoBranch string 30 + RID string 31 + RadHome string 32 + State *state.Store 33 + } 34 + 35 + func (g *GitSyncer) run(args ...string) (string, error) { 36 + cmd := exec.Command("git", args...) 37 + cmd.Dir = g.WorkDir 38 + cmd.Env = append(os.Environ(), "RAD_HOME="+g.RadHome) 39 + var out bytes.Buffer 40 + cmd.Stdout = &out 41 + cmd.Stderr = &out 42 + err := cmd.Run() 43 + if err != nil { 44 + return out.String(), fmt.Errorf("git %v: %w: %s", args, err, out.String()) 45 + } 46 + return out.String(), nil 47 + } 48 + 49 + // ensureClone creates the working clone and its two remotes if this is the 50 + // first run for this repo pair. The rad remote mirrors exactly what 51 + // `rad init` itself sets up (verified against a live repo): a fetch URL of 52 + // rad://<rid>, and a separate push URL of rad://<rid>/<local-node-id> — 53 + // git-remote-rad needs the pushing node's own id in the push URL. 54 + func (g *GitSyncer) ensureClone() error { 55 + if _, err := os.Stat(filepath.Join(g.WorkDir, ".git")); err == nil { 56 + return nil 57 + } 58 + if err := os.MkdirAll(g.WorkDir, 0o700); err != nil { 59 + return fmt.Errorf("create work dir: %w", err) 60 + } 61 + if _, err := g.run("init", "-q", "-b", g.ForgejoBranch); err != nil { 62 + return err 63 + } 64 + if _, err := g.run("remote", "add", "forgejo", g.ForgejoURL); err != nil { 65 + return err 66 + } 67 + 68 + ridBare := strings.TrimPrefix(g.RID, "rad:") 69 + nid, err := g.localNodeID() 70 + if err != nil { 71 + return fmt.Errorf("resolve local node id: %w", err) 72 + } 73 + if _, err := g.run("remote", "add", "rad", "rad://"+ridBare); err != nil { 74 + return err 75 + } 76 + if _, err := g.run("remote", "set-url", "--push", "rad", "rad://"+ridBare+"/"+nid); err != nil { 77 + return err 78 + } 79 + return nil 80 + } 81 + 82 + // localNodeID returns the Radicle node id (DID, without the did:key: 83 + // prefix) that owns g.RadHome. 84 + func (g *GitSyncer) localNodeID() (string, error) { 85 + // --nid is deprecated in favor of `rad node status --only nid` and 86 + // prints a warning to stderr; keep that separate from stdout so it 87 + // never ends up concatenated into the id itself. 88 + cmd := exec.Command("rad", "self", "--nid") 89 + cmd.Env = append(os.Environ(), "RAD_HOME="+g.RadHome) 90 + var out, errOut bytes.Buffer 91 + cmd.Stdout = &out 92 + cmd.Stderr = &errOut 93 + if err := cmd.Run(); err != nil { 94 + return "", fmt.Errorf("rad self --nid: %w: %s", err, errOut.String()) 95 + } 96 + return strings.TrimSpace(out.String()), nil 97 + } 98 + 99 + // headOf returns the commit SHA a remote branch currently points to, or "" 100 + // if the branch does not exist yet on that remote. 101 + func (g *GitSyncer) headOf(remote, branch string) (string, error) { 102 + out, err := g.run("ls-remote", remote, "refs/heads/"+branch) 103 + if err != nil { 104 + return "", err 105 + } 106 + if out == "" { 107 + return "", nil 108 + } 109 + var sha string 110 + fmt.Sscanf(out, "%s", &sha) 111 + return sha, nil 112 + } 113 + 114 + // isAncestor reports whether commit a is an ancestor of commit b (i.e. 115 + // fast-forwarding from a to b is safe). 116 + func (g *GitSyncer) isAncestor(a, b string) bool { 117 + _, err := g.run("merge-base", "--is-ancestor", a, b) 118 + return err == nil 119 + } 120 + 121 + // Sync mirrors the default branch in whichever direction has new, 122 + // fast-forwardable commits. It never force-pushes: a genuine divergence 123 + // (commits on both sides since the last sync, neither an ancestor of the 124 + // other) is reported as an error so the operator can resolve it by hand. 125 + func (g *GitSyncer) Sync() error { 126 + if err := g.ensureClone(); err != nil { 127 + return err 128 + } 129 + 130 + forgejoHead, err := g.headOf("forgejo", g.ForgejoBranch) 131 + if err != nil { 132 + return fmt.Errorf("read forgejo head: %w", err) 133 + } 134 + radHead, err := g.headOf("rad", g.ForgejoBranch) 135 + if err != nil { 136 + return fmt.Errorf("read rad head: %w", err) 137 + } 138 + 139 + lastForgejo, lastRad, err := g.State.GitCursor(g.RepoPair) 140 + if err != nil { 141 + return fmt.Errorf("read cursor: %w", err) 142 + } 143 + 144 + switch { 145 + case forgejoHead == radHead: 146 + // Already in sync; still record the cursor in case this is the 147 + // first run and it was empty before. 148 + 149 + case radHead == "" || radHead == lastRad: 150 + // Radicle hasn't moved since we last looked: forgejo is ahead. 151 + if err := g.pushBranch("forgejo", "rad"); err != nil { 152 + return fmt.Errorf("mirror forgejo -> rad: %w", err) 153 + } 154 + 155 + case forgejoHead == "" || forgejoHead == lastForgejo: 156 + // Forgejo hasn't moved: rad is ahead. 157 + if err := g.pushBranch("rad", "forgejo"); err != nil { 158 + return fmt.Errorf("mirror rad -> forgejo: %w", err) 159 + } 160 + 161 + case g.isAncestor(lastForgejo, forgejoHead) && g.isAncestor(lastRad, radHead) && 162 + g.isAncestor(radHead, forgejoHead): 163 + // Both moved, but rad's tip is contained in forgejo's: forgejo wins. 164 + if err := g.pushBranch("forgejo", "rad"); err != nil { 165 + return fmt.Errorf("mirror forgejo -> rad: %w", err) 166 + } 167 + 168 + case g.isAncestor(forgejoHead, radHead): 169 + // Symmetric case: forgejo's tip is contained in rad's. 170 + if err := g.pushBranch("rad", "forgejo"); err != nil { 171 + return fmt.Errorf("mirror rad -> forgejo: %w", err) 172 + } 173 + 174 + default: 175 + return fmt.Errorf( 176 + "%s: forgejo and rad diverged since last sync (forgejo=%s rad=%s, last forgejo=%s rad=%s); resolve manually, not auto-merging", 177 + g.RepoPair, forgejoHead, radHead, lastForgejo, lastRad) 178 + } 179 + 180 + forgejoHead, err = g.headOf("forgejo", g.ForgejoBranch) 181 + if err != nil { 182 + return err 183 + } 184 + radHead, err = g.headOf("rad", g.ForgejoBranch) 185 + if err != nil { 186 + return err 187 + } 188 + return g.State.SetGitCursor(g.RepoPair, forgejoHead, radHead) 189 + } 190 + 191 + func (g *GitSyncer) pushBranch(from, to string) error { 192 + if _, err := g.run("fetch", "-q", from, g.ForgejoBranch); err != nil { 193 + return fmt.Errorf("fetch %s: %w", from, err) 194 + } 195 + if _, err := g.run("push", to, "FETCH_HEAD:refs/heads/"+g.ForgejoBranch); err != nil { 196 + return fmt.Errorf("push %s: %w", to, err) 197 + } 198 + return nil 199 + }
+100
internal/sync/issues.go
··· 1 + package sync 2 + 3 + import ( 4 + "crypto/sha256" 5 + "encoding/hex" 6 + "fmt" 7 + 8 + "graft/internal/forgejo" 9 + "graft/internal/radicle" 10 + "graft/internal/state" 11 + ) 12 + 13 + // A marker prepended to mirrored items' bodies so a human browsing either 14 + // side can tell where an issue/patch actually originated. 15 + const mirrorNotice = "\n\n---\n_Mirrored automatically, do not edit here — edit at the source instead._" 16 + 17 + // IssueSyncer mirrors issues between one Forgejo repository and one Radicle 18 + // repository, create-only (see package doc for what that means). 19 + type IssueSyncer struct { 20 + RepoPair string 21 + Forgejo *forgejo.Client 22 + Radicle *radicle.Client 23 + State *state.Store 24 + } 25 + 26 + func (s *IssueSyncer) Sync() error { 27 + forgejoIssues, err := s.Forgejo.ListIssues() 28 + if err != nil { 29 + return fmt.Errorf("list forgejo issues: %w", err) 30 + } 31 + radicleIssues, err := s.Radicle.ListIssues() 32 + if err != nil { 33 + return fmt.Errorf("list radicle issues: %w", err) 34 + } 35 + 36 + for _, fi := range forgejoIssues { 37 + if err := s.mirrorForgejoToRadicle(fi); err != nil { 38 + return fmt.Errorf("mirror forgejo issue #%d: %w", fi.Index, err) 39 + } 40 + } 41 + for _, ri := range radicleIssues { 42 + if err := s.mirrorRadicleToForgejo(ri); err != nil { 43 + return fmt.Errorf("mirror radicle issue %s: %w", ri.ID, err) 44 + } 45 + } 46 + return nil 47 + } 48 + 49 + func (s *IssueSyncer) mirrorForgejoToRadicle(fi forgejo.Issue) error { 50 + existing, err := s.State.FindByForgejoID(s.RepoPair, "issue", fi.Index) 51 + if err != nil { 52 + return err 53 + } 54 + if existing != nil { 55 + return nil // already mirrored; edits not yet synced (see package doc) 56 + } 57 + 58 + radicleID, err := s.Radicle.OpenIssue(fi.Title, fi.Body+mirrorNotice) 59 + if err != nil { 60 + return fmt.Errorf("open radicle issue: %w", err) 61 + } 62 + 63 + return s.State.Upsert(s.RepoPair, state.ItemMapping{ 64 + Kind: "issue", 65 + ForgejoID: fi.Index, 66 + RadicleID: radicleID, 67 + ContentHash: hashText(fi.Title, fi.Body), 68 + }) 69 + } 70 + 71 + func (s *IssueSyncer) mirrorRadicleToForgejo(ri radicle.Issue) error { 72 + existing, err := s.State.FindByRadicleID(s.RepoPair, "issue", ri.ID) 73 + if err != nil { 74 + return err 75 + } 76 + if existing != nil { 77 + return nil 78 + } 79 + 80 + fi, err := s.Forgejo.CreateIssue(ri.Title, ri.Body()+mirrorNotice) 81 + if err != nil { 82 + return fmt.Errorf("create forgejo issue: %w", err) 83 + } 84 + 85 + return s.State.Upsert(s.RepoPair, state.ItemMapping{ 86 + Kind: "issue", 87 + ForgejoID: fi.Index, 88 + RadicleID: ri.ID, 89 + ContentHash: hashText(ri.Title, ri.Body()), 90 + }) 91 + } 92 + 93 + func hashText(parts ...string) string { 94 + h := sha256.New() 95 + for _, p := range parts { 96 + h.Write([]byte(p)) 97 + h.Write([]byte{0}) 98 + } 99 + return hex.EncodeToString(h.Sum(nil)) 100 + }
+164
internal/sync/patches.go
··· 1 + package sync 2 + 3 + import ( 4 + "bytes" 5 + "fmt" 6 + "os" 7 + "os/exec" 8 + "regexp" 9 + "strings" 10 + 11 + "graft/internal/forgejo" 12 + "graft/internal/radicle" 13 + "graft/internal/state" 14 + ) 15 + 16 + // PatchSyncer mirrors Forgejo pull requests and Radicle patches. It reuses 17 + // the same working clone GitSyncer maintains, since a patch/PR can only be 18 + // opened once its head commit is reachable on the destination side. 19 + type PatchSyncer struct { 20 + RepoPair string 21 + WorkDir string 22 + RadHome string 23 + DefaultBranch string 24 + Forgejo *forgejo.Client 25 + Radicle *radicle.Client 26 + State *state.Store 27 + } 28 + 29 + func (s *PatchSyncer) git(args ...string) (string, error) { 30 + cmd := exec.Command("git", args...) 31 + cmd.Dir = s.WorkDir 32 + // Must start from the inherited environment, not a bare slice: git 33 + // needs PATH to resolve the git-remote-rad helper for rad:// remotes. 34 + cmd.Env = append(os.Environ(), "RAD_HOME="+s.RadHome) 35 + var out bytes.Buffer 36 + cmd.Stdout = &out 37 + cmd.Stderr = &out 38 + if err := cmd.Run(); err != nil { 39 + return out.String(), fmt.Errorf("git %v: %w: %s", args, err, out.String()) 40 + } 41 + return out.String(), nil 42 + } 43 + 44 + func (s *PatchSyncer) Sync() error { 45 + prs, err := s.Forgejo.ListPullRequests() 46 + if err != nil { 47 + return fmt.Errorf("list forgejo pull requests: %w", err) 48 + } 49 + patches, err := s.Radicle.ListPatches() 50 + if err != nil { 51 + return fmt.Errorf("list radicle patches: %w", err) 52 + } 53 + 54 + for _, pr := range prs { 55 + if err := s.mirrorForgejoToRadicle(pr); err != nil { 56 + return fmt.Errorf("mirror forgejo PR #%d: %w", pr.Index, err) 57 + } 58 + } 59 + for _, p := range patches { 60 + if err := s.mirrorRadicleToForgejo(p); err != nil { 61 + return fmt.Errorf("mirror radicle patch %s: %w", p.ID, err) 62 + } 63 + } 64 + return nil 65 + } 66 + 67 + var patchOpenedRe = regexp.MustCompile(`Patch ([0-9a-f]{40}) opened`) 68 + 69 + func (s *PatchSyncer) mirrorForgejoToRadicle(pr forgejo.PullRequest) error { 70 + existing, err := s.State.FindByForgejoID(s.RepoPair, "patch", pr.Index) 71 + if err != nil { 72 + return err 73 + } 74 + if existing != nil { 75 + return nil 76 + } 77 + 78 + // Bring the PR's head branch content into the local clone, then open a 79 + // patch from it via the pseudo-ref, exactly as verified interactively: 80 + // `git push rad HEAD:refs/patches`. 81 + if _, err := s.git("fetch", "-q", "forgejo", pr.Head.Ref); err != nil { 82 + return fmt.Errorf("fetch PR head: %w", err) 83 + } 84 + if _, err := s.git("checkout", "-q", "-B", localPRBranch(pr.Index), "FETCH_HEAD"); err != nil { 85 + return fmt.Errorf("checkout PR head: %w", err) 86 + } 87 + // git push -o values cannot contain newlines, unlike issue/PR bodies. 88 + message := pr.Title + " (mirrored automatically, do not edit here)" 89 + out, err := s.git("push", "rad", "-o", "patch.message="+message, "HEAD:refs/patches") 90 + // The working clone's mirroring never touches local branch refs (only 91 + // FETCH_HEAD and the remotes), so there may be no local default-branch 92 + // ref to switch back to yet: fetch and (re)create it rather than assume 93 + // it exists. 94 + if _, errFetch := s.git("fetch", "-q", "forgejo", s.DefaultBranch); errFetch != nil { 95 + return fmt.Errorf("fetch %s to restore: %w", s.DefaultBranch, errFetch) 96 + } 97 + if _, errCheckout := s.git("checkout", "-q", "-B", s.DefaultBranch, "FETCH_HEAD"); errCheckout != nil { 98 + return fmt.Errorf("checkout back to %s: %w", s.DefaultBranch, errCheckout) 99 + } 100 + if err != nil { 101 + return fmt.Errorf("open radicle patch: %w", err) 102 + } 103 + 104 + m := patchOpenedRe.FindStringSubmatch(out) 105 + if m == nil { 106 + return fmt.Errorf("could not parse patch id from: %q", out) 107 + } 108 + 109 + return s.State.Upsert(s.RepoPair, state.ItemMapping{ 110 + Kind: "patch", 111 + ForgejoID: pr.Index, 112 + RadicleID: m[1], 113 + ContentHash: hashText(pr.Title, pr.Body), 114 + }) 115 + } 116 + 117 + func (s *PatchSyncer) mirrorRadicleToForgejo(p radicle.Patch) error { 118 + existing, err := s.State.FindByRadicleID(s.RepoPair, "patch", p.ID) 119 + if err != nil { 120 + return err 121 + } 122 + if existing != nil { 123 + return nil 124 + } 125 + if len(p.Revisions) == 0 { 126 + return fmt.Errorf("patch has no revisions") 127 + } 128 + latest := p.Revisions[len(p.Revisions)-1] 129 + 130 + branch := localPatchBranch(p.ID) 131 + if _, err := s.git("fetch", "-q", "rad", latest.OID); err != nil { 132 + return fmt.Errorf("fetch patch revision: %w", err) 133 + } 134 + if _, err := s.git("branch", "-q", "-f", branch, "FETCH_HEAD"); err != nil { 135 + return fmt.Errorf("branch patch revision: %w", err) 136 + } 137 + if _, err := s.git("push", "-q", "forgejo", branch+":refs/heads/"+branch); err != nil { 138 + return fmt.Errorf("push branch to forgejo: %w", err) 139 + } 140 + 141 + pr, err := s.Forgejo.CreatePullRequest(p.Title, latest.Description+mirrorNotice, branch, s.DefaultBranch) 142 + if err != nil { 143 + return fmt.Errorf("create forgejo pull request: %w", err) 144 + } 145 + 146 + return s.State.Upsert(s.RepoPair, state.ItemMapping{ 147 + Kind: "patch", 148 + ForgejoID: pr.Index, 149 + RadicleID: p.ID, 150 + ContentHash: hashText(p.Title, latest.Description), 151 + }) 152 + } 153 + 154 + func localPRBranch(index int64) string { 155 + return fmt.Sprintf("sync/forgejo-pr-%d", index) 156 + } 157 + 158 + func localPatchBranch(radicleID string) string { 159 + short := radicleID 160 + if len(short) > 12 { 161 + short = short[:12] 162 + } 163 + return "sync/radicle-patch-" + strings.ToLower(short) 164 + }
+107
internal/sync/syncer.go
··· 1 + package sync 2 + 3 + import ( 4 + "fmt" 5 + "log/slog" 6 + "net/url" 7 + "path/filepath" 8 + 9 + "graft/internal/config" 10 + "graft/internal/forgejo" 11 + "graft/internal/radicle" 12 + "graft/internal/state" 13 + ) 14 + 15 + // RepoSyncer runs one repo pair's enabled sync scopes for one pass. 16 + type RepoSyncer struct { 17 + pair config.RepoPair 18 + forgejo *forgejo.Client 19 + radicle *radicle.Client 20 + git *GitSyncer 21 + issues *IssueSyncer 22 + patches *PatchSyncer 23 + } 24 + 25 + // New builds a RepoSyncer for one configured pair. workDir is where this 26 + // pair's local git mirror is kept, e.g. <state-dir>/<pair-name>. 27 + func New(pair config.RepoPair, st *state.Store, workDir string) (*RepoSyncer, error) { 28 + token, err := config.ReadToken(pair.Forgejo.TokenFile) 29 + if err != nil { 30 + return nil, err 31 + } 32 + fc := forgejo.New(pair.Forgejo.BaseURL, pair.Forgejo.Owner, pair.Forgejo.Repo, token) 33 + 34 + repo, err := fc.GetRepository() 35 + if err != nil { 36 + return nil, fmt.Errorf("resolve forgejo repository: %w", err) 37 + } 38 + 39 + rc := radicle.New(pair.Radicle.HTTPBaseURL, pair.Radicle.RID, pair.Radicle.RadHome, "rad") 40 + 41 + rs := &RepoSyncer{pair: pair, forgejo: fc, radicle: rc} 42 + 43 + if pair.Sync.Git || pair.Sync.Patches { 44 + rs.git = &GitSyncer{ 45 + RepoPair: pair.Name, 46 + WorkDir: workDir, 47 + ForgejoURL: authenticatedCloneURL(repo.CloneURL, token), 48 + ForgejoBranch: repo.DefaultBranch, 49 + RID: pair.Radicle.RID, 50 + RadHome: pair.Radicle.RadHome, 51 + State: st, 52 + } 53 + } 54 + if pair.Sync.Issues { 55 + rs.issues = &IssueSyncer{RepoPair: pair.Name, Forgejo: fc, Radicle: rc, State: st} 56 + } 57 + if pair.Sync.Patches { 58 + rs.patches = &PatchSyncer{ 59 + RepoPair: pair.Name, 60 + WorkDir: workDir, 61 + RadHome: pair.Radicle.RadHome, 62 + DefaultBranch: repo.DefaultBranch, 63 + Forgejo: fc, 64 + Radicle: rc, 65 + State: st, 66 + } 67 + } 68 + return rs, nil 69 + } 70 + 71 + // Run executes every enabled scope once, logging and continuing past 72 + // per-scope errors so one broken scope doesn't block the others. 73 + func (rs *RepoSyncer) Run(log *slog.Logger) { 74 + log = log.With("pair", rs.pair.Name) 75 + 76 + if rs.git != nil { 77 + if err := rs.git.Sync(); err != nil { 78 + log.Error("git sync failed", "err", err) 79 + } 80 + } 81 + if rs.issues != nil { 82 + if err := rs.issues.Sync(); err != nil { 83 + log.Error("issue sync failed", "err", err) 84 + } 85 + } 86 + if rs.patches != nil { 87 + if err := rs.patches.Sync(); err != nil { 88 + log.Error("patch sync failed", "err", err) 89 + } 90 + } 91 + } 92 + 93 + // authenticatedCloneURL embeds a token into an HTTPS clone URL the way 94 + // Forgejo expects (token as the basic-auth username). 95 + func authenticatedCloneURL(cloneURL, token string) string { 96 + u, err := url.Parse(cloneURL) 97 + if err != nil { 98 + return cloneURL 99 + } 100 + u.User = url.User(token) 101 + return u.String() 102 + } 103 + 104 + // WorkDirFor returns the per-pair git mirror directory under stateDir. 105 + func WorkDirFor(stateDir, pairName string) string { 106 + return filepath.Join(stateDir, "repos", pairName) 107 + }
+23
systemd/graft.service
··· 1 + [Unit] 2 + Description=graft - Forgejo <-> Radicle sync daemon 3 + After=network-online.target 4 + Wants=network-online.target 5 + 6 + [Service] 7 + Type=simple 8 + User=sync 9 + Group=sync 10 + ExecStart=/usr/local/bin/graft -config /etc/graft/config.yaml 11 + Restart=always 12 + RestartSec=10 13 + 14 + # Hardening: the daemon only needs its own state dir, its config dir (for 15 + # reading the token files) and the rad CLI's home directory. 16 + NoNewPrivileges=true 17 + ProtectSystem=strict 18 + ProtectHome=true 19 + ReadWritePaths=/var/lib/graft /home/sync/.radicle 20 + ReadOnlyPaths=/etc/graft 21 + 22 + [Install] 23 + WantedBy=multi-user.target