Coverage Report

Created: 2024-09-08 06:23

/src/git/builtin/commit.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Builtin "git commit"
3
 *
4
 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5
 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
6
 */
7
8
#include "builtin.h"
9
#include "advice.h"
10
#include "config.h"
11
#include "lockfile.h"
12
#include "cache-tree.h"
13
#include "color.h"
14
#include "dir.h"
15
#include "editor.h"
16
#include "environment.h"
17
#include "diff.h"
18
#include "commit.h"
19
#include "gettext.h"
20
#include "revision.h"
21
#include "wt-status.h"
22
#include "run-command.h"
23
#include "strbuf.h"
24
#include "object-name.h"
25
#include "parse-options.h"
26
#include "path.h"
27
#include "preload-index.h"
28
#include "read-cache.h"
29
#include "string-list.h"
30
#include "rerere.h"
31
#include "unpack-trees.h"
32
#include "column.h"
33
#include "sequencer.h"
34
#include "sparse-index.h"
35
#include "mailmap.h"
36
#include "help.h"
37
#include "commit-reach.h"
38
#include "commit-graph.h"
39
#include "pretty.h"
40
#include "trailer.h"
41
42
static const char * const builtin_commit_usage[] = {
43
  N_("git commit [-a | --interactive | --patch] [-s] [-v] [-u<mode>] [--amend]\n"
44
     "           [--dry-run] [(-c | -C | --squash) <commit> | --fixup [(amend|reword):]<commit>]\n"
45
     "           [-F <file> | -m <msg>] [--reset-author] [--allow-empty]\n"
46
     "           [--allow-empty-message] [--no-verify] [-e] [--author=<author>]\n"
47
     "           [--date=<date>] [--cleanup=<mode>] [--[no-]status]\n"
48
     "           [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
49
     "           [(--trailer <token>[(=|:)<value>])...] [-S[<keyid>]]\n"
50
     "           [--] [<pathspec>...]"),
51
  NULL
52
};
53
54
static const char * const builtin_status_usage[] = {
55
  N_("git status [<options>] [--] [<pathspec>...]"),
56
  NULL
57
};
58
59
static const char empty_amend_advice[] =
60
N_("You asked to amend the most recent commit, but doing so would make\n"
61
"it empty. You can repeat your command with --allow-empty, or you can\n"
62
"remove the commit entirely with \"git reset HEAD^\".\n");
63
64
static const char empty_cherry_pick_advice[] =
65
N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
66
"If you wish to commit it anyway, use:\n"
67
"\n"
68
"    git commit --allow-empty\n"
69
"\n");
70
71
static const char empty_rebase_pick_advice[] =
72
N_("Otherwise, please use 'git rebase --skip'\n");
73
74
static const char empty_cherry_pick_advice_single[] =
75
N_("Otherwise, please use 'git cherry-pick --skip'\n");
76
77
static const char empty_cherry_pick_advice_multi[] =
78
N_("and then use:\n"
79
"\n"
80
"    git cherry-pick --continue\n"
81
"\n"
82
"to resume cherry-picking the remaining commits.\n"
83
"If you wish to skip this commit, use:\n"
84
"\n"
85
"    git cherry-pick --skip\n"
86
"\n");
87
88
static const char *color_status_slots[] = {
89
  [WT_STATUS_HEADER]    = "header",
90
  [WT_STATUS_UPDATED]   = "updated",
91
  [WT_STATUS_CHANGED]   = "changed",
92
  [WT_STATUS_UNTRACKED]   = "untracked",
93
  [WT_STATUS_NOBRANCH]    = "noBranch",
94
  [WT_STATUS_UNMERGED]    = "unmerged",
95
  [WT_STATUS_LOCAL_BRANCH]  = "localBranch",
96
  [WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
97
  [WT_STATUS_ONBRANCH]    = "branch",
98
};
99
100
static const char *use_message_buffer;
101
static struct lock_file index_lock; /* real index */
102
static struct lock_file false_lock; /* used only for partial commits */
103
static enum {
104
  COMMIT_AS_IS = 1,
105
  COMMIT_NORMAL,
106
  COMMIT_PARTIAL
107
} commit_style;
108
109
static const char *force_author;
110
static char *logfile;
111
static char *template_file;
112
/*
113
 * The _message variables are commit names from which to take
114
 * the commit message and/or authorship.
115
 */
116
static const char *author_message, *author_message_buffer;
117
static const char *edit_message, *use_message;
118
static char *fixup_message, *fixup_commit, *squash_message;
119
static const char *fixup_prefix;
120
static int all, also, interactive, patch_interactive, only, amend, signoff;
121
static int edit_flag = -1; /* unspecified */
122
static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
123
static int config_commit_verbose = -1; /* unspecified */
124
static int no_post_rewrite, allow_empty_message, pathspec_file_nul;
125
static const char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
126
static const char *sign_commit, *pathspec_from_file;
127
static struct strvec trailer_args = STRVEC_INIT;
128
129
/*
130
 * The default commit message cleanup mode will remove the lines
131
 * beginning with # (shell comments) and leading and trailing
132
 * whitespaces (empty lines or containing only whitespaces)
133
 * if editor is used, and only the whitespaces if the message
134
 * is specified explicitly.
135
 */
136
static enum commit_msg_cleanup_mode cleanup_mode;
137
static char *cleanup_arg;
138
139
static enum commit_whence whence;
140
static int use_editor = 1, include_status = 1;
141
static int have_option_m;
142
static struct strbuf message = STRBUF_INIT;
143
144
static enum wt_status_format status_format = STATUS_FORMAT_UNSPECIFIED;
145
146
static int opt_parse_porcelain(const struct option *opt, const char *arg, int unset)
147
0
{
148
0
  enum wt_status_format *value = (enum wt_status_format *)opt->value;
149
0
  if (unset)
150
0
    *value = STATUS_FORMAT_NONE;
151
0
  else if (!arg)
152
0
    *value = STATUS_FORMAT_PORCELAIN;
153
0
  else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
154
0
    *value = STATUS_FORMAT_PORCELAIN;
155
0
  else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
156
0
    *value = STATUS_FORMAT_PORCELAIN_V2;
157
0
  else
158
0
    die("unsupported porcelain version '%s'", arg);
159
160
0
  return 0;
161
0
}
162
163
static int opt_parse_m(const struct option *opt, const char *arg, int unset)
164
0
{
165
0
  struct strbuf *buf = opt->value;
166
0
  if (unset) {
167
0
    have_option_m = 0;
168
0
    strbuf_setlen(buf, 0);
169
0
  } else {
170
0
    have_option_m = 1;
171
0
    if (buf->len)
172
0
      strbuf_addch(buf, '\n');
173
0
    strbuf_addstr(buf, arg);
174
0
    strbuf_complete_line(buf);
175
0
  }
176
0
  return 0;
177
0
}
178
179
static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
180
0
{
181
0
  const char **value = opt->value;
182
183
0
  BUG_ON_OPT_NEG(unset);
184
185
0
  if (arg != NULL && *arg == '=')
186
0
    arg = arg + 1;
187
188
0
  *value = arg;
189
0
  return 0;
190
0
}
191
192
static void determine_whence(struct wt_status *s)
193
0
{
194
0
  if (file_exists(git_path_merge_head(the_repository)))
195
0
    whence = FROM_MERGE;
196
0
  else if (!sequencer_determine_whence(the_repository, &whence))
197
0
    whence = FROM_COMMIT;
198
0
  if (s)
199
0
    s->whence = whence;
200
0
}
201
202
static void status_init_config(struct wt_status *s, config_fn_t fn)
203
0
{
204
0
  wt_status_prepare(the_repository, s);
205
0
  init_diff_ui_defaults();
206
0
  git_config(fn, s);
207
0
  determine_whence(s);
208
0
  s->hints = advice_enabled(ADVICE_STATUS_HINTS); /* must come after git_config() */
209
0
}
210
211
static void rollback_index_files(void)
212
0
{
213
0
  switch (commit_style) {
214
0
  case COMMIT_AS_IS:
215
0
    break; /* nothing to do */
216
0
  case COMMIT_NORMAL:
217
0
    rollback_lock_file(&index_lock);
218
0
    break;
219
0
  case COMMIT_PARTIAL:
220
0
    rollback_lock_file(&index_lock);
221
0
    rollback_lock_file(&false_lock);
222
0
    break;
223
0
  }
224
0
}
225
226
static int commit_index_files(void)
227
0
{
228
0
  int err = 0;
229
230
0
  switch (commit_style) {
231
0
  case COMMIT_AS_IS:
232
0
    break; /* nothing to do */
233
0
  case COMMIT_NORMAL:
234
0
    err = commit_lock_file(&index_lock);
235
0
    break;
236
0
  case COMMIT_PARTIAL:
237
0
    err = commit_lock_file(&index_lock);
238
0
    rollback_lock_file(&false_lock);
239
0
    break;
240
0
  }
241
242
0
  return err;
243
0
}
244
245
/*
246
 * Take a union of paths in the index and the named tree (typically, "HEAD"),
247
 * and return the paths that match the given pattern in list.
248
 */
249
static int list_paths(struct string_list *list, const char *with_tree,
250
          const struct pathspec *pattern)
251
0
{
252
0
  int i, ret;
253
0
  char *m;
254
255
0
  if (!pattern->nr)
256
0
    return 0;
257
258
0
  m = xcalloc(1, pattern->nr);
259
260
0
  if (with_tree) {
261
0
    char *max_prefix = common_prefix(pattern);
262
0
    overlay_tree_on_index(the_repository->index, with_tree, max_prefix);
263
0
    free(max_prefix);
264
0
  }
265
266
  /* TODO: audit for interaction with sparse-index. */
267
0
  ensure_full_index(the_repository->index);
268
0
  for (i = 0; i < the_repository->index->cache_nr; i++) {
269
0
    const struct cache_entry *ce = the_repository->index->cache[i];
270
0
    struct string_list_item *item;
271
272
0
    if (ce->ce_flags & CE_UPDATE)
273
0
      continue;
274
0
    if (!ce_path_match(the_repository->index, ce, pattern, m))
275
0
      continue;
276
0
    item = string_list_insert(list, ce->name);
277
0
    if (ce_skip_worktree(ce))
278
0
      item->util = item; /* better a valid pointer than a fake one */
279
0
  }
280
281
0
  ret = report_path_error(m, pattern);
282
0
  free(m);
283
0
  return ret;
284
0
}
285
286
static void add_remove_files(struct string_list *list)
287
0
{
288
0
  int i;
289
0
  for (i = 0; i < list->nr; i++) {
290
0
    struct stat st;
291
0
    struct string_list_item *p = &(list->items[i]);
292
293
    /* p->util is skip-worktree */
294
0
    if (p->util)
295
0
      continue;
296
297
0
    if (!lstat(p->string, &st)) {
298
0
      if (add_to_index(the_repository->index, p->string, &st, 0))
299
0
        die(_("updating files failed"));
300
0
    } else
301
0
      remove_file_from_index(the_repository->index, p->string);
302
0
  }
303
0
}
304
305
static void create_base_index(const struct commit *current_head)
306
0
{
307
0
  struct tree *tree;
308
0
  struct unpack_trees_options opts;
309
0
  struct tree_desc t;
310
311
0
  if (!current_head) {
312
0
    discard_index(the_repository->index);
313
0
    return;
314
0
  }
315
316
0
  memset(&opts, 0, sizeof(opts));
317
0
  opts.head_idx = 1;
318
0
  opts.index_only = 1;
319
0
  opts.merge = 1;
320
0
  opts.src_index = the_repository->index;
321
0
  opts.dst_index = the_repository->index;
322
323
0
  opts.fn = oneway_merge;
324
0
  tree = parse_tree_indirect(&current_head->object.oid);
325
0
  if (!tree)
326
0
    die(_("failed to unpack HEAD tree object"));
327
0
  if (parse_tree(tree) < 0)
328
0
    exit(128);
329
0
  init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
330
0
  if (unpack_trees(1, &t, &opts))
331
0
    exit(128); /* We've already reported the error, finish dying */
332
0
}
333
334
static void refresh_cache_or_die(int refresh_flags)
335
0
{
336
  /*
337
   * refresh_flags contains REFRESH_QUIET, so the only errors
338
   * are for unmerged entries.
339
   */
340
0
  if (refresh_index(the_repository->index, refresh_flags | REFRESH_IN_PORCELAIN, NULL, NULL, NULL))
341
0
    die_resolve_conflict("commit");
342
0
}
343
344
static const char *prepare_index(const char **argv, const char *prefix,
345
         const struct commit *current_head, int is_status)
346
0
{
347
0
  struct string_list partial = STRING_LIST_INIT_DUP;
348
0
  struct pathspec pathspec;
349
0
  int refresh_flags = REFRESH_QUIET;
350
0
  const char *ret;
351
352
0
  if (is_status)
353
0
    refresh_flags |= REFRESH_UNMERGED;
354
0
  parse_pathspec(&pathspec, 0,
355
0
           PATHSPEC_PREFER_FULL,
356
0
           prefix, argv);
357
358
0
  if (pathspec_from_file) {
359
0
    if (interactive)
360
0
      die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--interactive/--patch");
361
362
0
    if (all)
363
0
      die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "-a");
364
365
0
    if (pathspec.nr)
366
0
      die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
367
368
0
    parse_pathspec_file(&pathspec, 0,
369
0
            PATHSPEC_PREFER_FULL,
370
0
            prefix, pathspec_from_file, pathspec_file_nul);
371
0
  } else if (pathspec_file_nul) {
372
0
    die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
373
0
  }
374
375
0
  if (!pathspec.nr && (also || (only && !allow_empty &&
376
0
      (!amend || (fixup_message && strcmp(fixup_prefix, "amend"))))))
377
0
    die(_("No paths with --include/--only does not make sense."));
378
379
0
  if (repo_read_index_preload(the_repository, &pathspec, 0) < 0)
380
0
    die(_("index file corrupt"));
381
382
0
  if (interactive) {
383
0
    char *old_index_env = NULL, *old_repo_index_file;
384
0
    repo_hold_locked_index(the_repository, &index_lock,
385
0
               LOCK_DIE_ON_ERROR);
386
387
0
    refresh_cache_or_die(refresh_flags);
388
389
0
    if (write_locked_index(the_repository->index, &index_lock, 0))
390
0
      die(_("unable to create temporary index"));
391
392
0
    old_repo_index_file = the_repository->index_file;
393
0
    the_repository->index_file =
394
0
      (char *)get_lock_file_path(&index_lock);
395
0
    old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
396
0
    setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
397
398
0
    if (interactive_add(argv, prefix, patch_interactive) != 0)
399
0
      die(_("interactive add failed"));
400
401
0
    the_repository->index_file = old_repo_index_file;
402
0
    if (old_index_env && *old_index_env)
403
0
      setenv(INDEX_ENVIRONMENT, old_index_env, 1);
404
0
    else
405
0
      unsetenv(INDEX_ENVIRONMENT);
406
0
    FREE_AND_NULL(old_index_env);
407
408
0
    discard_index(the_repository->index);
409
0
    read_index_from(the_repository->index, get_lock_file_path(&index_lock),
410
0
        get_git_dir());
411
0
    if (cache_tree_update(the_repository->index, WRITE_TREE_SILENT) == 0) {
412
0
      if (reopen_lock_file(&index_lock) < 0)
413
0
        die(_("unable to write index file"));
414
0
      if (write_locked_index(the_repository->index, &index_lock, 0))
415
0
        die(_("unable to update temporary index"));
416
0
    } else
417
0
      warning(_("Failed to update main cache tree"));
418
419
0
    commit_style = COMMIT_NORMAL;
420
0
    ret = get_lock_file_path(&index_lock);
421
0
    goto out;
422
0
  }
423
424
  /*
425
   * Non partial, non as-is commit.
426
   *
427
   * (1) get the real index;
428
   * (2) update the_index as necessary;
429
   * (3) write the_index out to the real index (still locked);
430
   * (4) return the name of the locked index file.
431
   *
432
   * The caller should run hooks on the locked real index, and
433
   * (A) if all goes well, commit the real index;
434
   * (B) on failure, rollback the real index.
435
   */
436
0
  if (all || (also && pathspec.nr)) {
437
0
    char *ps_matched = xcalloc(pathspec.nr, 1);
438
0
    repo_hold_locked_index(the_repository, &index_lock,
439
0
               LOCK_DIE_ON_ERROR);
440
0
    add_files_to_cache(the_repository, also ? prefix : NULL,
441
0
           &pathspec, ps_matched, 0, 0);
442
0
    if (!all && report_path_error(ps_matched, &pathspec))
443
0
      exit(128);
444
445
0
    refresh_cache_or_die(refresh_flags);
446
0
    cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
447
0
    if (write_locked_index(the_repository->index, &index_lock, 0))
448
0
      die(_("unable to write new index file"));
449
0
    commit_style = COMMIT_NORMAL;
450
0
    ret = get_lock_file_path(&index_lock);
451
0
    free(ps_matched);
452
0
    goto out;
453
0
  }
454
455
  /*
456
   * As-is commit.
457
   *
458
   * (1) return the name of the real index file.
459
   *
460
   * The caller should run hooks on the real index,
461
   * and create commit from the_index.
462
   * We still need to refresh the index here.
463
   */
464
0
  if (!only && !pathspec.nr) {
465
0
    repo_hold_locked_index(the_repository, &index_lock,
466
0
               LOCK_DIE_ON_ERROR);
467
0
    refresh_cache_or_die(refresh_flags);
468
0
    if (the_repository->index->cache_changed
469
0
        || !cache_tree_fully_valid(the_repository->index->cache_tree))
470
0
      cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
471
0
    if (write_locked_index(the_repository->index, &index_lock,
472
0
               COMMIT_LOCK | SKIP_IF_UNCHANGED))
473
0
      die(_("unable to write new index file"));
474
0
    commit_style = COMMIT_AS_IS;
475
0
    ret = get_index_file();
476
0
    goto out;
477
0
  }
478
479
  /*
480
   * A partial commit.
481
   *
482
   * (0) find the set of affected paths;
483
   * (1) get lock on the real index file;
484
   * (2) update the_index with the given paths;
485
   * (3) write the_index out to the real index (still locked);
486
   * (4) get lock on the false index file;
487
   * (5) reset the_index from HEAD;
488
   * (6) update the_index the same way as (2);
489
   * (7) write the_index out to the false index file;
490
   * (8) return the name of the false index file (still locked);
491
   *
492
   * The caller should run hooks on the locked false index, and
493
   * create commit from it.  Then
494
   * (A) if all goes well, commit the real index;
495
   * (B) on failure, rollback the real index;
496
   * In either case, rollback the false index.
497
   */
498
0
  commit_style = COMMIT_PARTIAL;
499
500
0
  if (whence != FROM_COMMIT) {
501
0
    if (whence == FROM_MERGE)
502
0
      die(_("cannot do a partial commit during a merge."));
503
0
    else if (is_from_cherry_pick(whence))
504
0
      die(_("cannot do a partial commit during a cherry-pick."));
505
0
    else if (is_from_rebase(whence))
506
0
      die(_("cannot do a partial commit during a rebase."));
507
0
  }
508
509
0
  if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
510
0
    exit(1);
511
512
0
  discard_index(the_repository->index);
513
0
  if (repo_read_index(the_repository) < 0)
514
0
    die(_("cannot read the index"));
515
516
0
  repo_hold_locked_index(the_repository, &index_lock, LOCK_DIE_ON_ERROR);
517
0
  add_remove_files(&partial);
518
0
  refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
519
0
  cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
520
0
  if (write_locked_index(the_repository->index, &index_lock, 0))
521
0
    die(_("unable to write new index file"));
522
523
0
  hold_lock_file_for_update(&false_lock,
524
0
          git_path("next-index-%"PRIuMAX,
525
0
             (uintmax_t) getpid()),
526
0
          LOCK_DIE_ON_ERROR);
527
528
0
  create_base_index(current_head);
529
0
  add_remove_files(&partial);
530
0
  refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
531
532
0
  if (write_locked_index(the_repository->index, &false_lock, 0))
533
0
    die(_("unable to write temporary index file"));
534
535
0
  discard_index(the_repository->index);
536
0
  ret = get_lock_file_path(&false_lock);
537
0
  read_index_from(the_repository->index, ret, get_git_dir());
538
0
out:
539
0
  string_list_clear(&partial, 0);
540
0
  clear_pathspec(&pathspec);
541
0
  return ret;
542
0
}
543
544
static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
545
          struct wt_status *s)
