]> git.ipfire.org Git - thirdparty/git.git/blob - contrib/scalar/scalar.c
f7455190385a134cc7c5c131b767e690531783da
[thirdparty/git.git] / contrib / scalar / scalar.c
1 /*
2 * The Scalar command-line interface.
3 */
4
5 #include "cache.h"
6 #include "gettext.h"
7 #include "parse-options.h"
8 #include "config.h"
9 #include "run-command.h"
10 #include "refs.h"
11 #include "dir.h"
12 #include "packfile.h"
13 #include "help.h"
14 #include "archive.h"
15 #include "object-store.h"
16
17 /*
18 * Remove the deepest subdirectory in the provided path string. Path must not
19 * include a trailing path separator. Returns 1 if parent directory found,
20 * otherwise 0.
21 */
22 static int strbuf_parent_directory(struct strbuf *buf)
23 {
24 size_t len = buf->len;
25 size_t offset = offset_1st_component(buf->buf);
26 char *path_sep = find_last_dir_sep(buf->buf + offset);
27 strbuf_setlen(buf, path_sep ? path_sep - buf->buf : offset);
28
29 return buf->len < len;
30 }
31
32 static void setup_enlistment_directory(int argc, const char **argv,
33 const char * const *usagestr,
34 const struct option *options,
35 struct strbuf *enlistment_root)
36 {
37 struct strbuf path = STRBUF_INIT;
38 char *root;
39 int enlistment_found = 0;
40
41 if (startup_info->have_repository)
42 BUG("gitdir already set up?!?");
43
44 if (argc > 1)
45 usage_with_options(usagestr, options);
46
47 /* find the worktree, determine its corresponding root */
48 if (argc == 1) {
49 strbuf_add_absolute_path(&path, argv[0]);
50 if (!is_directory(path.buf))
51 die(_("'%s' does not exist"), path.buf);
52 } else if (strbuf_getcwd(&path) < 0)
53 die(_("need a working directory"));
54
55 strbuf_trim_trailing_dir_sep(&path);
56 do {
57 const size_t len = path.len;
58
59 /* check if currently in enlistment root with src/ workdir */
60 strbuf_addstr(&path, "/src");
61 if (is_nonbare_repository_dir(&path)) {
62 if (enlistment_root)
63 strbuf_add(enlistment_root, path.buf, len);
64
65 enlistment_found = 1;
66 break;
67 }
68
69 /* reset to original path */
70 strbuf_setlen(&path, len);
71
72 /* check if currently in workdir */
73 if (is_nonbare_repository_dir(&path)) {
74 if (enlistment_root) {
75 /*
76 * If the worktree's directory's name is `src`, the enlistment is the
77 * parent directory, otherwise it is identical to the worktree.
78 */
79 root = strip_path_suffix(path.buf, "src");
80 strbuf_addstr(enlistment_root, root ? root : path.buf);
81 free(root);
82 }
83
84 enlistment_found = 1;
85 break;
86 }
87 } while (strbuf_parent_directory(&path));
88
89 if (!enlistment_found)
90 die(_("could not find enlistment root"));
91
92 if (chdir(path.buf) < 0)
93 die_errno(_("could not switch to '%s'"), path.buf);
94
95 strbuf_release(&path);
96 setup_git_directory();
97 }
98
99 static int run_git(const char *arg, ...)
100 {
101 struct strvec argv = STRVEC_INIT;
102 va_list args;
103 const char *p;
104 int res;
105
106 va_start(args, arg);
107 strvec_push(&argv, arg);
108 while ((p = va_arg(args, const char *)))
109 strvec_push(&argv, p);
110 va_end(args);
111
112 res = run_command_v_opt(argv.v, RUN_GIT_CMD);
113
114 strvec_clear(&argv);
115 return res;
116 }
117
118 static int set_recommended_config(int reconfigure)
119 {
120 struct {
121 const char *key;
122 const char *value;
123 int overwrite_on_reconfigure;
124 } config[] = {
125 /* Required */
126 { "am.keepCR", "true", 1 },
127 { "core.FSCache", "true", 1 },
128 { "core.multiPackIndex", "true", 1 },
129 { "core.preloadIndex", "true", 1 },
130 #ifndef WIN32
131 { "core.untrackedCache", "true", 1 },
132 #else
133 /*
134 * Unfortunately, Scalar's Functional Tests demonstrated
135 * that the untracked cache feature is unreliable on Windows
136 * (which is a bummer because that platform would benefit the
137 * most from it). For some reason, freshly created files seem
138 * not to update the directory's `lastModified` time
139 * immediately, but the untracked cache would need to rely on
140 * that.
141 *
142 * Therefore, with a sad heart, we disable this very useful
143 * feature on Windows.
144 */
145 { "core.untrackedCache", "false", 1 },
146 #endif
147 { "core.logAllRefUpdates", "true", 1 },
148 { "credential.https://dev.azure.com.useHttpPath", "true", 1 },
149 { "credential.validate", "false", 1 }, /* GCM4W-only */
150 { "gc.auto", "0", 1 },
151 { "gui.GCWarning", "false", 1 },
152 { "index.threads", "true", 1 },
153 { "index.version", "4", 1 },
154 { "merge.stat", "false", 1 },
155 { "merge.renames", "true", 1 },
156 { "pack.useBitmaps", "false", 1 },
157 { "pack.useSparse", "true", 1 },
158 { "receive.autoGC", "false", 1 },
159 { "feature.manyFiles", "false", 1 },
160 { "feature.experimental", "false", 1 },
161 { "fetch.unpackLimit", "1", 1 },
162 { "fetch.writeCommitGraph", "false", 1 },
163 #ifdef WIN32
164 { "http.sslBackend", "schannel", 1 },
165 #endif
166 /* Optional */
167 { "status.aheadBehind", "false" },
168 { "commitGraph.generationVersion", "1" },
169 { "core.autoCRLF", "false" },
170 { "core.safeCRLF", "false" },
171 { "fetch.showForcedUpdates", "false" },
172 { NULL, NULL },
173 };
174 int i;
175 char *value;
176
177 for (i = 0; config[i].key; i++) {
178 if ((reconfigure && config[i].overwrite_on_reconfigure) ||
179 git_config_get_string(config[i].key, &value)) {
180 trace2_data_string("scalar", the_repository, config[i].key, "created");
181 if (git_config_set_gently(config[i].key,
182 config[i].value) < 0)
183 return error(_("could not configure %s=%s"),
184 config[i].key, config[i].value);
185 } else {
186 trace2_data_string("scalar", the_repository, config[i].key, "exists");
187 free(value);
188 }
189 }
190
191 /*
192 * The `log.excludeDecoration` setting is special because it allows
193 * for multiple values.
194 */
195 if (git_config_get_string("log.excludeDecoration", &value)) {
196 trace2_data_string("scalar", the_repository,
197 "log.excludeDecoration", "created");
198 if (git_config_set_multivar_gently("log.excludeDecoration",
199 "refs/prefetch/*",
200 CONFIG_REGEX_NONE, 0))
201 return error(_("could not configure "
202 "log.excludeDecoration"));
203 } else {
204 trace2_data_string("scalar", the_repository,
205 "log.excludeDecoration", "exists");
206 free(value);
207 }
208
209 return 0;
210 }
211
212 static int toggle_maintenance(int enable)
213 {
214 return run_git("maintenance", enable ? "start" : "unregister", NULL);
215 }
216
217 static int add_or_remove_enlistment(int add)
218 {
219 int res;
220
221 if (!the_repository->worktree)
222 die(_("Scalar enlistments require a worktree"));
223
224 res = run_git("config", "--global", "--get", "--fixed-value",
225 "scalar.repo", the_repository->worktree, NULL);
226
227 /*
228 * If we want to add and the setting is already there, then do nothing.
229 * If we want to remove and the setting is not there, then do nothing.
230 */
231 if ((add && !res) || (!add && res))
232 return 0;
233
234 return run_git("config", "--global", add ? "--add" : "--unset",
235 add ? "--no-fixed-value" : "--fixed-value",
236 "scalar.repo", the_repository->worktree, NULL);
237 }
238
239 static int register_dir(void)
240 {
241 int res = add_or_remove_enlistment(1);
242
243 if (!res)
244 res = set_recommended_config(0);
245
246 if (!res)
247 res = toggle_maintenance(1);
248
249 return res;
250 }
251
252 static int unregister_dir(void)
253 {
254 int res = 0;
255
256 if (toggle_maintenance(0) < 0)
257 res = -1;
258
259 if (add_or_remove_enlistment(0) < 0)
260 res = -1;
261
262 return res;
263 }
264
265 static int add_directory_to_archiver(struct strvec *archiver_args,
266 const char *path, int recurse)
267 {
268 int at_root = !*path;
269 DIR *dir = opendir(at_root ? "." : path);
270 struct dirent *e;
271 struct strbuf buf = STRBUF_INIT;
272 size_t len;
273 int res = 0;
274
275 if (!dir)
276 return error_errno(_("could not open directory '%s'"), path);
277
278 if (!at_root)
279 strbuf_addf(&buf, "%s/", path);
280 len = buf.len;
281 strvec_pushf(archiver_args, "--prefix=%s", buf.buf);
282
283 while (!res && (e = readdir(dir))) {
284 if (!strcmp(".", e->d_name) || !strcmp("..", e->d_name))
285 continue;
286
287 strbuf_setlen(&buf, len);
288 strbuf_addstr(&buf, e->d_name);
289
290 if (e->d_type == DT_REG)
291 strvec_pushf(archiver_args, "--add-file=%s", buf.buf);
292 else if (e->d_type != DT_DIR)
293 warning(_("skipping '%s', which is neither file nor "
294 "directory"), buf.buf);
295 else if (recurse &&
296 add_directory_to_archiver(archiver_args,
297 buf.buf, recurse) < 0)
298 res = -1;
299 }
300
301 closedir(dir);
302 strbuf_release(&buf);
303 return res;
304 }
305
306 #ifndef WIN32
307 #include <sys/statvfs.h>
308 #endif
309
310 static int get_disk_info(struct strbuf *out)
311 {
312 #ifdef WIN32
313 struct strbuf buf = STRBUF_INIT;
314 char volume_name[MAX_PATH], fs_name[MAX_PATH];
315 DWORD serial_number, component_length, flags;
316 ULARGE_INTEGER avail2caller, total, avail;
317
318 strbuf_realpath(&buf, ".", 1);
319 if (!GetDiskFreeSpaceExA(buf.buf, &avail2caller, &total, &avail)) {
320 error(_("could not determine free disk size for '%s'"),
321 buf.buf);
322 strbuf_release(&buf);
323 return -1;
324 }
325
326 strbuf_setlen(&buf, offset_1st_component(buf.buf));
327 if (!GetVolumeInformationA(buf.buf, volume_name, sizeof(volume_name),
328 &serial_number, &component_length, &flags,
329 fs_name, sizeof(fs_name))) {
330 error(_("could not get info for '%s'"), buf.buf);
331 strbuf_release(&buf);
332 return -1;
333 }
334 strbuf_addf(out, "Available space on '%s': ", buf.buf);
335 strbuf_humanise_bytes(out, avail2caller.QuadPart);
336 strbuf_addch(out, '\n');
337 strbuf_release(&buf);
338 #else
339 struct strbuf buf = STRBUF_INIT;
340 struct statvfs stat;
341
342 strbuf_realpath(&buf, ".", 1);
343 if (statvfs(buf.buf, &stat) < 0) {
344 error_errno(_("could not determine free disk size for '%s'"),
345 buf.buf);
346 strbuf_release(&buf);
347 return -1;
348 }
349
350 strbuf_addf(out, "Available space on '%s': ", buf.buf);
351 strbuf_humanise_bytes(out, st_mult(stat.f_bsize, stat.f_bavail));
352 strbuf_addf(out, " (mount flags 0x%lx)\n", stat.f_flag);
353 strbuf_release(&buf);
354 #endif
355 return 0;
356 }
357
358 /* printf-style interface, expects `<key>=<value>` argument */
359 static int set_config(const char *fmt, ...)
360 {
361 struct strbuf buf = STRBUF_INIT;
362 char *value;
363 int res;
364 va_list args;
365
366 va_start(args, fmt);
367 strbuf_vaddf(&buf, fmt, args);
368 va_end(args);
369
370 value = strchr(buf.buf, '=');
371 if (value)
372 *(value++) = '\0';
373 res = git_config_set_gently(buf.buf, value);
374 strbuf_release(&buf);
375
376 return res;
377 }
378
379 static char *remote_default_branch(const char *url)
380 {
381 struct child_process cp = CHILD_PROCESS_INIT;
382 struct strbuf out = STRBUF_INIT;
383
384 cp.git_cmd = 1;
385 strvec_pushl(&cp.args, "ls-remote", "--symref", url, "HEAD", NULL);
386 if (!pipe_command(&cp, NULL, 0, &out, 0, NULL, 0)) {
387 const char *line = out.buf;
388
389 while (*line) {
390 const char *eol = strchrnul(line, '\n'), *p;
391 size_t len = eol - line;
392 char *branch;
393
394 if (!skip_prefix(line, "ref: ", &p) ||
395 !strip_suffix_mem(line, &len, "\tHEAD")) {
396 line = eol + (*eol == '\n');
397 continue;
398 }
399
400 eol = line + len;
401 if (skip_prefix(p, "refs/heads/", &p)) {
402 branch = xstrndup(p, eol - p);
403 strbuf_release(&out);
404 return branch;
405 }
406
407 error(_("remote HEAD is not a branch: '%.*s'"),
408 (int)(eol - p), p);
409 strbuf_release(&out);
410 return NULL;
411 }
412 }
413 warning(_("failed to get default branch name from remote; "
414 "using local default"));
415 strbuf_reset(&out);
416
417 child_process_init(&cp);
418 cp.git_cmd = 1;
419 strvec_pushl(&cp.args, "symbolic-ref", "--short", "HEAD", NULL);
420 if (!pipe_command(&cp, NULL, 0, &out, 0, NULL, 0)) {
421 strbuf_trim(&out);
422 return strbuf_detach(&out, NULL);
423 }
424
425 strbuf_release(&out);
426 error(_("failed to get default branch name"));
427 return NULL;
428 }
429
430 static int delete_enlistment(struct strbuf *enlistment)
431 {
432 #ifdef WIN32
433 struct strbuf parent = STRBUF_INIT;
434 #endif
435
436 if (unregister_dir())
437 die(_("failed to unregister repository"));
438
439 #ifdef WIN32
440 /*
441 * Change the current directory to one outside of the enlistment so
442 * that we may delete everything underneath it.
443 */
444 strbuf_addbuf(&parent, enlistment);
445 strbuf_parent_directory(&parent);
446 if (chdir(parent.buf) < 0)
447 die_errno(_("could not switch to '%s'"), parent.buf);
448 strbuf_release(&parent);
449 #endif
450
451 if (remove_dir_recursively(enlistment, 0))
452 die(_("failed to delete enlistment directory"));
453
454 return 0;
455 }
456
457 /*
458 * Dummy implementation; Using `get_version_info()` would cause a link error
459 * without this.
460 */
461 void load_builtin_commands(const char *prefix, struct cmdnames *cmds)
462 {
463 die("not implemented");
464 }
465
466 static int cmd_clone(int argc, const char **argv)
467 {
468 const char *branch = NULL;
469 int full_clone = 0, single_branch = 0;
470 struct option clone_options[] = {
471 OPT_STRING('b', "branch", &branch, N_("<branch>"),
472 N_("branch to checkout after clone")),
473 OPT_BOOL(0, "full-clone", &full_clone,
474 N_("when cloning, create full working directory")),
475 OPT_BOOL(0, "single-branch", &single_branch,
476 N_("only download metadata for the branch that will "
477 "be checked out")),
478 OPT_END(),
479 };
480 const char * const clone_usage[] = {
481 N_("scalar clone [<options>] [--] <repo> [<dir>]"),
482 NULL
483 };
484 const char *url;
485 char *enlistment = NULL, *dir = NULL;
486 struct strbuf buf = STRBUF_INIT;
487 int res;
488
489 argc = parse_options(argc, argv, NULL, clone_options, clone_usage, 0);
490
491 if (argc == 2) {
492 url = argv[0];
493 enlistment = xstrdup(argv[1]);
494 } else if (argc == 1) {
495 url = argv[0];
496
497 strbuf_addstr(&buf, url);
498 /* Strip trailing slashes, if any */
499 while (buf.len > 0 && is_dir_sep(buf.buf[buf.len - 1]))
500 strbuf_setlen(&buf, buf.len - 1);
501 /* Strip suffix `.git`, if any */
502 strbuf_strip_suffix(&buf, ".git");
503
504 enlistment = find_last_dir_sep(buf.buf);
505 if (!enlistment) {
506 die(_("cannot deduce worktree name from '%s'"), url);
507 }
508 enlistment = xstrdup(enlistment + 1);
509 } else {
510 usage_msg_opt(_("You must specify a repository to clone."),
511 clone_usage, clone_options);
512 }
513
514 if (is_directory(enlistment))
515 die(_("directory '%s' exists already"), enlistment);
516
517 dir = xstrfmt("%s/src", enlistment);
518
519 strbuf_reset(&buf);
520 if (branch)
521 strbuf_addf(&buf, "init.defaultBranch=%s", branch);
522 else {
523 char *b = repo_default_branch_name(the_repository, 1);
524 strbuf_addf(&buf, "init.defaultBranch=%s", b);
525 free(b);
526 }
527
528 if ((res = run_git("-c", buf.buf, "init", "--", dir, NULL)))
529 goto cleanup;
530
531 if (chdir(dir) < 0) {
532 res = error_errno(_("could not switch to '%s'"), dir);
533 goto cleanup;
534 }
535
536 setup_git_directory();
537
538 /* common-main already logs `argv` */
539 trace2_def_repo(the_repository);
540
541 if (!branch && !(branch = remote_default_branch(url))) {
542 res = error(_("failed to get default branch for '%s'"), url);
543 goto cleanup;
544 }
545
546 if (set_config("remote.origin.url=%s", url) ||
547 set_config("remote.origin.fetch="
548 "+refs/heads/%s:refs/remotes/origin/%s",
549 single_branch ? branch : "*",
550 single_branch ? branch : "*") ||
551 set_config("remote.origin.promisor=true") ||
552 set_config("remote.origin.partialCloneFilter=blob:none")) {
553 res = error(_("could not configure remote in '%s'"), dir);
554 goto cleanup;
555 }
556
557 if (!full_clone &&
558 (res = run_git("sparse-checkout", "init", "--cone", NULL)))
559 goto cleanup;
560
561 if (set_recommended_config(0))
562 return error(_("could not configure '%s'"), dir);
563
564 if ((res = run_git("fetch", "--quiet", "origin", NULL))) {
565 warning(_("partial clone failed; attempting full clone"));
566
567 if (set_config("remote.origin.promisor") ||
568 set_config("remote.origin.partialCloneFilter")) {
569 res = error(_("could not configure for full clone"));
570 goto cleanup;
571 }
572
573 if ((res = run_git("fetch", "--quiet", "origin", NULL)))
574 goto cleanup;
575 }
576
577 if ((res = set_config("branch.%s.remote=origin", branch)))
578 goto cleanup;
579 if ((res = set_config("branch.%s.merge=refs/heads/%s",
580 branch, branch)))
581 goto cleanup;
582
583 strbuf_reset(&buf);
584 strbuf_addf(&buf, "origin/%s", branch);
585 res = run_git("checkout", "-f", "-t", buf.buf, NULL);
586 if (res)
587 goto cleanup;
588
589 res = register_dir();
590
591 cleanup:
592 free(enlistment);
593 free(dir);
594 strbuf_release(&buf);
595 return res;
596 }
597
598 static void dir_file_stats_objects(const char *full_path, size_t full_path_len,
599 const char *file_name, void *data)
600 {
601 struct strbuf *buf = data;
602 struct stat st;
603
604 if (!stat(full_path, &st))
605 strbuf_addf(buf, "%-70s %16" PRIuMAX "\n", file_name,
606 (uintmax_t)st.st_size);
607 }
608
609 static int dir_file_stats(struct object_directory *object_dir, void *data)
610 {
611 struct strbuf *buf = data;
612
613 strbuf_addf(buf, "Contents of %s:\n", object_dir->path);
614
615 for_each_file_in_pack_dir(object_dir->path, dir_file_stats_objects,
616 data);
617
618 return 0;
619 }
620
621 static int cmd_diagnose(int argc, const char **argv)
622 {
623 struct option options[] = {
624 OPT_END(),
625 };
626 const char * const usage[] = {
627 N_("scalar diagnose [<enlistment>]"),
628 NULL
629 };
630 struct strbuf zip_path = STRBUF_INIT;
631 struct strvec archiver_args = STRVEC_INIT;
632 char **argv_copy = NULL;
633 int stdout_fd = -1, archiver_fd = -1;
634 time_t now = time(NULL);
635 struct tm tm;
636 struct strbuf path = STRBUF_INIT, buf = STRBUF_INIT;
637 int res = 0;
638
639 argc = parse_options(argc, argv, NULL, options,
640 usage, 0);
641
642 setup_enlistment_directory(argc, argv, usage, options, &zip_path);
643
644 strbuf_addstr(&zip_path, "/.scalarDiagnostics/scalar_");
645 strbuf_addftime(&zip_path,
646 "%Y%m%d_%H%M%S", localtime_r(&now, &tm), 0, 0);
647 strbuf_addstr(&zip_path, ".zip");
648 switch (safe_create_leading_directories(zip_path.buf)) {
649 case SCLD_EXISTS:
650 case SCLD_OK:
651 break;
652 default:
653 error_errno(_("could not create directory for '%s'"),
654 zip_path.buf);
655 goto diagnose_cleanup;
656 }
657 stdout_fd = dup(1);
658 if (stdout_fd < 0) {
659 res = error_errno(_("could not duplicate stdout"));
660 goto diagnose_cleanup;
661 }
662
663 archiver_fd = xopen(zip_path.buf, O_CREAT | O_WRONLY | O_TRUNC, 0666);
664 if (archiver_fd < 0 || dup2(archiver_fd, 1) < 0) {
665 res = error_errno(_("could not redirect output"));
666 goto diagnose_cleanup;
667 }
668
669 init_zip_archiver();
670 strvec_pushl(&archiver_args, "scalar-diagnose", "--format=zip", NULL);
671
672 strbuf_reset(&buf);
673 strbuf_addstr(&buf, "Collecting diagnostic info\n\n");
674 get_version_info(&buf, 1);
675
676 strbuf_addf(&buf, "Enlistment root: %s\n", the_repository->worktree);
677 get_disk_info(&buf);
678 write_or_die(stdout_fd, buf.buf, buf.len);
679 strvec_pushf(&archiver_args,
680 "--add-virtual-file=diagnostics.log:%.*s",
681 (int)buf.len, buf.buf);
682
683 strbuf_reset(&buf);
684 strbuf_addstr(&buf, "--add-virtual-file=packs-local.txt:");
685 dir_file_stats(the_repository->objects->odb, &buf);
686 foreach_alt_odb(dir_file_stats, &buf);
687 strvec_push(&archiver_args, buf.buf);
688
689 if ((res = add_directory_to_archiver(&archiver_args, ".git", 0)) ||
690 (res = add_directory_to_archiver(&archiver_args, ".git/hooks", 0)) ||
691 (res = add_directory_to_archiver(&archiver_args, ".git/info", 0)) ||
692 (res = add_directory_to_archiver(&archiver_args, ".git/logs", 1)) ||
693 (res = add_directory_to_archiver(&archiver_args, ".git/objects/info", 0)))
694 goto diagnose_cleanup;
695
696 strvec_pushl(&archiver_args, "--prefix=",
697 oid_to_hex(the_hash_algo->empty_tree), "--", NULL);
698
699 /* `write_archive()` modifies the `argv` passed to it. Let it. */
700 argv_copy = xmemdupz(archiver_args.v,
701 sizeof(char *) * archiver_args.nr);
702 res = write_archive(archiver_args.nr, (const char **)argv_copy, NULL,
703 the_repository, NULL, 0);
704 if (res) {
705 error(_("failed to write archive"));
706 goto diagnose_cleanup;
707 }
708
709 if (!res)
710 fprintf(stderr, "\n"
711 "Diagnostics complete.\n"
712 "All of the gathered info is captured in '%s'\n",
713 zip_path.buf);
714
715 diagnose_cleanup:
716 if (archiver_fd >= 0) {
717 close(1);
718 dup2(stdout_fd, 1);
719 }
720 free(argv_copy);
721 strvec_clear(&archiver_args);
722 strbuf_release(&zip_path);
723 strbuf_release(&path);
724 strbuf_release(&buf);
725
726 return res;
727 }
728
729 static int cmd_list(int argc, const char **argv)
730 {
731 if (argc != 1)
732 die(_("`scalar list` does not take arguments"));
733
734 if (run_git("config", "--global", "--get-all", "scalar.repo", NULL) < 0)
735 return -1;
736 return 0;
737 }
738
739 static int cmd_register(int argc, const char **argv)
740 {
741 struct option options[] = {
742 OPT_END(),
743 };
744 const char * const usage[] = {
745 N_("scalar register [<enlistment>]"),
746 NULL
747 };
748
749 argc = parse_options(argc, argv, NULL, options,
750 usage, 0);
751
752 setup_enlistment_directory(argc, argv, usage, options, NULL);
753
754 return register_dir();
755 }
756
757 static int get_scalar_repos(const char *key, const char *value, void *data)
758 {
759 struct string_list *list = data;
760
761 if (!strcmp(key, "scalar.repo"))
762 string_list_append(list, value);
763
764 return 0;
765 }
766
767 static int cmd_reconfigure(int argc, const char **argv)
768 {
769 int all = 0;
770 struct option options[] = {
771 OPT_BOOL('a', "all", &all,
772 N_("reconfigure all registered enlistments")),
773 OPT_END(),
774 };
775 const char * const usage[] = {
776 N_("scalar reconfigure [--all | <enlistment>]"),
777 NULL
778 };
779 struct string_list scalar_repos = STRING_LIST_INIT_DUP;
780 int i, res = 0;
781 struct repository r = { NULL };
782 struct strbuf commondir = STRBUF_INIT, gitdir = STRBUF_INIT;
783
784 argc = parse_options(argc, argv, NULL, options,
785 usage, 0);
786
787 if (!all) {
788 setup_enlistment_directory(argc, argv, usage, options, NULL);
789
790 return set_recommended_config(1);
791 }
792
793 if (argc > 0)
794 usage_msg_opt(_("--all or <enlistment>, but not both"),
795 usage, options);
796
797 git_config(get_scalar_repos, &scalar_repos);
798
799 for (i = 0; i < scalar_repos.nr; i++) {
800 const char *dir = scalar_repos.items[i].string;
801
802 strbuf_reset(&commondir);
803 strbuf_reset(&gitdir);
804
805 if (chdir(dir) < 0) {
806 warning_errno(_("could not switch to '%s'"), dir);
807 res = -1;
808 } else if (discover_git_directory(&commondir, &gitdir) < 0) {
809 warning_errno(_("git repository gone in '%s'"), dir);
810 res = -1;
811 } else {
812 git_config_clear();
813
814 the_repository = &r;
815 r.commondir = commondir.buf;
816 r.gitdir = gitdir.buf;
817
818 if (set_recommended_config(1) < 0)
819 res = -1;
820 }
821 }
822
823 string_list_clear(&scalar_repos, 1);
824 strbuf_release(&commondir);
825 strbuf_release(&gitdir);
826
827 return res;
828 }
829
830 static int cmd_run(int argc, const char **argv)
831 {
832 struct option options[] = {
833 OPT_END(),
834 };
835 struct {
836 const char *arg, *task;
837 } tasks[] = {
838 { "config", NULL },
839 { "commit-graph", "commit-graph" },
840 { "fetch", "prefetch" },
841 { "loose-objects", "loose-objects" },
842 { "pack-files", "incremental-repack" },
843 { NULL, NULL }
844 };
845 struct strbuf buf = STRBUF_INIT;
846 const char *usagestr[] = { NULL, NULL };
847 int i;
848
849 strbuf_addstr(&buf, N_("scalar run <task> [<enlistment>]\nTasks:\n"));
850 for (i = 0; tasks[i].arg; i++)
851 strbuf_addf(&buf, "\t%s\n", tasks[i].arg);
852 usagestr[0] = buf.buf;
853
854 argc = parse_options(argc, argv, NULL, options,
855 usagestr, 0);
856
857 if (!argc)
858 usage_with_options(usagestr, options);
859
860 if (!strcmp("all", argv[0])) {
861 i = -1;
862 } else {
863 for (i = 0; tasks[i].arg && strcmp(tasks[i].arg, argv[0]); i++)
864 ; /* keep looking for the task */
865
866 if (i > 0 && !tasks[i].arg) {
867 error(_("no such task: '%s'"), argv[0]);
868 usage_with_options(usagestr, options);
869 }
870 }
871
872 argc--;
873 argv++;
874 setup_enlistment_directory(argc, argv, usagestr, options, NULL);
875 strbuf_release(&buf);
876
877 if (i == 0)
878 return register_dir();
879
880 if (i > 0)
881 return run_git("maintenance", "run",
882 "--task", tasks[i].task, NULL);
883
884 if (register_dir())
885 return -1;
886 for (i = 1; tasks[i].arg; i++)
887 if (run_git("maintenance", "run",
888 "--task", tasks[i].task, NULL))
889 return -1;
890 return 0;
891 }
892
893 static int remove_deleted_enlistment(struct strbuf *path)
894 {
895 int res = 0;
896 strbuf_realpath_forgiving(path, path->buf, 1);
897
898 if (run_git("config", "--global",
899 "--unset", "--fixed-value",
900 "scalar.repo", path->buf, NULL) < 0)
901 res = -1;
902
903 if (run_git("config", "--global",
904 "--unset", "--fixed-value",
905 "maintenance.repo", path->buf, NULL) < 0)
906 res = -1;
907
908 return res;
909 }
910
911 static int cmd_unregister(int argc, const char **argv)
912 {
913 struct option options[] = {
914 OPT_END(),
915 };
916 const char * const usage[] = {
917 N_("scalar unregister [<enlistment>]"),
918 NULL
919 };
920
921 argc = parse_options(argc, argv, NULL, options,
922 usage, 0);
923
924 /*
925 * Be forgiving when the enlistment or worktree does not even exist any
926 * longer; This can be the case if a user deleted the worktree by
927 * mistake and _still_ wants to unregister the thing.
928 */
929 if (argc == 1) {
930 struct strbuf src_path = STRBUF_INIT, workdir_path = STRBUF_INIT;
931
932 strbuf_addf(&src_path, "%s/src/.git", argv[0]);
933 strbuf_addf(&workdir_path, "%s/.git", argv[0]);
934 if (!is_directory(src_path.buf) && !is_directory(workdir_path.buf)) {
935 /* remove possible matching registrations */
936 int res = -1;
937
938 strbuf_strip_suffix(&src_path, "/.git");
939 res = remove_deleted_enlistment(&src_path) && res;
940
941 strbuf_strip_suffix(&workdir_path, "/.git");
942 res = remove_deleted_enlistment(&workdir_path) && res;
943
944 strbuf_release(&src_path);
945 strbuf_release(&workdir_path);
946 return res;
947 }
948 strbuf_release(&src_path);
949 strbuf_release(&workdir_path);
950 }
951
952 setup_enlistment_directory(argc, argv, usage, options, NULL);
953
954 return unregister_dir();
955 }
956
957 static int cmd_delete(int argc, const char **argv)
958 {
959 char *cwd = xgetcwd();
960 struct option options[] = {
961 OPT_END(),
962 };
963 const char * const usage[] = {
964 N_("scalar delete <enlistment>"),
965 NULL
966 };
967 struct strbuf enlistment = STRBUF_INIT;
968 int res = 0;
969
970 argc = parse_options(argc, argv, NULL, options,
971 usage, 0);
972
973 if (argc != 1)
974 usage_with_options(usage, options);
975
976 setup_enlistment_directory(argc, argv, usage, options, &enlistment);
977
978 if (dir_inside_of(cwd, enlistment.buf) >= 0)
979 res = error(_("refusing to delete current working directory"));
980 else {
981 close_object_store(the_repository->objects);
982 res = delete_enlistment(&enlistment);
983 }
984 strbuf_release(&enlistment);
985 free(cwd);
986
987 return res;
988 }
989
990 static int cmd_version(int argc, const char **argv)
991 {
992 int verbose = 0, build_options = 0;
993 struct option options[] = {
994 OPT__VERBOSE(&verbose, N_("include Git version")),
995 OPT_BOOL(0, "build-options", &build_options,
996 N_("include Git's build options")),
997 OPT_END(),
998 };
999 const char * const usage[] = {
1000 N_("scalar verbose [-v | --verbose] [--build-options]"),
1001 NULL
1002 };
1003 struct strbuf buf = STRBUF_INIT;
1004
1005 argc = parse_options(argc, argv, NULL, options,
1006 usage, 0);
1007
1008 if (argc != 0)
1009 usage_with_options(usage, options);
1010
1011 get_version_info(&buf, build_options);
1012 fprintf(stderr, "%s\n", buf.buf);
1013 strbuf_release(&buf);
1014
1015 return 0;
1016 }
1017
1018 static struct {
1019 const char *name;
1020 int (*fn)(int, const char **);
1021 } builtins[] = {
1022 { "clone", cmd_clone },
1023 { "list", cmd_list },
1024 { "register", cmd_register },
1025 { "unregister", cmd_unregister },
1026 { "run", cmd_run },
1027 { "reconfigure", cmd_reconfigure },
1028 { "delete", cmd_delete },
1029 { "version", cmd_version },
1030 { "diagnose", cmd_diagnose },
1031 { NULL, NULL},
1032 };
1033
1034 int cmd_main(int argc, const char **argv)
1035 {
1036 struct strbuf scalar_usage = STRBUF_INIT;
1037 int i;
1038
1039 while (argc > 1 && *argv[1] == '-') {
1040 if (!strcmp(argv[1], "-C")) {
1041 if (argc < 3)
1042 die(_("-C requires a <directory>"));
1043 if (chdir(argv[2]) < 0)
1044 die_errno(_("could not change to '%s'"),
1045 argv[2]);
1046 argc -= 2;
1047 argv += 2;
1048 } else if (!strcmp(argv[1], "-c")) {
1049 if (argc < 3)
1050 die(_("-c requires a <key>=<value> argument"));
1051 git_config_push_parameter(argv[2]);
1052 argc -= 2;
1053 argv += 2;
1054 } else
1055 break;
1056 }
1057
1058 if (argc > 1) {
1059 argv++;
1060 argc--;
1061
1062 for (i = 0; builtins[i].name; i++)
1063 if (!strcmp(builtins[i].name, argv[0]))
1064 return !!builtins[i].fn(argc, argv);
1065 }
1066
1067 strbuf_addstr(&scalar_usage,
1068 N_("scalar [-C <directory>] [-c <key>=<value>] "
1069 "<command> [<options>]\n\nCommands:\n"));
1070 for (i = 0; builtins[i].name; i++)
1071 strbuf_addf(&scalar_usage, "\t%s\n", builtins[i].name);
1072
1073 usage(scalar_usage.buf);
1074 }