]> git.ipfire.org Git - thirdparty/git.git/blob - contrib/scalar/scalar.c
clone: allow "--bare" with "-o"
[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 count_files(char *path)
622 {
623 DIR *dir = opendir(path);
624 struct dirent *e;
625 int count = 0;
626
627 if (!dir)
628 return 0;
629
630 while ((e = readdir(dir)) != NULL)
631 if (!is_dot_or_dotdot(e->d_name) && e->d_type == DT_REG)
632 count++;
633
634 closedir(dir);
635 return count;
636 }
637
638 static void loose_objs_stats(struct strbuf *buf, const char *path)
639 {
640 DIR *dir = opendir(path);
641 struct dirent *e;
642 int count;
643 int total = 0;
644 unsigned char c;
645 struct strbuf count_path = STRBUF_INIT;
646 size_t base_path_len;
647
648 if (!dir)
649 return;
650
651 strbuf_addstr(buf, "Object directory stats for ");
652 strbuf_add_absolute_path(buf, path);
653 strbuf_addstr(buf, ":\n");
654
655 strbuf_add_absolute_path(&count_path, path);
656 strbuf_addch(&count_path, '/');
657 base_path_len = count_path.len;
658
659 while ((e = readdir(dir)) != NULL)
660 if (!is_dot_or_dotdot(e->d_name) &&
661 e->d_type == DT_DIR && strlen(e->d_name) == 2 &&
662 !hex_to_bytes(&c, e->d_name, 1)) {
663 strbuf_setlen(&count_path, base_path_len);
664 strbuf_addstr(&count_path, e->d_name);
665 total += (count = count_files(count_path.buf));
666 strbuf_addf(buf, "%s : %7d files\n", e->d_name, count);
667 }
668
669 strbuf_addf(buf, "Total: %d loose objects", total);
670
671 strbuf_release(&count_path);
672 closedir(dir);
673 }
674
675 static int cmd_diagnose(int argc, const char **argv)
676 {
677 struct option options[] = {
678 OPT_END(),
679 };
680 const char * const usage[] = {
681 N_("scalar diagnose [<enlistment>]"),
682 NULL
683 };
684 struct strbuf zip_path = STRBUF_INIT;
685 struct strvec archiver_args = STRVEC_INIT;
686 char **argv_copy = NULL;
687 int stdout_fd = -1, archiver_fd = -1;
688 time_t now = time(NULL);
689 struct tm tm;
690 struct strbuf path = STRBUF_INIT, buf = STRBUF_INIT;
691 int res = 0;
692
693 argc = parse_options(argc, argv, NULL, options,
694 usage, 0);
695
696 setup_enlistment_directory(argc, argv, usage, options, &zip_path);
697
698 strbuf_addstr(&zip_path, "/.scalarDiagnostics/scalar_");
699 strbuf_addftime(&zip_path,
700 "%Y%m%d_%H%M%S", localtime_r(&now, &tm), 0, 0);
701 strbuf_addstr(&zip_path, ".zip");
702 switch (safe_create_leading_directories(zip_path.buf)) {
703 case SCLD_EXISTS:
704 case SCLD_OK:
705 break;
706 default:
707 error_errno(_("could not create directory for '%s'"),
708 zip_path.buf);
709 goto diagnose_cleanup;
710 }
711 stdout_fd = dup(1);
712 if (stdout_fd < 0) {
713 res = error_errno(_("could not duplicate stdout"));
714 goto diagnose_cleanup;
715 }
716
717 archiver_fd = xopen(zip_path.buf, O_CREAT | O_WRONLY | O_TRUNC, 0666);
718 if (archiver_fd < 0 || dup2(archiver_fd, 1) < 0) {
719 res = error_errno(_("could not redirect output"));
720 goto diagnose_cleanup;
721 }
722
723 init_zip_archiver();
724 strvec_pushl(&archiver_args, "scalar-diagnose", "--format=zip", NULL);
725
726 strbuf_reset(&buf);
727 strbuf_addstr(&buf, "Collecting diagnostic info\n\n");
728 get_version_info(&buf, 1);
729
730 strbuf_addf(&buf, "Enlistment root: %s\n", the_repository->worktree);
731 get_disk_info(&buf);
732 write_or_die(stdout_fd, buf.buf, buf.len);
733 strvec_pushf(&archiver_args,
734 "--add-virtual-file=diagnostics.log:%.*s",
735 (int)buf.len, buf.buf);
736
737 strbuf_reset(&buf);
738 strbuf_addstr(&buf, "--add-virtual-file=packs-local.txt:");
739 dir_file_stats(the_repository->objects->odb, &buf);
740 foreach_alt_odb(dir_file_stats, &buf);
741 strvec_push(&archiver_args, buf.buf);
742
743 strbuf_reset(&buf);
744 strbuf_addstr(&buf, "--add-virtual-file=objects-local.txt:");
745 loose_objs_stats(&buf, ".git/objects");
746 strvec_push(&archiver_args, buf.buf);
747
748 if ((res = add_directory_to_archiver(&archiver_args, ".git", 0)) ||
749 (res = add_directory_to_archiver(&archiver_args, ".git/hooks", 0)) ||
750 (res = add_directory_to_archiver(&archiver_args, ".git/info", 0)) ||
751 (res = add_directory_to_archiver(&archiver_args, ".git/logs", 1)) ||
752 (res = add_directory_to_archiver(&archiver_args, ".git/objects/info", 0)))
753 goto diagnose_cleanup;
754
755 strvec_pushl(&archiver_args, "--prefix=",
756 oid_to_hex(the_hash_algo->empty_tree), "--", NULL);
757
758 /* `write_archive()` modifies the `argv` passed to it. Let it. */
759 argv_copy = xmemdupz(archiver_args.v,
760 sizeof(char *) * archiver_args.nr);
761 res = write_archive(archiver_args.nr, (const char **)argv_copy, NULL,
762 the_repository, NULL, 0);
763 if (res) {
764 error(_("failed to write archive"));
765 goto diagnose_cleanup;
766 }
767
768 if (!res)
769 fprintf(stderr, "\n"
770 "Diagnostics complete.\n"
771 "All of the gathered info is captured in '%s'\n",
772 zip_path.buf);
773
774 diagnose_cleanup:
775 if (archiver_fd >= 0) {
776 close(1);
777 dup2(stdout_fd, 1);
778 }
779 free(argv_copy);
780 strvec_clear(&archiver_args);
781 strbuf_release(&zip_path);
782 strbuf_release(&path);
783 strbuf_release(&buf);
784
785 return res;
786 }
787
788 static int cmd_list(int argc, const char **argv)
789 {
790 if (argc != 1)
791 die(_("`scalar list` does not take arguments"));
792
793 if (run_git("config", "--global", "--get-all", "scalar.repo", NULL) < 0)
794 return -1;
795 return 0;
796 }
797
798 static int cmd_register(int argc, const char **argv)
799 {
800 struct option options[] = {
801 OPT_END(),
802 };
803 const char * const usage[] = {
804 N_("scalar register [<enlistment>]"),
805 NULL
806 };
807
808 argc = parse_options(argc, argv, NULL, options,
809 usage, 0);
810
811 setup_enlistment_directory(argc, argv, usage, options, NULL);
812
813 return register_dir();
814 }
815
816 static int get_scalar_repos(const char *key, const char *value, void *data)
817 {
818 struct string_list *list = data;
819
820 if (!strcmp(key, "scalar.repo"))
821 string_list_append(list, value);
822
823 return 0;
824 }
825
826 static int cmd_reconfigure(int argc, const char **argv)
827 {
828 int all = 0;
829 struct option options[] = {
830 OPT_BOOL('a', "all", &all,
831 N_("reconfigure all registered enlistments")),
832 OPT_END(),
833 };
834 const char * const usage[] = {
835 N_("scalar reconfigure [--all | <enlistment>]"),
836 NULL
837 };
838 struct string_list scalar_repos = STRING_LIST_INIT_DUP;
839 int i, res = 0;
840 struct repository r = { NULL };
841 struct strbuf commondir = STRBUF_INIT, gitdir = STRBUF_INIT;
842
843 argc = parse_options(argc, argv, NULL, options,
844 usage, 0);
845
846 if (!all) {
847 setup_enlistment_directory(argc, argv, usage, options, NULL);
848
849 return set_recommended_config(1);
850 }
851
852 if (argc > 0)
853 usage_msg_opt(_("--all or <enlistment>, but not both"),
854 usage, options);
855
856 git_config(get_scalar_repos, &scalar_repos);
857
858 for (i = 0; i < scalar_repos.nr; i++) {
859 const char *dir = scalar_repos.items[i].string;
860
861 strbuf_reset(&commondir);
862 strbuf_reset(&gitdir);
863
864 if (chdir(dir) < 0) {
865 warning_errno(_("could not switch to '%s'"), dir);
866 res = -1;
867 } else if (discover_git_directory(&commondir, &gitdir) < 0) {
868 warning_errno(_("git repository gone in '%s'"), dir);
869 res = -1;
870 } else {
871 git_config_clear();
872
873 the_repository = &r;
874 r.commondir = commondir.buf;
875 r.gitdir = gitdir.buf;
876
877 if (set_recommended_config(1) < 0)
878 res = -1;
879 }
880 }
881
882 string_list_clear(&scalar_repos, 1);
883 strbuf_release(&commondir);
884 strbuf_release(&gitdir);
885
886 return res;
887 }
888
889 static int cmd_run(int argc, const char **argv)
890 {
891 struct option options[] = {
892 OPT_END(),
893 };
894 struct {
895 const char *arg, *task;
896 } tasks[] = {
897 { "config", NULL },
898 { "commit-graph", "commit-graph" },
899 { "fetch", "prefetch" },
900 { "loose-objects", "loose-objects" },
901 { "pack-files", "incremental-repack" },
902 { NULL, NULL }
903 };
904 struct strbuf buf = STRBUF_INIT;
905 const char *usagestr[] = { NULL, NULL };
906 int i;
907
908 strbuf_addstr(&buf, N_("scalar run <task> [<enlistment>]\nTasks:\n"));
909 for (i = 0; tasks[i].arg; i++)
910 strbuf_addf(&buf, "\t%s\n", tasks[i].arg);
911 usagestr[0] = buf.buf;
912
913 argc = parse_options(argc, argv, NULL, options,
914 usagestr, 0);
915
916 if (!argc)
917 usage_with_options(usagestr, options);
918
919 if (!strcmp("all", argv[0])) {
920 i = -1;
921 } else {
922 for (i = 0; tasks[i].arg && strcmp(tasks[i].arg, argv[0]); i++)
923 ; /* keep looking for the task */
924
925 if (i > 0 && !tasks[i].arg) {
926 error(_("no such task: '%s'"), argv[0]);
927 usage_with_options(usagestr, options);
928 }
929 }
930
931 argc--;
932 argv++;
933 setup_enlistment_directory(argc, argv, usagestr, options, NULL);
934 strbuf_release(&buf);
935
936 if (i == 0)
937 return register_dir();
938
939 if (i > 0)
940 return run_git("maintenance", "run",
941 "--task", tasks[i].task, NULL);
942
943 if (register_dir())
944 return -1;
945 for (i = 1; tasks[i].arg; i++)
946 if (run_git("maintenance", "run",
947 "--task", tasks[i].task, NULL))
948 return -1;
949 return 0;
950 }
951
952 static int remove_deleted_enlistment(struct strbuf *path)
953 {
954 int res = 0;
955 strbuf_realpath_forgiving(path, path->buf, 1);
956
957 if (run_git("config", "--global",
958 "--unset", "--fixed-value",
959 "scalar.repo", path->buf, NULL) < 0)
960 res = -1;
961
962 if (run_git("config", "--global",
963 "--unset", "--fixed-value",
964 "maintenance.repo", path->buf, NULL) < 0)
965 res = -1;
966
967 return res;
968 }
969
970 static int cmd_unregister(int argc, const char **argv)
971 {
972 struct option options[] = {
973 OPT_END(),
974 };
975 const char * const usage[] = {
976 N_("scalar unregister [<enlistment>]"),
977 NULL
978 };
979
980 argc = parse_options(argc, argv, NULL, options,
981 usage, 0);
982
983 /*
984 * Be forgiving when the enlistment or worktree does not even exist any
985 * longer; This can be the case if a user deleted the worktree by
986 * mistake and _still_ wants to unregister the thing.
987 */
988 if (argc == 1) {
989 struct strbuf src_path = STRBUF_INIT, workdir_path = STRBUF_INIT;
990
991 strbuf_addf(&src_path, "%s/src/.git", argv[0]);
992 strbuf_addf(&workdir_path, "%s/.git", argv[0]);
993 if (!is_directory(src_path.buf) && !is_directory(workdir_path.buf)) {
994 /* remove possible matching registrations */
995 int res = -1;
996
997 strbuf_strip_suffix(&src_path, "/.git");
998 res = remove_deleted_enlistment(&src_path) && res;
999
1000 strbuf_strip_suffix(&workdir_path, "/.git");
1001 res = remove_deleted_enlistment(&workdir_path) && res;
1002
1003 strbuf_release(&src_path);
1004 strbuf_release(&workdir_path);
1005 return res;
1006 }
1007 strbuf_release(&src_path);
1008 strbuf_release(&workdir_path);
1009 }
1010
1011 setup_enlistment_directory(argc, argv, usage, options, NULL);
1012
1013 return unregister_dir();
1014 }
1015
1016 static int cmd_delete(int argc, const char **argv)
1017 {
1018 char *cwd = xgetcwd();
1019 struct option options[] = {
1020 OPT_END(),
1021 };
1022 const char * const usage[] = {
1023 N_("scalar delete <enlistment>"),
1024 NULL
1025 };
1026 struct strbuf enlistment = STRBUF_INIT;
1027 int res = 0;
1028
1029 argc = parse_options(argc, argv, NULL, options,
1030 usage, 0);
1031
1032 if (argc != 1)
1033 usage_with_options(usage, options);
1034
1035 setup_enlistment_directory(argc, argv, usage, options, &enlistment);
1036
1037 if (dir_inside_of(cwd, enlistment.buf) >= 0)
1038 res = error(_("refusing to delete current working directory"));
1039 else {
1040 close_object_store(the_repository->objects);
1041 res = delete_enlistment(&enlistment);
1042 }
1043 strbuf_release(&enlistment);
1044 free(cwd);
1045
1046 return res;
1047 }
1048
1049 static int cmd_version(int argc, const char **argv)
1050 {
1051 int verbose = 0, build_options = 0;
1052 struct option options[] = {
1053 OPT__VERBOSE(&verbose, N_("include Git version")),
1054 OPT_BOOL(0, "build-options", &build_options,
1055 N_("include Git's build options")),
1056 OPT_END(),
1057 };
1058 const char * const usage[] = {
1059 N_("scalar verbose [-v | --verbose] [--build-options]"),
1060 NULL
1061 };
1062 struct strbuf buf = STRBUF_INIT;
1063
1064 argc = parse_options(argc, argv, NULL, options,
1065 usage, 0);
1066
1067 if (argc != 0)
1068 usage_with_options(usage, options);
1069
1070 get_version_info(&buf, build_options);
1071 fprintf(stderr, "%s\n", buf.buf);
1072 strbuf_release(&buf);
1073
1074 return 0;
1075 }
1076
1077 static struct {
1078 const char *name;
1079 int (*fn)(int, const char **);
1080 } builtins[] = {
1081 { "clone", cmd_clone },
1082 { "list", cmd_list },
1083 { "register", cmd_register },
1084 { "unregister", cmd_unregister },
1085 { "run", cmd_run },
1086 { "reconfigure", cmd_reconfigure },
1087 { "delete", cmd_delete },
1088 { "version", cmd_version },
1089 { "diagnose", cmd_diagnose },
1090 { NULL, NULL},
1091 };
1092
1093 int cmd_main(int argc, const char **argv)
1094 {
1095 struct strbuf scalar_usage = STRBUF_INIT;
1096 int i;
1097
1098 while (argc > 1 && *argv[1] == '-') {
1099 if (!strcmp(argv[1], "-C")) {
1100 if (argc < 3)
1101 die(_("-C requires a <directory>"));
1102 if (chdir(argv[2]) < 0)
1103 die_errno(_("could not change to '%s'"),
1104 argv[2]);
1105 argc -= 2;
1106 argv += 2;
1107 } else if (!strcmp(argv[1], "-c")) {
1108 if (argc < 3)
1109 die(_("-c requires a <key>=<value> argument"));
1110 git_config_push_parameter(argv[2]);
1111 argc -= 2;
1112 argv += 2;
1113 } else
1114 break;
1115 }
1116
1117 if (argc > 1) {
1118 argv++;
1119 argc--;
1120
1121 for (i = 0; builtins[i].name; i++)
1122 if (!strcmp(builtins[i].name, argv[0]))
1123 return !!builtins[i].fn(argc, argv);
1124 }
1125
1126 strbuf_addstr(&scalar_usage,
1127 N_("scalar [-C <directory>] [-c <key>=<value>] "
1128 "<command> [<options>]\n\nCommands:\n"));
1129 for (i = 0; builtins[i].name; i++)
1130 strbuf_addf(&scalar_usage, "\t%s\n", builtins[i].name);
1131
1132 usage(scalar_usage.buf);
1133 }