aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore3
-rw-r--r--LICENSE-APACHE202
-rw-r--r--LICENSE-MIT5
-rw-r--r--README.md95
-rw-r--r--assets/example_output.pngbin0 -> 114948 bytes
-rw-r--r--cmd/mugi/main.go50
-rw-r--r--config.example.yaml30
-rw-r--r--go.mod27
-rw-r--r--go.sum46
-rw-r--r--internal/cli/cli.go176
-rw-r--r--internal/config/config.go250
-rw-r--r--internal/git/git.go214
-rw-r--r--internal/remote/remote.go50
-rw-r--r--internal/ui/ui.go626
-rw-r--r--justfile14
15 files changed, 1788 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..daf278c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+/mugi
+config.yaml
+dev/
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..0e77b64
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,5 @@
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e3488d2
--- /dev/null
+++ b/README.md
@@ -0,0 +1,95 @@
+# Mugi
+
+> Personal **Mu**lti-**Gi**t Remote Manager
+
+Mugi keeps your repositories in sync across multiple Git remotes (GitHub, Codeberg, SourceHut, etc.)
+with a single command.
+
+Mugi is written in [Go](https://go.dev) and uses [Bubble Tea](https://github.com/charmbracelet/bubbletea)
+for its terminal interface.
+
+## Usage
+
+```bash
+mugi pull # Pull all repos from all remotes
+mugi pull windmark # Pull Windmark from all remotes
+mugi push windmark gh cb # Push Windmark to GitHub and Codeberg
+mugi fetch gemrest/september # Fetch specific repository
+```
+
+### Installation
+
+```bash
+go install github.com/Fuwn/mugi/cmd/mugi@main
+```
+
+or
+
+```bash
+git clone https://github.com/Fuwn/mugi.git
+cd mugi
+go build -o mugi ./cmd/mugi
+mv mugi ~/.local/bin/ # or anywhere in your PATH
+```
+
+### Configuration
+
+Mugi uses a YAML config file at `~/.config/mugi/config.yaml`:
+
+```yaml
+remotes:
+ github:
+ aliases: [gh]
+ url: [email protected]:${user}/${repo}.git
+ codeberg:
+ aliases: [cb]
+ url: [email protected]:${user}/${repo}.git
+ sourcehut:
+ aliases: [sh]
+ url: [email protected]:~fuwn/${repo}
+
+defaults:
+ remotes: [github, codeberg, sourcehut]
+ path_prefix: ~/Developer
+
+repos:
+ gemrest/windmark:
+ gemrest/september:
+```
+
+### `--help`
+
+```
+Mugi - Personal Multi-Git Remote Manager
+
+Usage:
+ mugi [flags] <command> [repo] [remotes...]
+
+Commands:
+ pull Pull from remote(s)
+ push Push to remote(s)
+ fetch Fetch from remote(s)
+ help Show this help
+ version Show version
+
+Flags:
+ -c, --config <path> Override config file path
+ -V, --verbose Show detailed output
+
+Examples:
+ mugi pull Pull all repositories from all remotes
+ mugi pull windmark Pull Windmark from all remotes
+ mugi pull windmark github Pull Windmark from GitHub only
+ mugi push windmark gh cb Push Windmark to GitHub and Codeberg
+ mugi fetch gemrest/september Fetch specific repository
+ mugi -c ./test.yaml pull Use custom config
+```
+
+## Licence
+
+Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
+[MIT license](LICENSE-MIT) at your option.
+
+Unless you explicitly state otherwise, any contribution intentionally submitted
+for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
+be dual licensed as above, without any additional terms or conditions.
diff --git a/assets/example_output.png b/assets/example_output.png
new file mode 100644
index 0000000..c0f36cc
--- /dev/null
+++ b/assets/example_output.png
Binary files differ
diff --git a/cmd/mugi/main.go b/cmd/mugi/main.go
new file mode 100644
index 0000000..6caed07
--- /dev/null
+++ b/cmd/mugi/main.go
@@ -0,0 +1,50 @@
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/ebisu/mugi/internal/cli"
+ "github.com/ebisu/mugi/internal/config"
+ "github.com/ebisu/mugi/internal/ui"
+)
+
+const version = "0.1.0"
+
+func main() {
+ if err := run(); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+func run() error {
+ cmd, err := cli.Parse(os.Args[1:])
+ if err != nil {
+ return err
+ }
+
+ if cmd.Help {
+ fmt.Println(cli.Usage())
+
+ return nil
+ }
+
+ if cmd.Version {
+ fmt.Printf("mugi %s\n", version)
+
+ return nil
+ }
+
+ cfg, err := config.Load(cmd.ConfigPath)
+ if err != nil {
+ return fmt.Errorf("config: %w", err)
+ }
+
+ tasks := ui.BuildTasks(cfg, cmd.Repo, cmd.Remotes)
+ if len(tasks) == 0 {
+ return fmt.Errorf("no matching repositories or remotes found")
+ }
+
+ return ui.Run(cmd.Operation, tasks, cmd.Verbose)
+}
diff --git a/config.example.yaml b/config.example.yaml
new file mode 100644
index 0000000..dc8ce4e
--- /dev/null
+++ b/config.example.yaml
@@ -0,0 +1,30 @@
+remotes:
+ github:
+ aliases: [gh]
+ url: [email protected]:${user}/${repo}.git
+ codeberg:
+ aliases: [cb]
+ url: [email protected]:${user}/${repo}.git
+ sourcehut:
+ aliases: [srht, sh]
+ url: [email protected]:~${user}/${repo}
+
+defaults:
+ remotes: [github, codeberg, sourcehut]
+ path_prefix: ~/Developer
+
+repos:
+ gemrest/windmark: {}
+
+ gemrest/september:
+ sourcehut:
+ user: fuwn
+
+ fuwn/dotfiles:
+ path: ~/.dotfiles
+
+ fuwn/private-project:
+ remotes: [github]
+
+ fuwn/fork:
+ github: [email protected]:upstream/original.git
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..305d0b7
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,27 @@
+module github.com/ebisu/mugi
+
+go 1.24.3
+
+require (
+ github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
+ github.com/charmbracelet/bubbles v0.21.0 // indirect
+ github.com/charmbracelet/bubbletea v1.3.10 // indirect
+ github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
+ github.com/charmbracelet/lipgloss v1.1.0 // indirect
+ github.com/charmbracelet/x/ansi v0.10.1 // indirect
+ github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
+ github.com/charmbracelet/x/term v0.2.1 // indirect
+ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
+ github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/mattn/go-localereader v0.0.1 // indirect
+ github.com/mattn/go-runewidth v0.0.16 // indirect
+ github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
+ github.com/muesli/cancelreader v0.2.2 // indirect
+ github.com/muesli/termenv v0.16.0 // indirect
+ github.com/rivo/uniseg v0.4.7 // indirect
+ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
+ golang.org/x/sys v0.36.0 // indirect
+ golang.org/x/text v0.3.8 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..ab83c1e
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,46 @@
+github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
+github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
+github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
+github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
+github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
+github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
+github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
+github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
+github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=
+github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
+github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=
+github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
+github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
+github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
+github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
+github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
+github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
+github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
+github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
+github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
+github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
+github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
+github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
+github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
+github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
+github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
+golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
+golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
+golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/internal/cli/cli.go b/internal/cli/cli.go
new file mode 100644
index 0000000..1ab54b2
--- /dev/null
+++ b/internal/cli/cli.go
@@ -0,0 +1,176 @@
+package cli
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/ebisu/mugi/internal/remote"
+)
+
+type Command struct {
+ Operation remote.Operation
+ Repo string
+ Remotes []string
+ ConfigPath string
+ Verbose bool
+ Help bool
+ Version bool
+}
+
+var ErrUnknownCommand = errors.New("unknown command")
+
+func Parse(args []string) (Command, error) {
+ cmd := Command{
+ Remotes: []string{remote.All},
+ }
+
+ if len(args) == 0 {
+ cmd.Help = true
+
+ return cmd, nil
+ }
+
+ args, cmd.ConfigPath = extractConfigFlag(args)
+ args, cmd.Verbose = extractVerboseFlag(args)
+
+ for _, arg := range args {
+ if arg == "-h" || arg == "--help" || arg == "help" {
+ cmd.Help = true
+
+ return cmd, nil
+ }
+
+ if arg == "-v" || arg == "--version" || arg == "version" {
+ cmd.Version = true
+
+ return cmd, nil
+ }
+ }
+
+ if len(args) == 0 {
+ cmd.Help = true
+
+ return cmd, nil
+ }
+
+ switch args[0] {
+ case "pull":
+ cmd.Operation = remote.Pull
+ case "push":
+ cmd.Operation = remote.Push
+ case "fetch":
+ cmd.Operation = remote.Fetch
+ default:
+ return cmd, fmt.Errorf("%w: %s", ErrUnknownCommand, args[0])
+ }
+
+ remaining := args[1:]
+
+ if len(remaining) == 0 {
+ cmd.Repo = remote.All
+
+ return cmd, nil
+ }
+
+ cmd.Repo = remaining[0]
+ remaining = remaining[1:]
+
+ if len(remaining) > 0 {
+ cmd.Remotes = remaining
+ }
+
+ return cmd, nil
+}
+
+func Usage() string {
+ return `Mugi - Personal Multi-Git Remote Manager
+
+Usage:
+ mugi [flags] <command> [repo] [remotes...]
+
+Commands:
+ pull Pull from remote(s)
+ push Push to remote(s)
+ fetch Fetch from remote(s)
+ help Show this help
+ version Show version
+
+Flags:
+ -c, --config <path> Override config file path
+ -V, --verbose Show detailed output
+
+Examples:
+ mugi pull Pull all repositories from all remotes
+ mugi pull windmark Pull Windmark from all remotes
+ mugi pull windmark github Pull Windmark from GitHub only
+ mugi push windmark gh cb Push Windmark to GitHub and Codeberg
+ mugi fetch gemrest/september Fetch specific repository
+ mugi -c ./test.yaml pull Use custom config
+
+Config: ` + configPath()
+}
+
+func configPath() string {
+ xdg := os.Getenv("XDG_CONFIG_HOME")
+
+ if xdg == "" {
+ home, _ := os.UserHomeDir()
+
+ return home + "/.config/mugi/config.yaml"
+ }
+
+ return xdg + "/mugi/config.yaml"
+}
+
+func extractConfigFlag(args []string) ([]string, string) {
+ var remaining []string
+ var configPath string
+
+ for i := 0; i < len(args); i++ {
+ arg := args[i]
+
+ if arg == "-c" || arg == "--config" {
+ if i+1 < len(args) {
+ configPath = args[i+1]
+ i++
+ }
+
+ continue
+ }
+
+ if v, ok := strings.CutPrefix(arg, "--config="); ok {
+ configPath = v
+
+ continue
+ }
+
+ if v, ok := strings.CutPrefix(arg, "-c"); ok && v != "" {
+ configPath = v
+
+ continue
+ }
+
+ remaining = append(remaining, arg)
+ }
+
+ return remaining, configPath
+}
+
+func extractVerboseFlag(args []string) ([]string, bool) {
+ var remaining []string
+ var verbose bool
+
+ for _, arg := range args {
+ if arg == "-V" || arg == "--verbose" {
+ verbose = true
+
+ continue
+ }
+
+ remaining = append(remaining, arg)
+ }
+
+ return remaining, verbose
+}
diff --git a/internal/config/config.go b/internal/config/config.go
new file mode 100644
index 0000000..9564b4e
--- /dev/null
+++ b/internal/config/config.go
@@ -0,0 +1,250 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+
+ "gopkg.in/yaml.v3"
+)
+
+type RemoteDefinition struct {
+ Aliases []string `yaml:"aliases"`
+ URL string `yaml:"url"`
+}
+
+type Defaults struct {
+ Remotes []string `yaml:"remotes"`
+ PathPrefix string `yaml:"path_prefix"`
+}
+
+type RepoRemotes map[string]string
+
+type Repo struct {
+ Path string
+ Remotes RepoRemotes
+}
+
+type Config struct {
+ Remotes map[string]RemoteDefinition
+ Defaults Defaults
+ Repos map[string]Repo
+}
+
+type rawConfig struct {
+ Remotes map[string]RemoteDefinition `yaml:"remotes"`
+ Defaults Defaults `yaml:"defaults"`
+ Repos map[string]yaml.Node `yaml:"repos"`
+}
+
+type remoteOverride struct {
+ User string `yaml:"user"`
+ Repo string `yaml:"repo"`
+}
+
+func Load(override string) (Config, error) {
+ path := override
+
+ if path == "" {
+ var err error
+
+ path, err = Path()
+ if err != nil {
+ return Config{}, err
+ }
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return Config{}, err
+ }
+
+ var raw rawConfig
+
+ if err := yaml.Unmarshal(data, &raw); err != nil {
+ return Config{}, err
+ }
+
+ return expand(raw)
+}
+
+func expand(raw rawConfig) (Config, error) {
+ cfg := Config{
+ Remotes: raw.Remotes,
+ Defaults: raw.Defaults,
+ Repos: make(map[string]Repo),
+ }
+
+ for name, node := range raw.Repos {
+ repo, err := expandRepo(name, node, raw)
+ if err != nil {
+ return Config{}, err
+ }
+
+ cfg.Repos[name] = repo
+ }
+
+ return cfg, nil
+}
+
+func expandRepo(name string, node yaml.Node, raw rawConfig) (Repo, error) {
+ user, repoName := splitRepoName(name)
+ repo := Repo{
+ Remotes: make(RepoRemotes),
+ }
+
+ var parsed map[string]yaml.Node
+
+ if err := node.Decode(&parsed); err != nil {
+ parsed = make(map[string]yaml.Node)
+ }
+
+ if pathNode, ok := parsed["path"]; ok {
+ var path string
+
+ pathNode.Decode(&path)
+
+ repo.Path = path
+ } else if raw.Defaults.PathPrefix != "" {
+ repo.Path = filepath.Join(raw.Defaults.PathPrefix, repoName)
+ }
+
+ remoteList := raw.Defaults.Remotes
+
+ if remotesNode, ok := parsed["remotes"]; ok {
+ var list []string
+
+ if err := remotesNode.Decode(&list); err == nil {
+ remoteList = list
+ } else {
+ var oldStyle map[string]string
+
+ if err := remotesNode.Decode(&oldStyle); err == nil {
+ repo.Remotes = oldStyle
+
+ return repo, nil
+ }
+ }
+ }
+
+ for _, remoteName := range remoteList {
+ remoteUser, remoteRepo := user, repoName
+
+ if overrideNode, ok := parsed[remoteName]; ok {
+ var override remoteOverride
+
+ if err := overrideNode.Decode(&override); err == nil {
+ if override.User != "" {
+ remoteUser = override.User
+ }
+
+ if override.Repo != "" {
+ remoteRepo = override.Repo
+ }
+ } else {
+ var urlOverride string
+
+ if err := overrideNode.Decode(&urlOverride); err == nil {
+ repo.Remotes[remoteName] = urlOverride
+
+ continue
+ }
+ }
+ }
+
+ if def, ok := raw.Remotes[remoteName]; ok && def.URL != "" {
+ url := expandURL(def.URL, remoteUser, remoteRepo)
+
+ repo.Remotes[remoteName] = url
+ }
+ }
+
+ return repo, nil
+}
+
+func expandURL(template, user, repo string) string {
+ url := strings.ReplaceAll(template, "${user}", user)
+ url = strings.ReplaceAll(url, "${repo}", repo)
+
+ return url
+}
+
+func splitRepoName(name string) (user, repo string) {
+ parts := strings.SplitN(name, "/", 2)
+
+ if len(parts) == 2 {
+ return parts[0], parts[1]
+ }
+
+ return "", parts[0]
+}
+
+func Path() (string, error) {
+ configDir := os.Getenv("XDG_CONFIG_HOME")
+
+ if configDir == "" {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+
+ configDir = filepath.Join(home, ".config")
+ }
+
+ return filepath.Join(configDir, "mugi", "config.yaml"), nil
+}
+
+func (c Config) FindRepo(name string) (string, Repo, bool) {
+ if repo, ok := c.Repos[name]; ok {
+ return name, repo, true
+ }
+
+ var matches []string
+
+ for fullName := range c.Repos {
+ repoName := filepath.Base(fullName)
+
+ if repoName == name {
+ matches = append(matches, fullName)
+ }
+ }
+
+ if len(matches) == 1 {
+ return matches[0], c.Repos[matches[0]], true
+ }
+
+ return "", Repo{}, false
+}
+
+func (c Config) AllRepos() []string {
+ repos := make([]string, 0, len(c.Repos))
+
+ for name := range c.Repos {
+ repos = append(repos, name)
+ }
+
+ return repos
+}
+
+func (c Config) ResolveAlias(alias string) string {
+ for name, def := range c.Remotes {
+ if name == alias || slices.Contains(def.Aliases, alias) {
+ return name
+ }
+ }
+
+ return alias
+}
+
+func (r Repo) ExpandPath() string {
+ path := r.Path
+
+ if len(path) > 0 && path[0] == '~' {
+ if home, err := os.UserHomeDir(); err == nil {
+ path = filepath.Join(home, path[1:])
+ }
+ }
+
+ return path
+}
diff --git a/internal/git/git.go b/internal/git/git.go
new file mode 100644
index 0000000..13e9cb2
--- /dev/null
+++ b/internal/git/git.go
@@ -0,0 +1,214 @@
+package git
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "strings"
+
+ "github.com/ebisu/mugi/internal/remote"
+)
+
+const sshEnv = "GIT_SSH_COMMAND=ssh -o StrictHostKeyChecking=accept-new"
+
+func gitEnv() []string {
+ return append(os.Environ(), sshEnv)
+}
+
+type Result struct {
+ Repo string
+ Remote string
+ Output string
+ Error error
+ ExitCode int
+}
+
+func (r *Result) setError(err error) {
+ r.Error = err
+
+ var exitErr *exec.ExitError
+
+ if errors.As(err, &exitErr) {
+ r.ExitCode = exitErr.ExitCode()
+ } else {
+ r.ExitCode = 1
+ }
+
+ if r.Output == "" {
+ r.Output = err.Error()
+ }
+}
+
+func Execute(ctx context.Context, op remote.Operation, repoPath, remoteName string) Result {
+ result := Result{
+ Repo: repoPath,
+ Remote: remoteName,
+ }
+
+ args := buildArgs(op, remoteName, repoPath)
+ cmd := exec.CommandContext(ctx, "git", args...)
+ cmd.Dir = repoPath
+ cmd.Env = gitEnv()
+
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+
+ err := cmd.Run()
+ result.Output = strings.TrimSpace(stdout.String() + stderr.String())
+
+ if err != nil {
+ result.setError(err)
+ }
+
+ return result
+}
+
+func buildArgs(op remote.Operation, remoteName, repoPath string) []string {
+ switch op {
+ case remote.Pull:
+ branch := currentBranch(repoPath)
+ if branch == "" {
+ branch = "HEAD"
+ }
+ return []string{"pull", remoteName, branch}
+ case remote.Push:
+ return []string{"push", remoteName}
+ case remote.Fetch:
+ return []string{"fetch", remoteName}
+ default:
+ return []string{}
+ }
+}
+
+func currentBranch(repoPath string) string {
+ cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
+ cmd.Dir = repoPath
+
+ out, err := cmd.Output()
+ if err != nil {
+ return ""
+ }
+
+ return strings.TrimSpace(string(out))
+}
+
+func IsRepo(path string) bool {
+ cmd := exec.Command("git", "rev-parse", "--git-dir")
+ cmd.Dir = path
+
+ return cmd.Run() == nil
+}
+
+func Clone(ctx context.Context, url, path string) Result {
+ result := Result{
+ Repo: path,
+ Remote: "origin",
+ }
+
+ cmd := exec.CommandContext(ctx, "git", "clone", url, path)
+ cmd.Env = gitEnv()
+
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+
+ err := cmd.Run()
+ result.Output = strings.TrimSpace(stdout.String() + stderr.String())
+
+ if err != nil {
+ result.setError(err)
+ }
+
+ return result
+}
+
+func AddRemote(ctx context.Context, repoPath, name, url string) Result {
+ result := Result{
+ Repo: repoPath,
+ Remote: name,
+ }
+
+ cmd := exec.CommandContext(ctx, "git", "remote", "add", name, url)
+ cmd.Dir = repoPath
+
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+
+ err := cmd.Run()
+ result.Output = strings.TrimSpace(stdout.String() + stderr.String())
+
+ if err != nil {
+ result.setError(err)
+ }
+
+ return result
+}
+
+func RenameRemote(ctx context.Context, repoPath, oldName, newName string) Result {
+ result := Result{
+ Repo: repoPath,
+ Remote: newName,
+ }
+
+ cmd := exec.CommandContext(ctx, "git", "remote", "rename", oldName, newName)
+ cmd.Dir = repoPath
+
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+
+ err := cmd.Run()
+ result.Output = strings.TrimSpace(stdout.String() + stderr.String())
+
+ if err != nil {
+ result.setError(err)
+ }
+
+ return result
+}
+
+func HasRemote(repoPath, name string) bool {
+ cmd := exec.Command("git", "remote", "get-url", name)
+ cmd.Dir = repoPath
+
+ return cmd.Run() == nil
+}
+
+func SetRemoteURL(ctx context.Context, repoPath, name, url string) Result {
+ result := Result{
+ Repo: repoPath,
+ Remote: name,
+ }
+
+ cmd := exec.CommandContext(ctx, "git", "remote", "set-url", name, url)
+ cmd.Dir = repoPath
+
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+
+ err := cmd.Run()
+ result.Output = strings.TrimSpace(stdout.String() + stderr.String())
+
+ if err != nil {
+ result.setError(err)
+ }
+
+ return result
+}
+
+func GetRemoteURL(repoPath, name string) string {
+ cmd := exec.Command("git", "remote", "get-url", name)
+ cmd.Dir = repoPath
+
+ out, err := cmd.Output()
+ if err != nil {
+ return ""
+ }
+
+ return strings.TrimSpace(string(out))
+}
diff --git a/internal/remote/remote.go b/internal/remote/remote.go
new file mode 100644
index 0000000..7280c66
--- /dev/null
+++ b/internal/remote/remote.go
@@ -0,0 +1,50 @@
+package remote
+
+type Operation int
+
+const (
+ Pull Operation = iota
+ Push
+ Fetch
+)
+
+func (o Operation) String() string {
+ switch o {
+ case Pull:
+ return "pull"
+ case Push:
+ return "push"
+ case Fetch:
+ return "fetch"
+ default:
+ return "unknown"
+ }
+}
+
+func (o Operation) Verb() string {
+ switch o {
+ case Pull:
+ return "Pulling"
+ case Push:
+ return "Pushing"
+ case Fetch:
+ return "Fetching"
+ default:
+ return "Operating"
+ }
+}
+
+func (o Operation) PastTense() string {
+ switch o {
+ case Pull:
+ return "Pulled"
+ case Push:
+ return "Pushed"
+ case Fetch:
+ return "Fetched"
+ default:
+ return "Completed"
+ }
+}
+
+const All = "all"
diff --git a/internal/ui/ui.go b/internal/ui/ui.go
new file mode 100644
index 0000000..cee3442
--- /dev/null
+++ b/internal/ui/ui.go
@@ -0,0 +1,626 @@
+package ui
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/charmbracelet/bubbles/spinner"
+ tea "github.com/charmbracelet/bubbletea"
+ "github.com/charmbracelet/lipgloss"
+ "github.com/ebisu/mugi/internal/config"
+ "github.com/ebisu/mugi/internal/git"
+ "github.com/ebisu/mugi/internal/remote"
+)
+
+type Task struct {
+ RepoName string
+ RemoteName string
+ RemoteURL string
+ RepoPath string
+ Op remote.Operation
+}
+
+type taskState int
+
+const (
+ taskPending taskState = iota
+ taskRunning
+ taskSuccess
+ taskFailed
+)
+
+type taskResult struct {
+ task Task
+ result git.Result
+}
+
+type Model struct {
+ tasks []Task
+ states map[string]taskState
+ results map[string]git.Result
+ spinner spinner.Model
+ operation remote.Operation
+ verbose bool
+ done bool
+}
+
+func NewModel(op remote.Operation, tasks []Task, verbose bool) Model {
+ s := spinner.New()
+ s.Spinner = spinner.Dot
+ s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
+
+ states := make(map[string]taskState)
+
+ for _, t := range tasks {
+ states[taskKey(t)] = taskPending
+ }
+
+ return Model{
+ tasks: tasks,
+ states: states,
+ results: make(map[string]git.Result),
+ spinner: s,
+ operation: op,
+ verbose: verbose,
+ }
+}
+
+func taskKey(t Task) string {
+ return t.RepoName + ":" + t.RemoteName
+}
+
+func (m Model) Init() tea.Cmd {
+ cmds := []tea.Cmd{m.spinner.Tick}
+
+ for _, task := range m.tasks {
+ cmds = append(cmds, m.runTask(task))
+ }
+
+ return tea.Batch(cmds...)
+}
+
+func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ switch msg := msg.(type) {
+ case tea.KeyMsg:
+ switch msg.String() {
+ case "q", "ctrl+c":
+ return m, tea.Quit
+ }
+
+ case spinner.TickMsg:
+ var cmd tea.Cmd
+ m.spinner, cmd = m.spinner.Update(msg)
+
+ return m, cmd
+
+ case taskResult:
+ key := taskKey(msg.task)
+ if msg.result.Error != nil {
+ m.states[key] = taskFailed
+ } else {
+ m.states[key] = taskSuccess
+ }
+ m.results[key] = msg.result
+
+ if m.allDone() {
+ m.done = true
+ return m, tea.Quit
+ }
+ }
+
+ return m, nil
+}
+
+func (m Model) View() string {
+ var b strings.Builder
+
+ title := lipgloss.NewStyle().
+ Bold(true).
+ Foreground(lipgloss.Color("212")).
+ Render(fmt.Sprintf("%s repositories", m.operation.Verb()))
+
+ b.WriteString(title + "\n\n")
+
+ successStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("42"))
+ failStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("196"))
+ dimStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
+
+ for _, task := range m.tasks {
+ key := taskKey(task)
+ state := m.states[key]
+
+ var status string
+ switch state {
+ case taskPending:
+ status = dimStyle.Render("○")
+ case taskRunning:
+ status = m.spinner.View()
+ case taskSuccess:
+ status = successStyle.Render("✓")
+ case taskFailed:
+ status = failStyle.Render("✗")
+ }
+
+ repoName := filepath.Base(task.RepoName)
+ line := fmt.Sprintf("%s %s → %s", status, repoName, task.RemoteName)
+
+ if result, ok := m.results[key]; ok && result.Output != "" {
+ if m.verbose {
+ line += "\n" + indentOutput(result.Output, dimStyle)
+ } else if state == taskFailed {
+ line += dimStyle.Render(" " + firstLine(result.Output))
+ }
+ }
+
+ b.WriteString(line + "\n")
+ }
+
+ if m.done {
+ b.WriteString("\n")
+ success, failed := m.summary()
+ if failed > 0 {
+ b.WriteString(failStyle.Render(fmt.Sprintf("%d failed", failed)))
+ b.WriteString(", ")
+ }
+ b.WriteString(successStyle.Render(fmt.Sprintf("%d succeeded", success)))
+ b.WriteString("\n")
+ }
+
+ return b.String()
+}
+
+func (m *Model) runTask(task Task) tea.Cmd {
+ return func() tea.Msg {
+ op := task.Op
+
+ if op == 0 {
+ op = m.operation
+ }
+
+ result := git.Execute(context.Background(), op, task.RepoPath, task.RemoteName)
+
+ return taskResult{task: task, result: result}
+ }
+}
+
+func (m Model) allDone() bool {
+ for _, state := range m.states {
+ if state == taskPending || state == taskRunning {
+ return false
+ }
+ }
+
+ return true
+}
+
+func (m Model) summary() (success, failed int) {
+ for _, state := range m.states {
+ switch state {
+ case taskSuccess:
+ success++
+ case taskFailed:
+ failed++
+ }
+ }
+ return
+}
+
+func firstLine(s string) string {
+ if idx := strings.Index(s, "\n"); idx != -1 {
+ return s[:idx]
+ }
+
+ return s
+}
+
+func indentOutput(s string, style lipgloss.Style) string {
+ lines := strings.Split(s, "\n")
+
+ for i, line := range lines {
+ lines[i] = " " + style.Render(line)
+ }
+
+ return strings.Join(lines, "\n")
+}
+
+func Run(op remote.Operation, tasks []Task, verbose bool) error {
+ if op == remote.Pull {
+ inits := NeedsInit(tasks)
+ if len(inits) > 0 {
+ if err := runInit(inits, verbose); err != nil {
+ return err
+ }
+ }
+ }
+
+ syncRemotes(tasks)
+
+ if op == remote.Pull {
+ tasks = adjustPullTasks(tasks)
+ }
+
+ model := NewModel(op, tasks, verbose)
+ p := tea.NewProgram(model)
+
+ _, err := p.Run()
+
+ return err
+}
+
+func syncRemotes(tasks []Task) {
+ ctx := context.Background()
+ seen := make(map[string]bool)
+
+ for _, task := range tasks {
+ key := task.RepoPath + ":" + task.RemoteName
+
+ if seen[key] {
+ continue
+ }
+
+ seen[key] = true
+
+ if !git.IsRepo(task.RepoPath) {
+ continue
+ }
+
+ currentURL := git.GetRemoteURL(task.RepoPath, task.RemoteName)
+
+ if currentURL == "" {
+ git.AddRemote(ctx, task.RepoPath, task.RemoteName, task.RemoteURL)
+ } else if currentURL != task.RemoteURL {
+ git.SetRemoteURL(ctx, task.RepoPath, task.RemoteName, task.RemoteURL)
+ }
+ }
+}
+
+func adjustPullTasks(tasks []Task) []Task {
+ firstPerRepo := make(map[string]bool)
+ result := make([]Task, len(tasks))
+
+ for i, task := range tasks {
+ result[i] = task
+
+ if firstPerRepo[task.RepoPath] {
+ result[i].Op = remote.Fetch
+ } else {
+ result[i].Op = remote.Pull
+ firstPerRepo[task.RepoPath] = true
+ }
+ }
+
+ return result
+}
+
+func runInit(inits []RepoInit, verbose bool) error {
+ model := NewInitModel(inits, verbose)
+ p := tea.NewProgram(model)
+
+ m, err := p.Run()
+ if err != nil {
+ return err
+ }
+
+ if initModel, ok := m.(InitModel); ok {
+ for _, state := range initModel.states {
+ if state == taskFailed {
+ return fmt.Errorf("repository initialisation failed")
+ }
+ }
+ }
+
+ return nil
+}
+
+func BuildTasks(cfg config.Config, repoName string, remoteNames []string) []Task {
+ var tasks []Task
+
+ repos := resolveRepos(cfg, repoName)
+
+ for _, fullName := range repos {
+ repo := cfg.Repos[fullName]
+ remotes := resolveRemotes(cfg, repo, remoteNames)
+
+ for _, remoteName := range remotes {
+ if url, ok := repo.Remotes[remoteName]; ok {
+ tasks = append(tasks, Task{
+ RepoName: fullName,
+ RemoteName: remoteName,
+ RemoteURL: url,
+ RepoPath: repo.ExpandPath(),
+ })
+ }
+ }
+ }
+
+ return tasks
+}
+
+type RepoInit struct {
+ Name string
+ Path string
+ Remotes map[string]string
+}
+
+type InitResult struct {
+ Repo string
+ Output string
+ Error error
+ Success bool
+}
+
+type initTaskResult struct {
+ init RepoInit
+ result InitResult
+}
+
+type InitModel struct {
+ inits []RepoInit
+ states map[string]taskState
+ results map[string]InitResult
+ spinner spinner.Model
+ verbose bool
+ done bool
+}
+
+func NewInitModel(inits []RepoInit, verbose bool) InitModel {
+ s := spinner.New()
+ s.Spinner = spinner.Dot
+ s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
+
+ states := make(map[string]taskState)
+
+ for _, init := range inits {
+ states[init.Path] = taskPending
+ }
+
+ return InitModel{
+ inits: inits,
+ states: states,
+ results: make(map[string]InitResult),
+ spinner: s,
+ verbose: verbose,
+ }
+}
+
+func (m InitModel) Init() tea.Cmd {
+ cmds := []tea.Cmd{m.spinner.Tick}
+
+ for _, init := range m.inits {
+ cmds = append(cmds, m.runInit(init))
+ }
+
+ return tea.Batch(cmds...)
+}
+
+func (m InitModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ switch msg := msg.(type) {
+ case tea.KeyMsg:
+ switch msg.String() {
+ case "q", "ctrl+c":
+ return m, tea.Quit
+ }
+
+ case spinner.TickMsg:
+ var cmd tea.Cmd
+ m.spinner, cmd = m.spinner.Update(msg)
+
+ return m, cmd
+
+ case initTaskResult:
+ if msg.result.Success {
+ m.states[msg.init.Path] = taskSuccess
+ } else {
+ m.states[msg.init.Path] = taskFailed
+ }
+ m.results[msg.init.Path] = msg.result
+
+ if m.allDone() {
+ m.done = true
+ return m, tea.Quit
+ }
+ }
+
+ return m, nil
+}
+
+func (m InitModel) View() string {
+ var b strings.Builder
+
+ title := lipgloss.NewStyle().
+ Bold(true).
+ Foreground(lipgloss.Color("212")).
+ Render("Initialising repositories")
+
+ b.WriteString(title + "\n\n")
+
+ successStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("42"))
+ failStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("196"))
+ dimStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
+
+ for _, init := range m.inits {
+ state := m.states[init.Path]
+
+ var status string
+ switch state {
+ case taskPending:
+ status = dimStyle.Render("○")
+ case taskRunning:
+ status = m.spinner.View()
+ case taskSuccess:
+ status = successStyle.Render("✓")
+ case taskFailed:
+ status = failStyle.Render("✗")
+ }
+
+ repoName := filepath.Base(init.Name)
+ line := fmt.Sprintf("%s %s", status, repoName)
+
+ if result, ok := m.results[init.Path]; ok && result.Output != "" {
+ if m.verbose || !result.Success {
+ line += "\n" + indentOutput(result.Output, dimStyle)
+ }
+ }
+
+ b.WriteString(line + "\n")
+ }
+
+ if m.done {
+ b.WriteString("\n")
+ }
+
+ return b.String()
+}
+
+func (m *InitModel) runInit(init RepoInit) tea.Cmd {
+ return func() tea.Msg {
+ result := InitRepo(context.Background(), init)
+
+ return initTaskResult{init: init, result: result}
+ }
+}
+
+func (m InitModel) allDone() bool {
+ for _, state := range m.states {
+ if state == taskPending || state == taskRunning {
+ return false
+ }
+ }
+
+ return true
+}
+
+func NeedsInit(tasks []Task) []RepoInit {
+ seen := make(map[string]bool)
+
+ var inits []RepoInit
+
+ for _, task := range tasks {
+ if seen[task.RepoPath] {
+ continue
+ }
+
+ seen[task.RepoPath] = true
+
+ if _, err := os.Stat(task.RepoPath); os.IsNotExist(err) {
+ inits = append(inits, collectRepoInit(tasks, task.RepoPath, task.RepoName))
+
+ continue
+ }
+
+ if !git.IsRepo(task.RepoPath) {
+ inits = append(inits, collectRepoInit(tasks, task.RepoPath, task.RepoName))
+ }
+ }
+
+ return inits
+}
+
+func collectRepoInit(tasks []Task, path, name string) RepoInit {
+ remotes := make(map[string]string)
+
+ for _, t := range tasks {
+ if t.RepoPath == path {
+ remotes[t.RemoteName] = t.RemoteURL
+ }
+ }
+
+ return RepoInit{Name: name, Path: path, Remotes: remotes}
+}
+
+func InitRepo(ctx context.Context, init RepoInit) InitResult {
+ result := InitResult{Repo: init.Name}
+
+ var firstRemote, firstURL string
+
+ for name, url := range init.Remotes {
+ firstRemote = name
+ firstURL = url
+
+ break
+ }
+
+ if err := os.MkdirAll(filepath.Dir(init.Path), 0o755); err != nil {
+ result.Error = err
+ result.Output = err.Error()
+
+ return result
+ }
+
+ cloneResult := git.Clone(ctx, firstURL, init.Path)
+
+ if cloneResult.Error != nil {
+ result.Error = cloneResult.Error
+ result.Output = cloneResult.Output
+
+ return result
+ }
+
+ outputs := []string{fmt.Sprintf("Cloned from %s", firstRemote)}
+
+ renameResult := git.RenameRemote(ctx, init.Path, "origin", firstRemote)
+
+ if renameResult.Error != nil {
+ result.Error = renameResult.Error
+ result.Output = renameResult.Output
+
+ return result
+ }
+
+ for name, url := range init.Remotes {
+ if name == firstRemote {
+ continue
+ }
+
+ addResult := git.AddRemote(ctx, init.Path, name, url)
+
+ if addResult.Error != nil {
+ result.Error = addResult.Error
+ result.Output = addResult.Output
+
+ return result
+ }
+
+ outputs = append(outputs, fmt.Sprintf("Added remote %s", name))
+ }
+
+ result.Success = true
+ result.Output = strings.Join(outputs, "\n")
+
+ return result
+}
+
+func resolveRepos(cfg config.Config, name string) []string {
+ if name == remote.All {
+ return cfg.AllRepos()
+ }
+
+ if fullName, _, ok := cfg.FindRepo(name); ok {
+ return []string{fullName}
+ }
+
+ return nil
+}
+
+func resolveRemotes(cfg config.Config, repo config.Repo, names []string) []string {
+ if len(names) == 1 && names[0] == remote.All {
+ remotes := make([]string, 0, len(repo.Remotes))
+
+ for name := range repo.Remotes {
+ remotes = append(remotes, name)
+ }
+
+ return remotes
+ }
+
+ resolved := make([]string, 0, len(names))
+
+ for _, name := range names {
+ resolved = append(resolved, cfg.ResolveAlias(name))
+ }
+
+ return resolved
+}
diff --git a/justfile b/justfile
new file mode 100644
index 0000000..b1530db
--- /dev/null
+++ b/justfile
@@ -0,0 +1,14 @@
+name := "mugi"
+format_command := "~/go/bin/gofumpt -l -w ."
+
+default:
+ just --list
+
+fmt:
+ {{ format_command }}
+
+run *arguments="":
+ go run ./cmd/{{ name }} {{ arguments }}
+
+build:
+ go build -o {{ name }} ./cmd/{{ name }}