-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.rs
More file actions
456 lines (441 loc) · 13.6 KB
/
Copy pathmain.rs
File metadata and controls
456 lines (441 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use clap::{Parser, Subcommand};
use gitopolis::exec::exec;
use gitopolis::git::GitImpl;
use gitopolis::gitopolis::Gitopolis;
use gitopolis::repos::Repo;
use gitopolis::storage::StorageImpl;
use gitopolis::tag_filter::TagFilter;
use log::LevelFilter;
use std::collections::BTreeMap;
use std::io::Write;
/// A CLI tool for managing multiple git repositories
/// License: A-GPL v3.0
/// Repo: https://github.com/timabell/gitopolis
#[derive(Parser)]
#[clap(author, version, subcommand_required = true, verbatim_doc_comment)]
struct Args {
#[clap(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand)]
enum Commands {
/// Add one or more git repos to manage.
Add {
#[clap(required = true)]
repo_folders: Vec<String>,
},
/// Remove one or more git repos from gitopolis's list. Leaves actual repo on filesystem alone.
Remove {
#[clap(required = true)]
repo_folders: Vec<String>,
},
/// Show list of repos gitopolis knows about. Use "long" to see tags and urls (tab separated format).
List {
/// Filter by tags. Comma-separated tags use AND logic (e.g., "foo,bar" = foo AND bar).
/// Multiple --tag flags use OR logic (e.g., "--tag foo,bar --tag baz" = (foo AND bar) OR baz).
#[arg(short, long)]
tag: Vec<String>,
#[clap(short, long)]
long: bool,
},
/// Run any shell command. E.g. `gitopolis exec -- git pull`. Double-dash separator indicates end of gitopolis's arguments and prevents arguments to your commands being interpreted by gitopolis.
Exec {
/// Filter by tags. Comma-separated tags use AND logic (e.g., "foo,bar" = foo AND bar).
/// Multiple --tag flags use OR logic (e.g., "--tag foo,bar --tag baz" = (foo AND bar) OR baz).
#[arg(short, long)]
tag: Vec<String>,
#[arg(long)]
oneline: bool,
/// Don't output repo name when no stdout/stderr output produced
#[arg(long)]
skip_blank: bool,
exec_args: Vec<String>,
},
/// Add/remove repo tags. Use tags to organise repos and allow running commands against subsets of the repo list. Supports comma-separated tag lists (e.g., "tag1,tag2,tag3").
Tag {
/// Remove this tag from these repo_folders. If no repos specified, removes from ALL repos.
#[clap(short, long)]
remove: bool,
#[clap(required = true)]
tag: String,
repo_folders: Vec<String>,
},
/// List known tags. Use "long" to list repos per tag.
Tags {
#[clap(short, long)]
long: bool,
},
/// Clone repository from URL and add to gitopolis, or clone all configured repos from .gitopolis.toml.
/// This command behaves in two very different ways depending on whether a remote url was provided:
/// If URL is provided: clones from that URL, extracts repo name, adds to gitopolis (optionally with tags).
/// If URL is omitted: clones all repos from .gitopolis.toml (filtered by --tag if specified) skipping existing folders. (Useful for setting up new machines/developers from an existing team configuration)
Clone {
/// Optional git URL to clone from (e.g., git@github.com:user/repo.git or https://github.com/user/repo).
/// If omitted, clones repos defined in .gitopolis.toml configuration
url: Option<String>,
/// Optional addition to URL - target directory name to clone this url into (like git clone). If omitted, extracts name from URL
target_dir: Option<String>,
/// When cloning from URL, all specified tags are applied to the new repo.
/// When cloning without URL from existing config,
/// filters repos to clone from configuration by tags; comma-separated tags use AND logic (e.g., "foo,bar" = foo AND bar),
/// multiple --tag flags use OR logic (e.g., "--tag foo,bar --tag baz" = (foo AND bar) OR baz).
#[arg(short, long)]
tag: Vec<String>,
},
/// Sync remotes between git repositories and .gitopolis.toml configuration
Sync {
/// Update .gitopolis.toml from remotes in git repositories
#[arg(long, conflicts_with = "write_remotes")]
read_remotes: bool,
/// Update git repositories with remotes from .gitopolis.toml (adds missing remotes and updates URLs, but will not remove any remotes)
#[arg(long, conflicts_with = "read_remotes")]
write_remotes: bool,
/// Show what would be changed without making any modifications
#[arg(long)]
dry_run: bool,
/// Filter by tags. Comma-separated tags use AND logic (e.g., "foo,bar" = foo AND bar).
/// Multiple --tag flags use OR logic (e.g., "--tag foo,bar --tag baz" = (foo AND bar) OR baz).
#[arg(short, long)]
tag: Vec<String>,
},
/// Show detailed information about a repository including tags and remotes
Show {
#[clap(required = true)]
repo_folder: String,
},
/// Move a repository to a new location, updating gitopolis configuration
Move {
#[clap(subcommand)]
entity: MoveEntity,
},
/// Rename a tag or other entity
Rename {
#[clap(subcommand)]
entity: RenameEntity,
},
}
#[derive(Subcommand)]
enum MoveEntity {
/// Move a repository to a new location
Repo {
/// Current path of the repository
old_path: String,
/// New path for the repository
new_path: String,
},
}
#[derive(Subcommand)]
enum RenameEntity {
/// Rename a tag across all repos. Use --merge if some repos already have the new tag.
Tag {
/// Current tag name
old_name: String,
/// New tag name
new_name: String,
/// Allow renaming even if some repos already have the new tag
#[clap(long)]
merge: bool,
},
}
fn main() {
env_logger::builder()
.format(|buf, record| writeln!(buf, "{}", record.args())) // turn off log decorations https://docs.rs/env_logger/0.9.0/env_logger/#using-a-custom-format
.filter(None, LevelFilter::Info) // turn on log output
.init();
match &Args::parse_from(wild::args()).command {
Some(Commands::Add { repo_folders }) => add(repo_folders.to_owned()),
Some(Commands::Remove { repo_folders }) => {
init_gitopolis()
.remove(repo_folders)
.expect("Failed to remove repository");
}
Some(Commands::List {
tag: tag_args,
long,
}) => {
let filter = TagFilter::from_cli_args(tag_args);
list(
init_gitopolis()
.list(&filter)
.expect("Failed to list repositories"),
*long,
)
}
Some(Commands::Clone {
url,
target_dir,
tag: tag_args,
}) => clone(url, target_dir, tag_args),
Some(Commands::Exec {
tag: tag_args,
oneline,
skip_blank,
exec_args,
}) => {
let filter = TagFilter::from_cli_args(tag_args);
exec(
exec_args.to_owned(),
init_gitopolis()
.list(&filter)
.expect("Failed to list repositories for exec"),
*oneline,
*skip_blank,
);
}
Some(Commands::Tag {
tag: tag_name,
repo_folders,
remove,
}) => {
let tags: Vec<&str> = tag_name.split(',').map(|s| s.trim()).collect();
if *remove && repo_folders.is_empty() {
let mut repo_tags: BTreeMap<String, Vec<&str>> = BTreeMap::new();
for tag in &tags {
match init_gitopolis().remove_tag_from_all(tag) {
Ok(affected) => {
for repo in affected {
repo_tags.entry(repo).or_default().push(tag);
}
}
Err(error) => {
eprintln!("Error: {}", error.message());
std::process::exit(1);
}
}
}
if repo_tags.is_empty() {
println!("Tags {} not found on any repos", tags.join(","));
} else {
println!("Removed tags:");
for (repo, removed_tags) in &repo_tags {
println!("{} {}", repo, removed_tags.join(","));
}
}
} else if !*remove && repo_folders.is_empty() {
eprintln!("Error: repo_folders are required when adding tags");
std::process::exit(1);
} else {
for tag in tags {
let result = if *remove {
init_gitopolis().remove_tag(tag, repo_folders)
} else {
init_gitopolis().add_tag(tag, repo_folders)
};
if let Err(error) = result {
eprintln!("Error: {}", error.message());
std::process::exit(1);
}
}
}
}
Some(Commands::Tags { long }) => list_tags(*long),
Some(Commands::Sync {
read_remotes,
write_remotes,
dry_run,
tag: tag_args,
}) => {
let filter = TagFilter::from_cli_args(tag_args);
if *read_remotes {
init_gitopolis()
.sync_read_remotes(&filter, *dry_run)
.expect("Sync read failed");
} else if *write_remotes {
init_gitopolis()
.sync_write_remotes(&filter, *dry_run)
.expect("Sync write failed");
} else {
eprintln!("Error: Must specify either --read-remotes or --write-remotes");
std::process::exit(1);
}
}
Some(Commands::Show { repo_folder }) => {
show(repo_folder);
}
Some(Commands::Move { entity }) => match entity {
MoveEntity::Repo { old_path, new_path } => {
match init_gitopolis().move_repo(old_path, new_path) {
Ok(resolved_path) => {
eprintln!("Moved {} to {}", old_path, resolved_path);
}
Err(error) => {
eprintln!("Error: {}", error.message());
std::process::exit(1);
}
}
}
},
Some(Commands::Rename { entity }) => match entity {
RenameEntity::Tag {
old_name,
new_name,
merge,
} => match init_gitopolis().rename_tag(old_name, new_name, *merge) {
Ok(affected) => {
if affected.is_empty() {
println!("Tag '{}' not found on any repos", old_name);
} else {
println!("Renamed tag '{}' to '{}' on:", old_name, new_name);
for repo in &affected {
println!("{}", repo);
}
}
}
Err(error) => {
eprintln!("Error: {}", error.message());
std::process::exit(1);
}
},
},
None => {
panic!("no command") // this doesn't happen because help shows instead
}
}
}
/// Clone repository/repositories with dual behavior depending on URL presence.
///
/// # Behavior
///
/// ## When URL is provided
/// Clones a single repository from the given URL and adds it to gitopolis.
/// All tags from tag_args are flattened and applied to the cloned repository.
/// - Example: `--tag foo,bar --tag baz` results in repo having tags: [foo, bar, baz]
///
/// ## When URL is omitted
/// Clones all repositories from .gitopolis.toml configuration that match the tag filter.
/// Uses AND/OR logic for filtering:
/// - Comma-separated tags within one --tag flag use AND logic
/// - Multiple --tag flags use OR logic
/// - Example: `--tag foo,bar --tag baz,boz` clones repos matching (foo AND bar) OR (baz AND boz)
///
/// # Arguments
///
/// * `url` - Optional git URL to clone from
/// * `target_dir` - Optional target directory name (only used when URL is provided)
/// * `tag_args` - Tag arguments for either applying (with URL) or filtering (without URL)
fn clone(url: &Option<String>, target_dir: &Option<String>, tag_args: &[String]) {
match url {
Some(git_url) => clone_from_url(git_url, target_dir, tag_args),
None => {
// Clone from .gitopolis.toml with tag filtering
let gitopolis = init_gitopolis();
let filter = TagFilter::from_cli_args(tag_args);
gitopolis.clone(
gitopolis
.list(&filter)
.expect("Failed to list repositories for cloning"),
);
}
}
}
/// Clone a single repository from a URL and add it to gitopolis.
///
/// All tags from tag_args are flattened (comma-separated tags are split)
/// and applied to the cloned repository. No AND/OR filtering logic is used
/// since we're cloning a single repo.
///
/// # Arguments
///
/// * `git_url` - Git URL to clone from
/// * `target_dir` - Optional target directory name. If None, extracts from URL
/// * `tag_args` - Tags to apply to the cloned repo (all tags are flattened)
///
/// # Example
///
/// `--tag foo,bar --tag baz` results in repo having tags: [foo, bar, baz]
fn clone_from_url(git_url: &str, target_dir: &Option<String>, tag_args: &[String]) {
let mut gitopolis = init_gitopolis();
// Flatten all tags - when cloning a single repo, all tags are applied (no AND/OR logic)
let tags: Vec<String> = tag_args
.iter()
.flat_map(|s| s.split(',').map(|t| t.trim().to_string()))
.collect();
match gitopolis.clone_and_add(git_url, target_dir.as_deref(), &tags) {
Ok(folder_name) => {
println!("Successfully cloned and added {}", folder_name);
}
Err(error) => {
eprintln!("Error: {}", error.message());
std::process::exit(1);
}
}
}
const STATE_FILE: &str = ".gitopolis.toml";
fn init_gitopolis() -> Gitopolis {
Gitopolis::new(
Box::new(StorageImpl { path: STATE_FILE }),
Box::new(GitImpl {}),
)
}
fn add(repo_folders: Vec<String>) {
for repo_folder in repo_folders {
init_gitopolis().add(repo_folder).expect("Add failed");
}
}
fn list(repos: Vec<Repo>, long: bool) {
if repos.is_empty() {
println!("No repos");
std::process::exit(2);
}
for repo in &repos {
if long {
let remotes_str = repo
.remotes
.iter()
.map(|(name, remote)| format!("{}={}", name, remote.url))
.collect::<Vec<_>>()
.join(",");
println!("{}\t{}\t{}", repo.path, repo.tags.join(","), remotes_str);
} else {
println!("{}", repo.path);
}
}
}
fn list_tags(long: bool) {
let gitopolis = &init_gitopolis();
if long {
for tag in gitopolis.tags().expect("Failed to get tags") {
println!("{tag}");
let filter = TagFilter::from_cli_args(std::slice::from_ref(&tag));
for r in gitopolis
.list(&filter)
.expect("Failed to list repositories for tag")
{
println!("\t{}", r.path);
}
println!();
}
} else {
for tag in gitopolis.tags().expect("Failed to get tags") {
println!("{tag}");
}
}
}
fn show(repo_folder: &str) {
let gitopolis = init_gitopolis();
match gitopolis.show(repo_folder) {
Ok(repo_info) => {
println!("Tags:");
if repo_info.tags.is_empty() {
println!(" (none)");
} else {
for tag in &repo_info.tags {
println!(" {}", tag);
}
}
println!();
println!("Remotes:");
if repo_info.remotes.is_empty() {
println!(" (none)");
} else {
for (name, remote) in &repo_info.remotes {
println!(" {}: {}", name, remote.url);
}
}
}
Err(error) => {
eprintln!("Error: {}", error.message());
std::process::exit(1);
}
}
}