546
0
{
547
0
  struct object_id oid;
548
549
0
  if (s->relative_paths)
550
0
    s->prefix = prefix;
551
552
0
  if (amend) {
553
0
    s->amend = 1;
554
0
    s->reference = "HEAD^1";
555
0
  }
556
0
  s->verbose = verbose;
557
0
  s->index_file = index_file;
558
0
  s->fp = fp;
559
0
  s->nowarn = nowarn;
560
0
  s->is_initial = repo_get_oid(the_repository, s->reference, &oid) ? 1 : 0;
561
0
  if (!s->is_initial)
562
0
    oidcpy(&s->oid_commit, &oid);
563
0
  s->status_format = status_format;
564
0
  s->ignore_submodule_arg = ignore_submodule_arg;
565
566
0
  wt_status_collect(s);
567
0
  wt_status_print(s);
568
0
  wt_status_collect_free_buffers(s);
569
570
0
  return s->committable;
571
0
}
572
573
static int is_a_merge(const struct commit *current_head)
574
0
{
575
0
  return !!(current_head->parents && current_head->parents->next);
576
0
}
577
578
static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
579
0
{
580
0
  if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
581
0
    BUG("unable to parse our own ident: %s", buf->buf);
582
0
}
583
584
static void export_one(const char *var, const char *s, const char *e, int hack)
585
0
{
586
0
  struct strbuf buf = STRBUF_INIT;
587
0
  if (hack)
588
0
    strbuf_addch(&buf, hack);
589
0
  strbuf_add(&buf, s, e - s);
590
0
  setenv(var, buf.buf, 1);
591
0
  strbuf_release(&buf);
592
0
}
593
594
static int parse_force_date(const char *in, struct strbuf *out)
595
0
{
596
0
  strbuf_addch(out, '@');
597
598
0
  if (parse_date(in, out) < 0) {
599
0
    int errors = 0;
600
0
    unsigned long t = approxidate_careful(in, &errors);
601
0
    if (errors)
602
0
      return -1;
603
0
    strbuf_addf(out, "%lu", t);
604
0
  }
605
606
0
  return 0;
607
0
}
608
609
static void set_ident_var(char **buf, char *val)
610
0
{
611
0
  free(*buf);
612
0
  *buf = val;
613
0
}
614
615
static void determine_author_info(struct strbuf *author_ident)
616
0
{
617
0
  char *name, *email, *date;
618
0
  struct ident_split author;
619
620
0
  name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
621
0
  email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
622
0
  date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
623
624
0
  if (author_message) {
625
0
    struct ident_split ident;
626
0
    size_t len;
627
0
    const char *a;
628
629
0
    a = find_commit_header(author_message_buffer, "author", &len);
630
0
    if (!a)
631
0
      die(_("commit '%s' lacks author header"), author_message);
632
0
    if (split_ident_line(&ident, a, len) < 0)
633
0
      die(_("commit '%s' has malformed author line"), author_message);
634
635
0
    set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
636
0
    set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
637
638
0
    if (ident.date_begin) {
639
0
      struct strbuf date_buf = STRBUF_INIT;
640
0
      strbuf_addch(&date_buf, '@');
641
0
      strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
642
0
      strbuf_addch(&date_buf, ' ');
643
0
      strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
644
0
      set_ident_var(&date, strbuf_detach(&date_buf, NULL));
645
0
    }
646
0
  }
647
648
0
  if (force_author) {
649
0
    struct ident_split ident;
650
651
0
    if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
652
0
      die(_("malformed --author parameter"));
653
0
    set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
654
0
    set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
655
0
  }
656
657
0
  if (force_date) {
658
0
    struct strbuf date_buf = STRBUF_INIT;
659
0
    if (parse_force_date(force_date, &date_buf))
660
0
      die(_("invalid date format: %s"), force_date);
661
0
    set_ident_var(&date, strbuf_detach(&date_buf, NULL));
662
0
  }
663
664
0
  strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
665
0
        IDENT_STRICT));
