Coverage Report

Created: 2025-12-31 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/advice.c
Line
Count
Source
1
#include "git-compat-util.h"
2
#include "advice.h"
3
#include "config.h"
4
#include "color.h"
5
#include "environment.h"
6
#include "gettext.h"
7
#include "help.h"
8
#include "string-list.h"
9
10
static enum git_colorbool advice_use_color = GIT_COLOR_UNKNOWN;
11
static char advice_colors[][COLOR_MAXLEN] = {
12
  GIT_COLOR_RESET,
13
  GIT_COLOR_YELLOW, /* HINT */
14
};
15
16
enum color_advice {
17
  ADVICE_COLOR_RESET = 0,
18
  ADVICE_COLOR_HINT = 1,
19
};
20
21
static int parse_advise_color_slot(const char *slot)
22
0
{
23
0
  if (!strcasecmp(slot, "reset"))
24
0
    return ADVICE_COLOR_RESET;
25
0
  if (!strcasecmp(slot, "hint"))
26
0
    return ADVICE_COLOR_HINT;
27
0
  return -1;
28
0
}
29
30
static const char *advise_get_color(enum color_advice ix)
31
0
{
32
0
  if (want_color_stderr(advice_use_color))
33
0
    return advice_colors[ix];
34
0
  return "";
35
0
}
36
37
enum advice_level {
38
  ADVICE_LEVEL_NONE = 0,
39
  ADVICE_LEVEL_DISABLED,
40
  ADVICE_LEVEL_ENABLED,
41
};
42
43
static struct {
44
  const char *key;
45
  enum advice_level level;
46
} advice_setting[] = {
47
  [ADVICE_ADD_EMBEDDED_REPO]      = { "addEmbeddedRepo" },
48
  [ADVICE_ADD_EMPTY_PATHSPEC]     = { "addEmptyPathspec" },
49
  [ADVICE_ADD_IGNORED_FILE]     = { "addIgnoredFile" },
50
  [ADVICE_AMBIGUOUS_FETCH_REFSPEC]    = { "ambiguousFetchRefspec" },
51
  [ADVICE_AM_WORK_DIR]        = { "amWorkDir" },
52
  [ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME]  = { "checkoutAmbiguousRemoteBranchName" },
53
  [ADVICE_COMMIT_BEFORE_MERGE]      = { "commitBeforeMerge" },
54
  [ADVICE_DEFAULT_BRANCH_NAME]      = { "defaultBranchName" },
55
  [ADVICE_DETACHED_HEAD]        = { "detachedHead" },
56
  [ADVICE_DIVERGING]        = { "diverging" },
57
  [ADVICE_FETCH_SET_HEAD_WARN]      = { "fetchRemoteHEADWarn" },
58
  [ADVICE_FETCH_SHOW_FORCED_UPDATES]    = { "fetchShowForcedUpdates" },
59
  [ADVICE_FORCE_DELETE_BRANCH]      = { "forceDeleteBranch" },
60
  [ADVICE_GRAFT_FILE_DEPRECATED]      = { "graftFileDeprecated" },
61
  [ADVICE_IGNORED_HOOK]       = { "ignoredHook" },
62
  [ADVICE_IMPLICIT_IDENTITY]      = { "implicitIdentity" },
63
  [ADVICE_MERGE_CONFLICT]       = { "mergeConflict" },
64
  [ADVICE_NESTED_TAG]       = { "nestedTag" },
65
  [ADVICE_OBJECT_NAME_WARNING]      = { "objectNameWarning" },
66
  [ADVICE_PUSH_ALREADY_EXISTS]      = { "pushAlreadyExists" },
67
  [ADVICE_PUSH_FETCH_FIRST]     = { "pushFetchFirst" },
68
  [ADVICE_PUSH_NEEDS_FORCE]     = { "pushNeedsForce" },
69
  [ADVICE_PUSH_NON_FF_CURRENT]      = { "pushNonFFCurrent" },
70
  [ADVICE_PUSH_NON_FF_MATCHING]     = { "pushNonFFMatching" },
71
  [ADVICE_PUSH_REF_NEEDS_UPDATE]      = { "pushRefNeedsUpdate" },
72
  [ADVICE_PUSH_UNQUALIFIED_REF_NAME]    = { "pushUnqualifiedRefName" },
73
  [ADVICE_PUSH_UPDATE_REJECTED]     = { "pushUpdateRejected" },
74
  [ADVICE_PUSH_UPDATE_REJECTED_ALIAS]   = { "pushNonFastForward" }, /* backwards compatibility */
75
  [ADVICE_REBASE_TODO_ERROR]      = { "rebaseTodoError" },
76
  [ADVICE_REF_SYNTAX]       = { "refSyntax" },
77
  [ADVICE_RESET_NO_REFRESH_WARNING]   = { "resetNoRefresh" },
78
  [ADVICE_RESOLVE_CONFLICT]     = { "resolveConflict" },
79
  [ADVICE_RM_HINTS]       = { "rmHints" },
80
  [ADVICE_SEQUENCER_IN_USE]     = { "sequencerInUse" },
81
  [ADVICE_SET_UPSTREAM_FAILURE]     = { "setUpstreamFailure" },
82
  [ADVICE_SKIPPED_CHERRY_PICKS]     = { "skippedCherryPicks" },
83
  [ADVICE_SPARSE_INDEX_EXPANDED]      = { "sparseIndexExpanded" },
84
  [ADVICE_STATUS_AHEAD_BEHIND_WARNING]    = { "statusAheadBehindWarning" },
85
  [ADVICE_STATUS_HINTS]       = { "statusHints" },
86
  [ADVICE_STATUS_U_OPTION]      = { "statusUoption" },
87
  [ADVICE_SUBMODULES_NOT_UPDATED]     = { "submodulesNotUpdated" },
88
  [ADVICE_SUBMODULE_ALTERNATE_ERROR_STRATEGY_DIE] = { "submoduleAlternateErrorStrategyDie" },
89
  [ADVICE_SUBMODULE_MERGE_CONFLICT]               = { "submoduleMergeConflict" },
90
  [ADVICE_SUGGEST_DETACHING_HEAD]     = { "suggestDetachingHead" },
91
  [ADVICE_UPDATE_SPARSE_PATH]     = { "updateSparsePath" },
92
  [ADVICE_WAITING_FOR_EDITOR]     = { "waitingForEditor" },
93
  [ADVICE_WORKTREE_ADD_ORPHAN]      = { "worktreeAddOrphan" },
94
};
95
96
static const char turn_off_instructions[] =
97
N_("\n"
98
   "Disable this message with \"git config set advice.%s false\"");