666
0
  assert_split_ident(&author, author_ident);
667
0
  export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
668
0
  export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
669
0
  export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
670
0
  free(name);
671
0
  free(email);
672
0
  free(date);
673
0
}
674
675
static int author_date_is_interesting(void)
676
0
{
677
0
  return author_message || force_date;
678
0
}
679
680
static void adjust_comment_line_char(const struct strbuf *sb)
681
0
{
682
0
  char candidates[] = "#;@!$%^&|:";
683
0
  char *candidate;
684
0
  const char *p;
685
686
0
  if (!memchr(sb->buf, candidates[0], sb->len)) {
687
0
    free(comment_line_str_to_free);
688
0
    comment_line_str = comment_line_str_to_free =
689
0
      xstrfmt("%c", candidates[0]);
690
0
    return;
691
0
  }
692
693
0
  p = sb->buf;
694
0
  candidate = strchr(candidates, *p);
695
0
  if (candidate)
696
0
    *candidate = ' ';
697
0
  for (p = sb->buf; *p; p++) {
698
0
    if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
699
0
      candidate = strchr(candidates, p[1]);
700
0
      if (candidate)
701
0
        *candidate = ' ';
702
0
    }
703
0
  }
704
705
0
  for (p = candidates; *p == ' '; p++)
706
0
    ;
707
0
  if (!*p)
708
0
    die(_("unable to select a comment character that is not used\n"
709
0
          "in the current commit message"));
710
0
  free(comment_line_str_to_free);
711
0
  comment_line_str = comment_line_str_to_free = xstrfmt("%c", *p);
712
0
}
713
714
static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
715
        struct pretty_print_context *ctx)
716
0
{
717
0
  const char *buffer, *subject, *fmt;
718
719
0
  buffer = repo_get_commit_buffer(the_repository, commit, NULL);
720
0
  find_commit_subject(buffer, &subject);
721
  /*
722
   * If we amend the 'amend!' commit then we don't want to
723
   * duplicate the subject line.
724
   */
725
0
  fmt = starts_with(subject, "amend!") ? "%b" : "%B";
726
0
  repo_format_commit_message(the_repository, commit, fmt, sb, ctx);
727
0
  repo_unuse_commit_buffer(the_repository, commit, buffer);
728
0
}
729
730
static int prepare_to_commit(const char *index_file, const char *prefix,
731
           struct commit *current_head,
732
           struct wt_status *s,
733
           struct strbuf *author_ident)
734
0
{
735
0
  struct stat statbuf;
736
0
  struct strbuf committer_ident = STRBUF_INIT;
737
0
  int committable;
738
0
  struct strbuf sb = STRBUF_INIT;
739
0
  const char *hook_arg1 = NULL;
740
0
  const char *hook_arg2 = NULL;
741
0
  int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
742
0
  int old_display_comment_prefix;
743
0
  int invoked_hook;
744
745
  /* This checks and barfs if author is badly specified */
746
0
  determine_author_info(author_ident);
747
748
0
  if (!no_verify && run_commit_hook(use_editor, index_file, &invoked_hook,
749
0
            "pre-commit", NULL))
750
0
    return 0;
751
752
0
  if (squash_message) {
753
    /*
754
     * Insert the proper subject line before other commit
755
     * message options add their content.
756
     */
757
0
    if (use_message && !strcmp(use_message, squash_message))
758
0
      strbuf_addstr(&sb, "squash! ");
759
0
    else {
760
0
      struct pretty_print_context ctx = {0};
761
0
      struct commit *c;
762
0
      c = lookup_commit_reference_by_name(squash_message);
763
0
      if (!c)
764
0
        die(_("could not lookup commit '%s'"), squash_message);
765
0
      ctx.output_encoding = get_commit_output_encoding();
766
0
      repo_format_commit_message(the_repository, c,
767
0
               "squash! %s\n\n", &sb,
768
0
               &ctx);
769
0
    }
770
0
  }
771
772
0
  if (have_option_m && !fixup_message) {
773
0
    strbuf_addbuf(&sb, &message);
774
0
    hook_arg1 = "message";
775
0
  } else if (logfile && !strcmp(logfile, "-")) {
776
0
    if (isatty(0))
777
0
      fprintf(stderr, _("(reading log message from standard input)\n"));
778
0
    if (strbuf_read(&sb, 0, 0) < 0)
779
0
      die_errno(_("could not read log from standard input"));
780
0
    hook_arg1 = "message";
781
0
  } else if (logfile) {
782
0
    if (strbuf_read_file(&sb, logfile, 0) < 0)
783
0
      die_errno(_("could not read log file '%s'"),
784
0
          logfile);
785
0
    hook_arg1 = "message";
786
0
  } else if (use_message) {
787
0
    char *buffer;
788
0
    buffer = strstr(use_message_buffer, "\n\n");
789
0
    if (buffer)
790
0
      strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
791
0
    hook_arg1 = "commit";
792
0
    hook_arg2 = use_message;
793
0
  } else if (fixup_message) {
794
0
    struct pretty_print_context ctx = {0};
795
0
    struct commit *commit;
796
0
    char *fmt;
797
0
    commit = lookup_commit_reference_by_name(fixup_commit);
798
0
    if (!commit)
799
0
      die(_("could not lookup commit '%s'"), fixup_commit);
800
0
    ctx.output_encoding = get_commit_output_encoding();
801
0
    fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
802
0
    repo_format_commit_message(the_repository, commit, fmt, &sb,
803
0
             &ctx);
804
0
    free(fmt);
805
0
    hook_arg1 = "message";
806
807
    /*
808
     * Only `-m` commit message option is checked here, as
809
     * it supports `--fixup` to append the commit message.
810
     *
811
     * The other commit message options `-c`/`-C`/`-F` are
812
     * incompatible with all the forms of `--fixup` and
813
     * have already errored out while parsing the `git commit`
814
     * options.
815
     */
816
0
    if (have_option_m && !strcmp(fixup_prefix, "fixup"))
817
0
      strbuf_addbuf(&sb, &message);
818
819
0
    if (!strcmp(fixup_prefix, "amend")) {
820
0
      if (have_option_m)
821
0
        die(_("options '%s' and '%s:%s' cannot be used together"), "-m", "--fixup", fixup_message);
822
0
      prepare_amend_commit(commit, &sb, &ctx);
823
0
    }
824
0
  } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
825
0
    size_t merge_msg_start;
826
827
    /*
828
     * prepend SQUASH_MSG here if it exists and a
829
     * "merge --squash" was originally performed
830
     */
831
0
    if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
832
0
      if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
833
0
        die_errno(_("could not read SQUASH_MSG"));
834
0
      hook_arg1 = "squash";
835
0
    } else
836
0
      hook_arg1 = "merge";
837
838
0
    merge_msg_start = sb.len;
839
0
    if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
840
0
      die_errno(_("could not read MERGE_MSG"));
841
842
0
    if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
843
0
        wt_status_locate_end(sb.buf + merge_msg_start,
844
0
           sb.len - merge_msg_start) <
845
0
        sb.len - merge_msg_start)
846
0
      s->added_cut_line = 1;
847
0
  } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
848
0
    if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
849
0
      die_errno(_("could not read SQUASH_MSG"));
850
0
    hook_arg1 = "squash";
851
0
  } else if (template_file) {
852
0
    if (strbuf_read_file(&sb, template_file, 0) < 0)
853
0
      die_errno(_("could not read '%s'"), template_file);
854
0
    hook_arg1 = "template";
855
0
    clean_message_contents = 0;
856
0
  }
857
858
  /*
859
   * The remaining cases don't modify the template message, but
860
   * just set the argument(s) to the prepare-commit-msg hook.
861
   */
862
0
  else if (whence == FROM_MERGE)
863
0
    hook_arg1 = "merge";
864
0
  else if (is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) {
865
0
    hook_arg1 = "commit";
866
0
    hook_arg2 = "CHERRY_PICK_HEAD";
867
0
  }
868
869
0
  if (squash_message) {
870
    /*
871
     * If squash_commit was used for the commit subject,
872
     * then we're possibly hijacking other commit log options.
873
     * Reset the hook args to tell the real story.
874
     */
875
0
    hook_arg1 = "message";
876
0
    hook_arg2 = "";
877
0
  }
878
879
0
  s->fp = fopen_for_writing(git_path_commit_editmsg());
880
0
  if (!s->fp)
881
0
    die_errno(_("could not open '%s'"), git_path_commit_editmsg());
882
883
  /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
884
0
  old_display_comment_prefix = s->display_comment_prefix;
885
0
  s->display_comment_prefix = 1;
886
887
  /*
888
   * Most hints are counter-productive when the commit has
889
   * already started.
890
   */
891
0
  s->hints = 0;
892
893
0
  if (clean_message_contents)
894
0
    strbuf_stripspace(&sb, NULL);
895
896
0
  if (signoff)
897
0
    append_signoff(&sb, ignored_log_message_bytes(sb.buf, sb.len), 0);
898
899
0
  if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
900
0
    die_errno(_("could not write commit template"));
901
902
0
  if (auto_comment_line_char)
903
0
    adjust_comment_line_char(&sb);
904
0
  strbuf_release(&sb);
905
906
  /* This checks if committer ident is explicitly given */
907
0
  strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
908
0
  if (use_editor && include_status) {
909
0
    int ident_shown = 0;
910
0
    int saved_color_setting;
911
0
    struct ident_split ci, ai;
912
0
    const char *hint_cleanup_all = allow_empty_message ?
913
0
      _("Please enter the commit message for your changes."
914
0
        " Lines starting\nwith '%s' will be ignored.\n") :
915
0
      _("Please enter the commit message for your changes."
916
0
        " Lines starting\nwith '%s' will be ignored, and an empty"
917
0
        " message aborts the commit.\n");
918
0
    const char *hint_cleanup_space = allow_empty_message ?
919
0
      _("Please enter the commit message for your changes."
920
0
        " Lines starting\n"
921
0
        "with '%s' will be kept; you may remove them"
922
0
        " yourself if you want to.\n") :
923
0
      _("Please enter the commit message for your changes."
924
0
        " Lines starting\n"
925
0
        "with '%s' will be kept; you may remove them"
926
0
        " yourself if you want to.\n"
927
0
        "An empty message aborts the commit.\n");
928
0
    if (whence != FROM_COMMIT) {
929
0
      if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
930
0
        wt_status_add_cut_line(s);
931
0
      status_printf_ln(
932
0
        s, GIT_COLOR_NORMAL,
933
0
        whence == FROM_MERGE ?
934
0
                _("\n"
935
0
            "It looks like you may be committing a merge.\n"
936
0
            "If this is not correct, please run\n"
937
0
            " git update-ref -d MERGE_HEAD\n"
938
0
            "and try again.\n") :
939
0
                _("\n"
940
0
            "It looks like you may be committing a cherry-pick.\n"
941
0
            "If this is not correct, please run\n"
942
0
            " git update-ref -d CHERRY_PICK_HEAD\n"
943
0
            "and try again.\n"));
944
0
    }
945
946
0
    fprintf(s->fp, "\n");
947
0
    if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
948
0
      status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_all, comment_line_str);
949
0
    else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
950
0
      if (whence == FROM_COMMIT)
951
0
        wt_status_add_cut_line(s);
952
0
    } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
953
0
      status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_space, comment_line_str);
954
955
    /*
956
     * These should never fail because they come from our own
957
     * fmt_ident. They may fail the sane_ident test, but we know
958
     * that the name and mail pointers will at least be valid,
959
     * which is enough for our tests and printing here.
960
     */
961
0
    assert_split_ident(&ai, author_ident);
962
0
    assert_split_ident(&ci, &committer_ident);
963
964
0
    if (ident_cmp(&ai, &ci))