99
100
static void vadvise(const char *advice, int display_instructions,
101
        const char *key, va_list params)
102
0
{
103
0
  struct strbuf buf = STRBUF_INIT;
104
0
  const char *cp, *np;
105
106
0
  strbuf_vaddf(&buf, advice, params);
107
108
0
  if (display_instructions)
109
0
    strbuf_addf(&buf, turn_off_instructions, key);
110
111
0
  for (cp = buf.buf; *cp; cp = np) {
112
0
    np = strchrnul(cp, '\n');
113
0
    fprintf(stderr, _("%shint:%s%.*s%s\n"),
114
0
      advise_get_color(ADVICE_COLOR_HINT),
115
0
      (np == cp) ? "" : " ",
116
0
      (int)(np - cp), cp,
117
0
      advise_get_color(ADVICE_COLOR_RESET));
118
0
    if (*np)
119
0
      np++;
120
0
  }
121
0
  strbuf_release(&buf);
122
0
}
123
124
void advise(const char *advice, ...)
125
0
{
126
0
  va_list params;
127
0
  va_start(params, advice);
128
0
  vadvise(advice, 0, "", params);
129
0
  va_end(params);
130
0
}
131
132
int advice_enabled(enum advice_type type)
133
0
{
134
0
  int enabled = advice_setting[type].level != ADVICE_LEVEL_DISABLED;
135
0
  static int globally_enabled = -1;
136
137
0
  if (globally_enabled < 0)
138
0
    globally_enabled = git_env_bool(GIT_ADVICE_ENVIRONMENT, 1);
139
0
  if (!globally_enabled)
140
0
    return 0;
141
142
0
  if (type == ADVICE_PUSH_UPDATE_REJECTED)
143
0
    return enabled &&
144
0
           advice_enabled(ADVICE_PUSH_UPDATE_REJECTED_ALIAS);
145
146
0
  return enabled;
147
0
}
148
149
void advise_if_enabled(enum advice_type type, const char *advice, ...)
150
0
{
151
0
  va_list params;
152
153
0
  if (!advice_enabled(type))
154
0
    return;
155
156
0
  va_start(params, advice);
157
0
  vadvise(advice, !advice_setting[type].level, advice_setting[type].key,
158
0
    params);
159
0
  va_end(params);
160
0
}
161
162
int git_default_advice_config(const char *var, const char *value)
163
0
{
164
0
  const char *k, *slot_name;
165
166
0
  if (!strcmp(var, "color.advice")) {
167
0
    advice_use_color = git_config_colorbool(var, value);
168
0
    return 0;
169
0
  }
170
171
0
  if (skip_prefix(var, "color.advice.", &slot_name)) {
172
0
    int slot = parse_advise_color_slot(slot_name);
173
0
    if (slot < 0)
174
0
      return 0;
175
0
    if (!value)
176
0
      return config_error_nonbool(var);
177
0
    return color_parse(value, advice_colors[slot]);
178
0
  }
179
180
0
  if (!skip_prefix(var, "advice.", &k))
181
0
    return 0;
182
183
0
  for (size_t i = 0; i < ARRAY_SIZE(advice_setting); i++) {
184
0
    if (strcasecmp(k, advice_setting[i].key))
185
0
      continue;
186
0
    advice_setting[i].level = git_config_bool(var, value)
187
0
            ? ADVICE_LEVEL_ENABLED
188
0
            : ADVICE_LEVEL_DISABLED;
189
0
    return 0;
190
0
  }
191
192
0
  return 0;
193
0
}
194
195
void list_config_advices(struct string_list *list, const char *prefix)
196
0
{
197
0
  for (size_t i = 0; i < ARRAY_SIZE(advice_setting); i++)
198
0
    list_config_item(list, prefix, advice_setting[i].key);
199
0
}
200
201
int error_resolve_conflict(const char *me)
202
0
{
203
0
  if (!strcmp(me, "cherry-pick"))
204
0
    error(_("Cherry-picking is not possible because you have unmerged files."));
205
0
  else if (!strcmp(me, "commit"))
206
0
    error(_("Committing is not possible because you have unmerged files."));
207
0
  else if (!strcmp(me, "merge"))
208
0
    error(_("Merging is not possible because you have unmerged files."));
209
0
  else if (!strcmp(me, "pull"))
210
0
    error(_("Pulling is not possible because you have unmerged files."));
211
0
  else if (!strcmp(me, "revert"))
212
0
    error(_("Reverting is not possible because you have unmerged files."));
213
0
  else if (!strcmp(me, "rebase"))
214
0
    error(_("Rebasing is not possible because you have unmerged files."));
215
0
  else
216
0
    BUG("Unhandled conflict reason '%s'", me);
217
218
0
  if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
219
    /*
220
     * Message used both when 'git commit' fails and when
221
     * other commands doing a merge do.
222
     */
223
0
    advise(_("Fix them up in the work tree, and then use 'git add/rm <file>'\n"
224
0
       "as appropriate to mark resolution and make a commit."));
225
0
  return -1;
226
0
}
227
228
void NORETURN die_resolve_conflict(const char *me)
229
0
{
230
0
  error_resolve_conflict(me);
231
0
  die(_("Exiting because of an unresolved conflict."));
232
0
}
233
234
void NORETURN die_conclude_merge(void)
235
0
{
236
0
  error(_("You have not concluded your merge (MERGE_HEAD exists)."));
237
0
  if (advice_enabled(ADVICE_RESOLVE_CONFLICT))
238
0
    advise(_("Please, commit your changes before merging."));
239
0
  die(_("Exiting because of unfinished merge."));
240
0
}
241
242
void NORETURN die_ff_impossible(void)
243
0
{
244
0
  advise_if_enabled(ADVICE_DIVERGING,
245
0
    _("Diverging branches can't be fast-forwarded, you need to either:\n"
246
0
    "\n"
247
0
    "\tgit merge --no-ff\n"
248
0
    "\n"
249
0
    "or:\n"
250
0
    "\n"
251
0
    "\tgit rebase\n"));
252
0
  die(_("Not possible to fast-forward, aborting."));
253
0
}
254
255
void advise_on_updating_sparse_paths(struct string_list *pathspec_list)
256
0
{
257
0
  struct string_list_item *item;
258
259
0
  if (!pathspec_list->nr)
260
0
    return;
261
262
0
  fprintf(stderr, _("The following paths and/or pathspecs matched paths that exist\n"
263
0
        "outside of your sparse-checkout definition, so will not be\n"
264
0
        "updated in the index:\n"));
265
0
  for_each_string_list_item(item, pathspec_list)
266
0
    fprintf(stderr, "%s\n", item->string);
267
268
0
  advise_if_enabled(ADVICE_UPDATE_SPARSE_PATH,
269
0
        _("If you intend to update such entries, try one of the following:\n"
270
0
          "* Use the --sparse option.\n"
271
0
          "* Disable or modify the sparsity rules."));
272
0
}
273
274
void detach_advice(const char *new_name)
275
0
{
276
0
  const char *fmt =
277
0
  _("Note: switching to '%s'.\n"
278
0
  "\n"
279
0
  "You are in 'detached HEAD' state. You can look around, make experimental\n"
280
0
  "changes and commit them, and you can discard any commits you make in this\n"
281
0
  "state without impacting any branches by switching back to a branch.\n"
282
0
  "\n"
283
0
  "If you want to create a new branch to retain commits you create, you may\n"
284
0
  "do so (now or later) by using -c with the switch command. Example:\n"
285
0
  "\n"
286
0
  "  git switch -c <new-branch-name>\n"
287
0
  "\n"
288
0
  "Or undo this operation with:\n"
289
0
  "\n"
290
0
  "  git switch -\n"
291
0
  "\n"
292
0
  "Turn off this advice by setting config variable advice.detachedHead to false\n\n");
293
294
0
  fprintf(stderr, fmt, new_name);
295
0
}
296
297
void advise_on_moving_dirty_path(struct string_list *pathspec_list)
298
0
{
299
0
  struct string_list_item *item;
300
301
0
  if (!pathspec_list->nr)
302
0
    return;
303
304
0
  fprintf(stderr, _("The following paths have been moved outside the\n"
305
0
        "sparse-checkout definition but are not sparse due to local\n"
306
0
        "modifications.\n"));
307
0
  for_each_string_list_item(item, pathspec_list)
308
0
    fprintf(stderr, "%s\n", item->string);
309
310
0
  advise_if_enabled(ADVICE_UPDATE_SPARSE_PATH,
311
0
        _("To correct the sparsity of these paths, do the following:\n"
312
0
          "* Use \"git add --sparse <paths>\" to update the index\n"
313
0
          "* Use \"git sparse-checkout reapply\" to apply the sparsity rules"));
314
0
}