965
0
      status_printf_ln(s, GIT_COLOR_NORMAL,
966
0
        _("%s"
967
0
        "Author:    %.*s <%.*s>"),
968
0
        ident_shown++ ? "" : "\n",
969
0
        (int)(ai.name_end - ai.name_begin), ai.name_begin,
970
0
        (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
971
972
0
    if (author_date_is_interesting())
973
0
      status_printf_ln(s, GIT_COLOR_NORMAL,
974
0
        _("%s"
975
0
        "Date:      %s"),
976
0
        ident_shown++ ? "" : "\n",
977
0
        show_ident_date(&ai, DATE_MODE(NORMAL)));
978
979
0
    if (!committer_ident_sufficiently_given())
980
0
      status_printf_ln(s, GIT_COLOR_NORMAL,
981
0
        _("%s"
982
0
        "Committer: %.*s <%.*s>"),
983
0
        ident_shown++ ? "" : "\n",
984
0
        (int)(ci.name_end - ci.name_begin), ci.name_begin,
985
0
        (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
986
987
0
    status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
988
989
0
    saved_color_setting = s->use_color;
990
0
    s->use_color = 0;
991
0
    committable = run_status(s->fp, index_file, prefix, 1, s);
992
0
    s->use_color = saved_color_setting;
993
0
    string_list_clear(&s->change, 1);
994
0
  } else {
995
0
    struct object_id oid;
996
0
    const char *parent = "HEAD";
997
998
0
    if (!the_repository->index->initialized && repo_read_index(the_repository) < 0)
999
0
      die(_("Cannot read index"));
1000
1001
0
    if (amend)
1002
0
      parent = "HEAD^1";
1003
1004
0
    if (repo_get_oid(the_repository, parent, &oid)) {
1005
0
      int i, ita_nr = 0;
1006
1007
      /* TODO: audit for interaction with sparse-index. */
1008
0
      ensure_full_index(the_repository->index);
1009
0
      for (i = 0; i < the_repository->index->cache_nr; i++)
1010
0
        if (ce_intent_to_add(the_repository->index->cache[i]))
1011
0
          ita_nr++;
1012
0
      committable = the_repository->index->cache_nr - ita_nr > 0;
1013
0
    } else {
1014
      /*
1015
       * Unless the user did explicitly request a submodule
1016
       * ignore mode by passing a command line option we do
1017
       * not ignore any changed submodule SHA-1s when
1018
       * comparing index and parent, no matter what is
1019
       * configured. Otherwise we won't commit any
1020
       * submodules which were manually staged, which would
1021
       * be really confusing.
1022
       */
1023
0
      struct diff_flags flags = DIFF_FLAGS_INIT;
1024
0
      flags.override_submodule_config = 1;
1025
0
      if (ignore_submodule_arg &&
1026
0
          !strcmp(ignore_submodule_arg, "all"))
1027
0
        flags.ignore_submodules = 1;
1028
0
      committable = index_differs_from(the_repository,
1029
0
               parent, &flags, 1);
1030
0
    }
1031
0
  }
1032
0
  strbuf_release(&committer_ident);
1033
1034
0
  fclose(s->fp);
1035
1036
0
  if (trailer_args.nr) {
1037
0
    if (amend_file_with_trailers(git_path_commit_editmsg(), &trailer_args))
1038
0
      die(_("unable to pass trailers to --trailers"));
1039
0
    strvec_clear(&trailer_args);
1040
0
  }
1041
1042
  /*
1043
   * Reject an attempt to record a non-merge empty commit without
1044
   * explicit --allow-empty. In the cherry-pick case, it may be
1045
   * empty due to conflict resolution, which the user should okay.
1046
   */
1047
0
  if (!committable && whence != FROM_MERGE && !allow_empty &&
1048
0
      !(amend && is_a_merge(current_head))) {
1049
0
    s->hints = advice_enabled(ADVICE_STATUS_HINTS);
1050
0
    s->display_comment_prefix = old_display_comment_prefix;
1051
0
    run_status(stdout, index_file, prefix, 0, s);
1052
0
    if (amend)
1053
0
      fputs(_(empty_amend_advice), stderr);
1054
0
    else if (is_from_cherry_pick(whence) ||
1055
0
       whence == FROM_REBASE_PICK) {
1056
0
      fputs(_(empty_cherry_pick_advice), stderr);
1057
0
      if (whence == FROM_CHERRY_PICK_SINGLE)
1058
0
        fputs(_(empty_cherry_pick_advice_single), stderr);
1059
0
      else if (whence == FROM_CHERRY_PICK_MULTI)
1060
0
        fputs(_(empty_cherry_pick_advice_multi), stderr);
1061
0
      else
1062
0
        fputs(_(empty_rebase_pick_advice), stderr);
1063
0
    }
1064
0
    return 0;
1065
0
  }
1066
1067
0
  if (!no_verify && invoked_hook) {
1068
    /*
1069
     * Re-read the index as the pre-commit-commit hook was invoked
1070
     * and could have updated it. We must do this before we invoke
1071
     * the editor and after we invoke run_status above.
1072
     */
1073
0
    discard_index(the_repository->index);
1074
0
  }
1075
0
  read_index_from(the_repository->index, index_file, get_git_dir());
1076
1077
0
  if (cache_tree_update(the_repository->index, 0)) {
1078
0
    error(_("Error building trees"));
1079
0
    return 0;
1080
0
  }
1081
1082
0
  if (run_commit_hook(use_editor, index_file, NULL, "prepare-commit-msg",
1083
0
          git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1084
0
    return 0;
1085
1086
0
  if (use_editor) {
1087
0
    struct strvec env = STRVEC_INIT;
1088
1089
0
    strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1090
0
    if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1091
0
      fprintf(stderr,
1092
0
      _("Please supply the message using either -m or -F option.\n"));
1093
0
      exit(1);
1094
0
    }
1095
0
    strvec_clear(&env);
1096
0
  }
1097
1098
0
  if (!no_verify &&
1099
0
      run_commit_hook(use_editor, index_file, NULL, "commit-msg",
1100
0
          git_path_commit_editmsg(), NULL)) {
1101
0
    return 0;
1102
0
  }
1103
1104
0
  return 1;
1105
0
}
1106
1107
static const char *find_author_by_nickname(const char *name)
1108
0
{
1109
0
  struct rev_info revs;
1110
0
  struct commit *commit;
1111
0
  struct strbuf buf = STRBUF_INIT;
1112
0
  const char *av[20];
1113
0
  int ac = 0;
1114
1115
0
  repo_init_revisions(the_repository, &revs, NULL);
1116
0
  strbuf_addf(&buf, "--author=%s", name);
1117
0
  av[++ac] = "--all";
1118
0
  av[++ac] = "-i";
1119
0
  av[++ac] = buf.buf;
1120
0
  av[++ac] = NULL;
1121
0
  setup_revisions(ac, av, &revs, NULL);
1122
0
  revs.mailmap = xmalloc(sizeof(struct string_list));
1123
0
  string_list_init_nodup(revs.mailmap);
1124
0
  read_mailmap(revs.mailmap);
1125
1126
0
  if (prepare_revision_walk(&revs))
1127
0
    die(_("revision walk setup failed"));
1128
0
  commit = get_revision(&revs);
1129
0
  if (commit) {
1130
0
    struct pretty_print_context ctx = {0};
1131
0
    ctx.date_mode.type = DATE_NORMAL;
1132
0
    strbuf_release(&buf);
1133
0
    repo_format_commit_message(the_repository, commit,
1134
0
             "%aN <%aE>", &buf, &ctx);
1135
0
    release_revisions(&revs);
1136
0
    return strbuf_detach(&buf, NULL);
1137
0
  }
1138
0
  die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1139
0
}
1140
1141
static void handle_ignored_arg(struct wt_status *s)
1142
0
{
1143
0
  if (!ignored_arg)
1144
0
    ; /* default already initialized */
1145
0
  else if (!strcmp(ignored_arg, "traditional"))
1146
0
    s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1147
0
  else if (!strcmp(ignored_arg, "no"))
1148
0
    s->show_ignored_mode = SHOW_NO_IGNORED;
1149
0
  else if (!strcmp(ignored_arg, "matching"))
1150
0
    s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1151
0
  else
1152
0
    die(_("Invalid ignored mode '%s'"), ignored_arg);
1153
0
}
1154
1155
static enum untracked_status_type parse_untracked_setting_name(const char *u)
1156
0
{
1157
  /*
1158
   * Please update $__git_untracked_file_modes in
1159
   * git-completion.bash when you add new options
1160
   */
1161
0
  switch (git_parse_maybe_bool(u)) {
1162
0
  case 0:
1163
0
    u = "no";
1164
0
    break;
1165
0
  case 1:
1166
0
    u = "normal";
1167
0
    break;
1168
0
  default:
1169
0
    break;
1170
0
  }
1171
1172
0
  if (!strcmp(u, "no"))
1173
0
    return SHOW_NO_UNTRACKED_FILES;
1174
0
  else if (!strcmp(u, "normal"))
1175
0
    return SHOW_NORMAL_UNTRACKED_FILES;
1176
0
  else if (!strcmp(u, "all"))
1177
0
    return SHOW_ALL_UNTRACKED_FILES;
1178
0
  else
1179
0
    return SHOW_UNTRACKED_FILES_ERROR;
1180
0
}
1181
1182
static void handle_untracked_files_arg(struct wt_status *s)
1183
0
{
1184
0
  enum untracked_status_type u;
1185
1186
0
  if (!untracked_files_arg)
1187
0
    return; /* default already initialized */
1188
1189
0
  u = parse_untracked_setting_name(untracked_files_arg);
1190
0
  if (u == SHOW_UNTRACKED_FILES_ERROR)
1191
0
    die(_("Invalid untracked files mode '%s'"),
1192
0
        untracked_files_arg);
1193
0
  s->show_untracked_files = u;
1194
0
}
1195
1196
static const char *read_commit_message(const char *name)
1197
0
{
1198
0
  const char *out_enc;
1199
0
  struct commit *commit;
1200
1201
0
  commit = lookup_commit_reference_by_name(name);
1202
0
  if (!commit)
1203
0
    die(_("could not lookup commit '%s'"), name);
1204
0
  out_enc = get_commit_output_encoding();
1205
0
  return repo_logmsg_reencode(the_repository, commit, NULL, out_enc);
1206
0
}
1207
1208
/*
1209
 * Enumerate what needs to be propagated when --porcelain
1210
 * is not in effect here.
1211
 */
1212
static struct status_deferred_config {
1213
  enum wt_status_format status_format;
1214
  int show_branch;
1215
  enum ahead_behind_flags ahead_behind;
1216
} status_deferred_config = {
1217
  STATUS_FORMAT_UNSPECIFIED,
1218
  -1, /* unspecified */
1219
  AHEAD_BEHIND_UNSPECIFIED,
1220
};
1221
1222
static void finalize_deferred_config(struct wt_status *s)
1223
0
{
1224
0
  int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1225
0
           status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1226
0
           !s->null_termination);
1227
1228
0
  if (s->null_termination) {
1229
0
    if (status_format == STATUS_FORMAT_NONE ||
1230
0
        status_format == STATUS_FORMAT_UNSPECIFIED)
1231
0
      status_format = STATUS_FORMAT_PORCELAIN;
1232
0
    else if (status_format == STATUS_FORMAT_LONG)
1233
0
      die(_("options '%s' and '%s' cannot be used together"), "--long", "-z");
1234
0
  }
1235
1236
0
  if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1237
0
    status_format = status_deferred_config.status_format;
1238
0
  if (status_format == STATUS_FORMAT_UNSPECIFIED)
1239
0
    status_format = STATUS_FORMAT_NONE;
1240
1241
0
  if (use_deferred_config && s->show_branch < 0)
1242
0
    s->show_branch = status_deferred_config.show_branch;
1243
0
  if (s->show_branch < 0)
1244
0
    s->show_branch = 0;
1245
1246
  /*
1247
   * If the user did not give a "--[no]-ahead-behind" command
1248
   * line argument *AND* we will print in a human-readable format
1249
   * (short, long etc.) then we inherit from the status.aheadbehind
1250
   * config setting.  In all other cases (and porcelain V[12] formats
1251
   * in particular), we inherit _FULL for backwards compatibility.
1252
   */
1253
0
  if (use_deferred_config &&
1254
0
      s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1255
0
    s->ahead_behind_flags = status_deferred_config.ahead_behind;
1256
1257
0
  if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1258
0
    s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1259
0
}
1260
1261
0
static void check_fixup_reword_options(int argc, const char *argv[]) {
1262
0
  if (whence != FROM_COMMIT) {
1263
0
    if (whence == FROM_MERGE)
1264
0
      die(_("You are in the middle of a merge -- cannot reword."));
1265
0
    else if (is_from_cherry_pick(whence))
1266
0
      die(_("You are in the middle of a cherry-pick -- cannot reword."));
1267
0
  }
1268
0
  if (argc)
1269
0
    die(_("reword option of '%s' and path '%s' cannot be used together"), "--fixup", *argv);
1270
0
  if (patch_interactive || interactive || all || also || only)
1271
0
    die(_("reword option of '%s' and '%s' cannot be used together"),
1272
0
      "--fixup", "--patch/--interactive/--all/--include/--only");
1273
0
}
1274
1275
static int parse_and_validate_options(int argc, const char *argv[],
1276
              const struct option *options,
1277
              const char * const usage[],
1278
              const char *prefix,
1279
              struct commit *current_head,
1280
              struct wt_status *s)
1281
0
{
1282
0
  argc = parse_options(argc, argv, prefix, options, usage, 0);
1283
0
  finalize_deferred_config(s);
1284
1285
0
  if (force_author && !strchr(force_author, '>'))
1286
0
    force_author = find_author_by_nickname(force_author);
1287
1288
0
  if (force_author && renew_authorship)
1289
0
    die(_("options '%s' and '%s' cannot be used together"), "--reset-author", "--author");
1290
1291
0
  if (logfile || have_option_m || use_message)
1292
0
    use_editor = 0;
1293
1294
  /* Sanity check options */
1295
0
  if (amend && !current_head)
1296
0
    die(_("You have nothing to amend."));
1297
0
  if (amend && whence != FROM_COMMIT) {
1298
0
    if (whence == FROM_MERGE)
1299
0
      die(_("You are in the middle of a merge -- cannot amend."));
1300
0
    else if (is_from_cherry_pick(whence))
1301
0
      die(_("You are in the middle of a cherry-pick -- cannot amend."));
1302
0
    else if (whence == FROM_REBASE_PICK)
1303
0
      die(_("You are in the middle of a rebase -- cannot amend."));
1304
0
  }
1305
0
  if (fixup_message && squash_message)
1306
0
    die(_("options '%s' and '%s' cannot be used together"), "--squash", "--fixup");
1307
0
  die_for_incompatible_opt4(!!use_message, "-C",
1308
0
          !!edit_message, "-c",
1309
0
          !!logfile, "-F",
1310
0
          !!fixup_message, "--fixup");
1311
0
  die_for_incompatible_opt4(have_option_m, "-m",
1312
0
          !!edit_message, "-c",
1313
0
          !!use_message, "-C",
1314
0
          !!logfile, "-F");
1315
0
  if (use_message || edit_message || logfile ||fixup_message || have_option_m)
1316
0
    FREE_AND_NULL(template_file);
1317
0
  if (edit_message)
1318
0
    use_message = edit_message;
1319
0
  if (amend && !use_message && !fixup_message)
1320
0
    use_message = "HEAD";
1321
0
  if (!use_message && !is_from_cherry_pick(whence) &&
1322
0
      !is_from_rebase(whence) && renew_authorship)
1323
0
    die(_("--reset-author can be used only with -C, -c or --amend."));
1324
0
  if (use_message) {
1325
0
    use_message_buffer = read_commit_message(use_message);
1326
0
    if (!renew_authorship) {
1327
0
      author_message = use_message;
1328
0
      author_message_buffer = use_message_buffer;
1329
0
    }
1330
0
  }
1331
0
  if ((is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) &&
1332
0
      !renew_authorship) {
1333
0
    author_message = "CHERRY_PICK_HEAD";
1334
0
    author_message_buffer = read_commit_message(author_message);
1335
0
  }
1336
1337
0
  if (patch_interactive)
1338
0
    interactive = 1;
1339
1340
0
  die_for_incompatible_opt4(also, "-i/--include",
1341
0
          only, "-o/--only",
1342
0
          all, "-a/--all",
1343
0
          interactive, "--interactive/-p/--patch");
1344
0
  if (fixup_message) {
1345
    /*
1346
     * We limit --fixup's suboptions to only alpha characters.
1347
     * If the first character after a run of alpha is colon,
1348
     * then the part before the colon may be a known suboption
1349
     * name like `amend` or `reword`, or a misspelt suboption
1350
     * name. In either case, we treat it as
1351
     * --fixup=<suboption>:<arg>.
1352
     *
1353
     * Otherwise, we are dealing with --fixup=<commit>.
1354
     */
1355
0
    char *p = fixup_message;
1356
0
    while (isalpha(*p))
1357
0
      p++;
1358
0
    if (p > fixup_message && *p == ':') {
1359
0
      *p = '\0';
1360
0
      fixup_commit = p + 1;
1361
0
      if (!strcmp("amend", fixup_message) ||
1362
0
          !strcmp("reword", fixup_message)) {
1363
0
        fixup_prefix = "amend";
1364
0
        allow_empty = 1;
1365
0
        if (*fixup_message == 'r') {
1366
0
          check_fixup_reword_options(argc, argv);
1367
0
          only = 1;
1368
0
        }
1369
0
      } else {
1370
0
        die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1371
0
      }
1372
0
    } else {
1373
0
      fixup_commit = fixup_message;
1374
0
      fixup_prefix = "fixup";
1375
0
      use_editor = 0;
1376
0
    }
1377
0
  }
1378
1379
0
  if (0 <= edit_flag)
1380
0
    use_editor = edit_flag;
1381
1382
0
  cleanup_mode = get_cleanup_mode(cleanup_arg, use_editor);
1383
1384
0
  handle_untracked_files_arg(s);
1385
1386
0
  if (all && argc > 0)
1387
0
    die(_("paths '%s ...' with -a does not make sense"),
1388
0
        argv[0]);
1389
1390
0
  if (status_format != STATUS_FORMAT_NONE)
1391
0
    dry_run = 1;
1392
1393
0
  return argc;
1394
0
}
1395
1396
static int dry_run_commit(const char **argv, const char *prefix,
1397
        const struct commit *current_head, struct wt_status *s)
1398
0
{
1399
0
  int committable;
1400
0
  const char *index_file;
1401
1402
0
  index_file = prepare_index(argv, prefix, current_head, 1);
1403
0
  committable = run_status(stdout, index_file, prefix, 0, s);
1404
0
  rollback_index_files();
1405
1406
0
  return committable ? 0 : 1;
1407
0
}
1408
1409
define_list_config_array_extra(color_status_slots, {"added"});
1410
1411
static int parse_status_slot(const char *slot)
1412
0
{
1413
0
  if (!strcasecmp(slot, "added"))
1414
0
    return WT_STATUS_UPDATED;
1415
1416
0
  return LOOKUP_CONFIG(color_status_slots, slot);
1417
0
}
1418
1419
static int git_status_config(const char *k, const char *v,
1420
           const struct config_context *ctx, void *cb)
1421
0
{
1422
0
  struct wt_status *s = cb;
1423
0
  const char *slot_name;
1424
1425
0
  if (starts_with(k, "column."))
1426
0
    return git_column_config(k, v, "status", &s->colopts);
1427
0
  if (!strcmp(k, "status.submodulesummary")) {
1428
0
    int is_bool;
1429
0
    s->submodule_summary = git_config_bool_or_int(k, v, ctx->kvi,
1430
0
                    &is_bool);
1431
0
    if (is_bool && s->submodule_summary)
1432
0
      s->submodule_summary = -1;
1433
0
    return 0;
1434
0
  }
1435
0
  if (!strcmp(k, "status.short")) {
1436
0
    if (git_config_bool(k, v))
1437
0
      status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1438
0
    else
1439
0
      status_deferred_config.status_format = STATUS_FORMAT_NONE;
1440
0
    return 0;
1441
0
  }
1442
0
  if (!strcmp(k, "status.branch")) {
1443
0
    status_deferred_config.show_branch = git_config_bool(k, v);
1444
0
    return 0;
1445
0
  }
1446
0
  if (!strcmp(k, "status.aheadbehind")) {
1447
0
    status_deferred_config.ahead_behind = git_config_bool(k, v);
1448
0
    return 0;
1449
0
  }
1450
0
  if (!strcmp(k, "status.showstash")) {
1451
0
    s->show_stash = git_config_bool(k, v);
1452
0
    return 0;
1453
0
  }
1454
0
  if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1455
0
    s->use_color = git_config_colorbool(k, v);
1456
0
    return 0;
1457
0
  }
1458
0
  if (!strcmp(k, "status.displaycommentprefix")) {
1459
0
    s->display_comment_prefix = git_config_bool(k, v);
1460
0
    return 0;
1461
0
  }
1462
0
  if (skip_prefix(k, "status.color.", &slot_name) ||
1463
0
      skip_prefix(k, "color.status.", &slot_name)) {
1464
0
    int slot = parse_status_slot(slot_name);
1465
0
    if (slot < 0)
1466
0
      return 0;
1467
0
    if (!v)
1468
0
      return config_error_nonbool(k);
1469
0
    return color_parse(v, s->color_palette[slot]);
1470
0
  }
1471
0
  if (!strcmp(k, "status.relativepaths")) {
1472
0
    s->relative_paths = git_config_bool(k, v);
1473
0
    return 0;
1474
0
  }
1475
0
  if (!strcmp(k, "status.showuntrackedfiles")) {
1476
0
    enum untracked_status_type u;
1477
1478
0
    u = parse_untracked_setting_name(v);
1479
0
    if (u == SHOW_UNTRACKED_FILES_ERROR)
1480
0
      return error(_("Invalid untracked files mode '%s'"), v);
1481
0
    s->show_untracked_files = u;
1482
0
    return 0;
1483
0
  }
1484
0
  if (!strcmp(k, "diff.renamelimit")) {
1485
0
    if (s->rename_limit == -1)
1486
0
      s->rename_limit = git_config_int(k, v, ctx->kvi);
1487
0
    return 0;
1488
0
  }
1489
0
  if (!strcmp(k, "status.renamelimit")) {
1490
0
    s->rename_limit = git_config_int(k, v, ctx->kvi);
1491
0
    return 0;
1492
0
  }
1493
0
  if (!strcmp(k, "diff.renames")) {
1494
0
    if (s->detect_rename == -1)
1495
0
      s->detect_rename = git_config_rename(k, v);
1496
0
    return 0;
1497
0
  }
1498
0
  if (!strcmp(k, "status.renames")) {
1499
0
    s->detect_rename = git_config_rename(k, v);
1500
0
    return 0;
1501
0
  }
1502
0
  return git_diff_ui_config(k, v, ctx, NULL);
1503
0
}
1504
1505
int cmd_status(int argc, const char **argv, const char *prefix)
1506
0
{
1507
0
  static int no_renames = -1;
1508
0
  static const char *rename_score_arg = (const char *)-1;
1509
0
  static struct wt_status s;
1510
0
  unsigned int progress_flag = 0;
1511
0
  int fd;
1512
0
  struct object_id oid;
1513
0
  static struct option builtin_status_options[] = {
1514
0
    OPT__VERBOSE(&verbose, N_("be verbose")),
1515
0
    OPT_SET_INT('s', "short", &status_format,
1516
0
          N_("show status concisely"), STATUS_FORMAT_SHORT),
1517
0
    OPT_BOOL('b', "branch", &s.show_branch,
1518
0
       N_("show branch information")),
1519
0
    OPT_BOOL(0, "show-stash", &s.show_stash,
1520
0
       N_("show stash information")),
1521
0
    OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1522
0
       N_("compute full ahead/behind values")),
1523
0
    OPT_CALLBACK_F(0, "porcelain", &status_format,
1524
0
      N_("version"), N_("machine-readable output"),
1525
0
      PARSE_OPT_OPTARG, opt_parse_porcelain),
1526
0
    OPT_SET_INT(0, "long", &status_format,
1527
0
          N_("show status in long format (default)"),
1528
0
          STATUS_FORMAT_LONG),
1529
0
    OPT_BOOL('z', "null", &s.null_termination,
1530
0
       N_("terminate entries with NUL")),
1531
0
    { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1532
0
      N_("mode"),
1533
0
      N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1534
0
      PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1535
0
    { OPTION_STRING, 0, "ignored", &ignored_arg,
1536
0
      N_("mode"),
1537
0
      N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1538
0
      PARSE_OPT_OPTARG, NULL, (intptr_t)"traditional" },
1539
0
    { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1540
0
      N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1541
0
      PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1542
0
    OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1543
0
    OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1544
0
    OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1545
0
      N_("n"), N_("detect renames, optionally set similarity index"),
1546
0
      PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1547
0
    OPT_END(),
1548
0
  };
1549
1550
0
  if (argc == 2 && !strcmp(argv[1], "-h"))
1551
0
    usage_with_options(builtin_status_usage, builtin_status_options);
1552
1553
0
  prepare_repo_settings(the_repository);
1554
0
  the_repository->settings.command_requires_full_index = 0;
1555
1556
0
  status_init_config(&s, git_status_config);
1557
0
  argc = parse_options(argc, argv, prefix,
1558
0
           builtin_status_options,
1559
0
           builtin_status_usage, 0);
1560
0
  finalize_colopts(&s.colopts, -1);
1561
0
  finalize_deferred_config(&s);
1562
1563
0
  handle_untracked_files_arg(&s);
1564
0
  handle_ignored_arg(&s);
1565
1566
0
  if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1567
0
      s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1568
0
    die(_("Unsupported combination of ignored and untracked-files arguments"));
1569
1570
0
  parse_pathspec(&s.pathspec, 0,
1571
0
           PATHSPEC_PREFER_FULL,
1572
0
           prefix, argv);
1573
1574
0
  if (status_format != STATUS_FORMAT_PORCELAIN &&
1575
0
      status_format != STATUS_FORMAT_PORCELAIN_V2)
1576
0
    progress_flag = REFRESH_PROGRESS;
1577
0
  repo_read_index(the_repository);
1578
0
  refresh_index(the_repository->index,
1579
0
          REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1580
0
          &s.pathspec, NULL, NULL);
1581
1582
0
  if (use_optional_locks())
1583
0
    fd = repo_hold_locked_index(the_repository, &index_lock, 0);
1584
0
  else
1585
0
    fd = -1;
1586
1587
0
  s.is_initial = repo_get_oid(the_repository, s.reference, &oid) ? 1 : 0;
1588
0
  if (!s.is_initial)
1589
0
    oidcpy(&s.oid_commit, &oid);
1590
1591
0
  s.ignore_submodule_arg = ignore_submodule_arg;
1592
0
  s.status_format = status_format;
1593
0
  s.verbose = verbose;
1594
0
  if (no_renames != -1)
1595
0
    s.detect_rename = !no_renames;
1596
0
  if ((intptr_t)rename_score_arg != -1) {
1597
0
    if (s.detect_rename < DIFF_DETECT_RENAME)
1598
0
      s.detect_rename = DIFF_DETECT_RENAME;
1599
0
    if (rename_score_arg)
1600
0
      s.rename_score = parse_rename_score(&rename_score_arg);
1601
0
  }
1602
1603
0
  wt_status_collect(&s);
1604
1605
0
  if (0 <= fd)
1606
0
    repo_update_index_if_able(the_repository, &index_lock);
1607
1608
0
  if (s.relative_paths)
1609
0
    s.prefix = prefix;
1610
1611
0
  wt_status_print(&s);
1612
0
  wt_status_collect_free_buffers(&s);
1613
1614
0
  return 0;
1615
0
}
1616
1617
static int git_commit_config(const char *k, const char *v,
1618
           const struct config_context *ctx, void *cb)
1619
0
{
1620
0
  struct wt_status *s = cb;
1621
1622
0
  if (!strcmp(k, "commit.template"))
1623
0
    return git_config_pathname(&template_file, k, v);
1624
0
  if (!strcmp(k, "commit.status")) {
1625
0
    include_status = git_config_bool(k, v);
1626
0
    return 0;
1627
0
  }
1628
0
  if (!strcmp(k, "commit.cleanup"))
1629
0
    return git_config_string(&cleanup_arg, k, v);
1630
0
  if (!strcmp(k, "commit.gpgsign")) {
1631
0
    sign_commit = git_config_bool(k, v) ? "" : NULL;
1632
0
    return 0;
1633
0
  }
1634
0
  if (!strcmp(k, "commit.verbose")) {
1635
0
    int is_bool;
1636
0
    config_commit_verbose = git_config_bool_or_int(k, v, ctx->kvi,
1637
0
                     &is_bool);
1638
0
    return 0;
1639
0
  }
1640
1641
0
  return git_status_config(k, v, ctx, s);
1642
0
}
1643
1644
int cmd_commit(int argc, const char **argv, const char *prefix)
1645
0
{
1646
0
  static struct wt_status s;
1647
0
  static struct option builtin_commit_options[] = {
1648
0
    OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1649
0
    OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1650
1651
0
    OPT_GROUP(N_("Commit message options")),
1652
0
    OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1653
0
    OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1654
0
    OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1655
0
    OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1656
0
    OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1657
0
    OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1658
    /*
1659
     * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1660
     * and only translate <commit>.
1661
     */
1662
0
    OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1663
0
    OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1664
0
    OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1665
0
    OPT_PASSTHRU_ARGV(0, "trailer", &trailer_args, N_("trailer"), N_("add custom trailer(s)"), PARSE_OPT_NONEG),
1666
0
    OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1667
0
    OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1668
0
    OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1669
0
    OPT_CLEANUP(&cleanup_arg),
1670
0
    OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1671
0
    { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1672
0
      N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1673
    /* end commit message options */
1674
1675
0
    OPT_GROUP(N_("Commit contents options")),
1676
0
    OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1677
0
    OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1678
0
    OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1679
0
    OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1680
0
    OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1681
0
    OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1682
0
    OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1683
0
    OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1684
0
          STATUS_FORMAT_SHORT),
1685
0
    OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1686
0
    OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1687
0
       N_("compute full ahead/behind values")),
1688
0
    OPT_SET_INT(0, "porcelain", &status_format,
1689
0
          N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1690
0
    OPT_SET_INT(0, "long", &status_format,
1691
0
          N_("show status in long format (default)"),
1692
0
          STATUS_FORMAT_LONG),
1693
0
    OPT_BOOL('z', "null", &s.null_termination,
1694
0
       N_("terminate entries with NUL")),
1695
0
    OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1696
0
    OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1697
0
    { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, N_("mode"), N_("show untracked files, optional modes: all, normal, no. (Default: all)"), PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1698
0
    OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1699
0
    OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1700
    /* end commit contents options */
1701
1702
0
    OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1703
0
        N_("ok to record an empty change")),
1704
0
    OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1705
0
        N_("ok to record a change with an empty message")),
1706
1707
0
    OPT_END()
1708
0
  };
1709
1710
0
  struct strbuf sb = STRBUF_INIT;
1711
0
  struct strbuf author_ident = STRBUF_INIT;
1712
0
  const char *index_file, *reflog_msg;
1713
0
  struct object_id oid;
1714
0
  struct commit_list *parents = NULL;
1715
0
  struct stat statbuf;
1716
0
  struct commit *current_head = NULL;
1717
0
  struct commit_extra_header *extra = NULL;
1718
0
  struct strbuf err = STRBUF_INIT;
1719
0
  int ret = 0;
1720
1721
0
  if (argc == 2 && !strcmp(argv[1], "-h"))
1722
0
    usage_with_options(builtin_commit_usage, builtin_commit_options);
1723
1724
0
  prepare_repo_settings(the_repository);
1725
0
  the_repository->settings.command_requires_full_index = 0;
1726
1727
0
  status_init_config(&s, git_commit_config);
1728
0
  s.commit_template = 1;
1729
0
  status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1730
0
  s.colopts = 0;
1731
1732
0
  if (repo_get_oid(the_repository, "HEAD", &oid))
1733
0
    current_head = NULL;
1734
0
  else {
1735
0
    current_head = lookup_commit_or_die(&oid, "HEAD");
1736
0
    if (repo_parse_commit(the_repository, current_head))
1737
0
      die(_("could not parse HEAD commit"));
1738
0
  }
1739
0
  verbose = -1; /* unspecified */
1740
0
  argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1741
0
            builtin_commit_usage,
1742
0
            prefix, current_head, &s);
1743
0
  if (verbose == -1)
1744
0
    verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1745
1746
0
  if (dry_run)
1747
0
    return dry_run_commit(argv, prefix, current_head, &s);
1748
0
  index_file = prepare_index(argv, prefix, current_head, 0);
1749
1750
  /* Set up everything for writing the commit object.  This includes
1751
     running hooks, writing the trees, and interacting with the user.  */
1752
0
  if (!prepare_to_commit(index_file, prefix,
1753
0
             current_head, &s, &author_ident)) {
1754
0
    ret = 1;
1755
0
    rollback_index_files();
1756
0
    goto cleanup;
1757
0
  }
1758
1759
  /* Determine parents */
1760
0
  reflog_msg = getenv("GIT_REFLOG_ACTION");
1761
0
  if (!current_head) {
1762
0
    if (!reflog_msg)
1763
0
      reflog_msg = "commit (initial)";
1764
0
  } else if (amend) {
1765
0
    if (!reflog_msg)
1766
0
      reflog_msg = "commit (amend)";
1767
0
    parents = copy_commit_list(current_head->parents);
1768
0
  } else if (whence == FROM_MERGE) {
1769
0
    struct strbuf m = STRBUF_INIT;
1770
0
    FILE *fp;
1771
0
    int allow_fast_forward = 1;
1772
0
    struct commit_list **pptr = &parents;
1773
1774
0
    if (!reflog_msg)
1775
0
      reflog_msg = "commit (merge)";
1776
0
    pptr = commit_list_append(current_head, pptr);
1777
0
    fp = xfopen(git_path_merge_head(the_repository), "r");
1778
0
    while (strbuf_getline_lf(&m, fp) != EOF) {
1779
0
      struct commit *parent;
1780
1781
0
      parent = get_merge_parent(m.buf);
1782
0
      if (!parent)
1783
0
        die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1784
0
      pptr = commit_list_append(parent, pptr);
1785
0
    }
1786
0
    fclose(fp);
1787
0
    strbuf_release(&m);
1788
0
    if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1789
0
      if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1790
0
        die_errno(_("could not read MERGE_MODE"));
1791
0
      if (!strcmp(sb.buf, "no-ff"))
1792
0
        allow_fast_forward = 0;
1793
0
    }
1794
0
    if (allow_fast_forward)
1795
0
      reduce_heads_replace(&parents);
1796
0
  } else {
1797
0
    if (!reflog_msg)
1798
0
      reflog_msg = is_from_cherry_pick(whence)
1799
0
          ? "commit (cherry-pick)"
1800
0
          : is_from_rebase(whence)
1801
0
          ? "commit (rebase)"
1802
0
          : "commit";
1803
0
    commit_list_insert(current_head, &parents);
1804
0
  }
1805
1806
  /* Finally, get the commit message */
1807
0
  strbuf_reset(&sb);
1808
0
  if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1809
0
    int saved_errno = errno;
1810
0
    rollback_index_files();
1811
0
    die(_("could not read commit message: %s"), strerror(saved_errno));
1812
0
  }
1813
1814
0
  cleanup_message(&sb, cleanup_mode, verbose);
1815
1816
0
  if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1817
0
    rollback_index_files();
1818
0
    fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1819
0
    exit(1);
1820
0
  }
1821
0
  if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1822
0
    rollback_index_files();
1823
0
    fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1824
0
    exit(1);
1825
0
  }
1826
1827
0
  if (fixup_message && starts_with(sb.buf, "amend! ") &&
1828
0
      !allow_empty_message) {
1829
0
    struct strbuf body = STRBUF_INIT;
1830
0
    size_t len = commit_subject_length(sb.buf);
1831
0
    strbuf_addstr(&body, sb.buf + len);
1832
0
    if (message_is_empty(&body, cleanup_mode)) {
1833
0
      rollback_index_files();
1834
0
      fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1835
0
      exit(1);
1836
0
    }
1837
0
    strbuf_release(&body);
1838
0
  }
1839
1840
0
  if (amend) {
1841
0
    const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1842
0
    extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1843
0
  } else {
1844
0
    struct commit_extra_header **tail = &extra;
1845
0
    append_merge_tag_headers(parents, &tail);
1846
0
  }
1847
1848
0
  if (commit_tree_extended(sb.buf, sb.len, &the_repository->index->cache_tree->oid,
1849
0
         parents, &oid, author_ident.buf, NULL,
1850
0
         sign_commit, extra)) {
1851
0
    rollback_index_files();
1852
0
    die(_("failed to write commit object"));
1853
0
  }
1854
1855
0
  if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1856
0
            &err)) {
1857
0
    rollback_index_files();
1858
0
    die("%s", err.buf);
1859
0
  }
1860
1861
0
  sequencer_post_commit_cleanup(the_repository, 0);
1862
0
  unlink(git_path_merge_head(the_repository));
1863
0
  unlink(git_path_merge_msg(the_repository));
1864
0
  unlink(git_path_merge_mode(the_repository));
1865
0
  unlink(git_path_squash_msg(the_repository));
1866
1867
0
  if (commit_index_files())
1868
0
    die(_("repository has been updated, but unable to write\n"
1869
0
          "new index file. Check that disk is not full and quota is\n"
1870
0
          "not exceeded, and then \"git restore --staged :/\" to recover."));
1871
1872
0
  git_test_write_commit_graph_or_die();
1873
1874
0
  repo_rerere(the_repository, 0);
1875
0
  run_auto_maintenance(quiet);
1876
0
  run_commit_hook(use_editor, get_index_file(), NULL, "post-commit",
1877
0
      NULL);
1878
0
  if (amend && !no_post_rewrite) {
1879
0
    commit_post_rewrite(the_repository, current_head, &oid);
1880
0
  }
1881
0
  if (!quiet) {
1882
0
    unsigned int flags = 0;
1883
1884
0
    if (!current_head)
1885
0
      flags |= SUMMARY_INITIAL_COMMIT;
1886
0
    if (author_date_is_interesting())
1887
0
      flags |= SUMMARY_SHOW_AUTHOR_DATE;
1888
0
    print_commit_summary(the_repository, prefix,
1889
0
             &oid, flags);
1890
0
  }
1891
1892
0
  apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1893
1894
0
cleanup:
1895
0
  free_commit_extra_headers(extra);
1896
0
  free_commit_list(parents);
1897
0
  strbuf_release(&author_ident);
1898
0
  strbuf_release(&err);
1899
0
  strbuf_release(&sb);
1900
0
  free(logfile);
1901
0
  free(template_file);
1902
0
  return ret;
1903
0
}