4 * Based on git-am.sh by Junio C Hamano.
9 #include "parse-options.h"
11 #include "run-command.h"
14 #include "cache-tree.h"
21 * Returns 1 if the file is empty or does not exist, 0 otherwise.
23 static int is_empty_file(const char *filename
)
27 if (stat(filename
, &st
) < 0) {
30 die_errno(_("could not stat %s"), filename
);
37 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
39 static int strbuf_getline_crlf(struct strbuf
*sb
, FILE *fp
)
41 if (strbuf_getwholeline(sb
, fp
, '\n'))
43 if (sb
->buf
[sb
->len
- 1] == '\n') {
44 strbuf_setlen(sb
, sb
->len
- 1);
45 if (sb
->len
> 0 && sb
->buf
[sb
->len
- 1] == '\r')
46 strbuf_setlen(sb
, sb
->len
- 1);
52 * Returns the length of the first line of msg.
54 static int linelen(const char *msg
)
56 return strchrnul(msg
, '\n') - msg
;
60 PATCH_FORMAT_UNKNOWN
= 0,
65 /* state directory path */
68 /* current and last patch numbers, 1-indexed */
72 /* commit metadata and message */
79 /* number of digits in patch filename */
84 * Initializes am_state with the default values. The state directory is set to
87 static void am_state_init(struct am_state
*state
, const char *dir
)
89 memset(state
, 0, sizeof(*state
));
92 state
->dir
= xstrdup(dir
);
98 * Releases memory allocated by an am_state.
100 static void am_state_release(struct am_state
*state
)
103 free(state
->author_name
);
104 free(state
->author_email
);
105 free(state
->author_date
);
110 * Returns path relative to the am_state directory.
112 static inline const char *am_path(const struct am_state
*state
, const char *path
)
114 return mkpath("%s/%s", state
->dir
, path
);
118 * Returns 1 if there is an am session in progress, 0 otherwise.
120 static int am_in_progress(const struct am_state
*state
)
124 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
126 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
128 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
134 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
135 * number of bytes read on success, -1 if the file does not exist. If `trim` is
136 * set, trailing whitespace will be removed.
138 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
139 const char *file
, int trim
)
143 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
153 die_errno(_("could not read '%s'"), am_path(state
, file
));
157 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
158 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
159 * match `key`. Returns NULL on failure.
161 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
164 static char *read_shell_var(FILE *fp
, const char *key
)
166 struct strbuf sb
= STRBUF_INIT
;
169 if (strbuf_getline(&sb
, fp
, '\n'))
172 if (!skip_prefix(sb
.buf
, key
, &str
))
175 if (!skip_prefix(str
, "=", &str
))
178 strbuf_remove(&sb
, 0, str
- sb
.buf
);
180 str
= sq_dequote(sb
.buf
);
184 return strbuf_detach(&sb
, NULL
);
192 * Reads and parses the state directory's "author-script" file, and sets
193 * state->author_name, state->author_email and state->author_date accordingly.
194 * Returns 0 on success, -1 if the file could not be parsed.
196 * The author script is of the format:
198 * GIT_AUTHOR_NAME='$author_name'
199 * GIT_AUTHOR_EMAIL='$author_email'
200 * GIT_AUTHOR_DATE='$author_date'
202 * where $author_name, $author_email and $author_date are quoted. We are strict
203 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
204 * script, and thus if the file differs from what this function expects, it is
205 * better to bail out than to do something that the user does not expect.
207 static int read_author_script(struct am_state
*state
)
209 const char *filename
= am_path(state
, "author-script");
212 assert(!state
->author_name
);
213 assert(!state
->author_email
);
214 assert(!state
->author_date
);
216 fp
= fopen(filename
, "r");
220 die_errno(_("could not open '%s' for reading"), filename
);
223 state
->author_name
= read_shell_var(fp
, "GIT_AUTHOR_NAME");
224 if (!state
->author_name
) {
229 state
->author_email
= read_shell_var(fp
, "GIT_AUTHOR_EMAIL");
230 if (!state
->author_email
) {
235 state
->author_date
= read_shell_var(fp
, "GIT_AUTHOR_DATE");
236 if (!state
->author_date
) {
241 if (fgetc(fp
) != EOF
) {
251 * Saves state->author_name, state->author_email and state->author_date in the
252 * state directory's "author-script" file.
254 static void write_author_script(const struct am_state
*state
)
256 struct strbuf sb
= STRBUF_INIT
;
258 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
259 sq_quote_buf(&sb
, state
->author_name
);
260 strbuf_addch(&sb
, '\n');
262 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
263 sq_quote_buf(&sb
, state
->author_email
);
264 strbuf_addch(&sb
, '\n');
266 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
267 sq_quote_buf(&sb
, state
->author_date
);
268 strbuf_addch(&sb
, '\n');
270 write_file(am_path(state
, "author-script"), 1, "%s", sb
.buf
);
276 * Reads the commit message from the state directory's "final-commit" file,
277 * setting state->msg to its contents and state->msg_len to the length of its
280 * Returns 0 on success, -1 if the file does not exist.
282 static int read_commit_msg(struct am_state
*state
)
284 struct strbuf sb
= STRBUF_INIT
;
288 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
293 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
298 * Saves state->msg in the state directory's "final-commit" file.
300 static void write_commit_msg(const struct am_state
*state
)
303 const char *filename
= am_path(state
, "final-commit");
305 fd
= xopen(filename
, O_WRONLY
| O_CREAT
, 0666);
306 if (write_in_full(fd
, state
->msg
, state
->msg_len
) < 0)
307 die_errno(_("could not write to %s"), filename
);
312 * Loads state from disk.
314 static void am_load(struct am_state
*state
)
316 struct strbuf sb
= STRBUF_INIT
;
318 if (read_state_file(&sb
, state
, "next", 1) < 0)
319 die("BUG: state file 'next' does not exist");
320 state
->cur
= strtol(sb
.buf
, NULL
, 10);
322 if (read_state_file(&sb
, state
, "last", 1) < 0)
323 die("BUG: state file 'last' does not exist");
324 state
->last
= strtol(sb
.buf
, NULL
, 10);
326 if (read_author_script(state
) < 0)
327 die(_("could not parse author script"));
329 read_commit_msg(state
);
335 * Removes the am_state directory, forcefully terminating the current am
338 static void am_destroy(const struct am_state
*state
)
340 struct strbuf sb
= STRBUF_INIT
;
342 strbuf_addstr(&sb
, state
->dir
);
343 remove_dir_recursively(&sb
, 0);
348 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
349 * non-indented lines and checking if they look like they begin with valid
350 * header field names.
352 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
354 static int is_mail(FILE *fp
)
356 const char *header_regex
= "^[!-9;-~]+:";
357 struct strbuf sb
= STRBUF_INIT
;
361 if (fseek(fp
, 0L, SEEK_SET
))
362 die_errno(_("fseek failed"));
364 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
365 die("invalid pattern: %s", header_regex
);
367 while (!strbuf_getline_crlf(&sb
, fp
)) {
369 break; /* End of header */
371 /* Ignore indented folded lines */
372 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
375 /* It's a header if it matches header_regex */
376 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
389 * Attempts to detect the patch_format of the patches contained in `paths`,
390 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
393 static int detect_patch_format(const char **paths
)
395 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
396 struct strbuf l1
= STRBUF_INIT
;
400 * We default to mbox format if input is from stdin and for directories
402 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
403 return PATCH_FORMAT_MBOX
;
406 * Otherwise, check the first few lines of the first patch, starting
407 * from the first non-blank line, to try to detect its format.
410 fp
= xfopen(*paths
, "r");
412 while (!strbuf_getline_crlf(&l1
, fp
)) {
417 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
418 ret
= PATCH_FORMAT_MBOX
;
422 if (l1
.len
&& is_mail(fp
)) {
423 ret
= PATCH_FORMAT_MBOX
;
434 * Splits out individual email patches from `paths`, where each path is either
435 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
437 static int split_mail_mbox(struct am_state
*state
, const char **paths
)
439 struct child_process cp
= CHILD_PROCESS_INIT
;
440 struct strbuf last
= STRBUF_INIT
;
443 argv_array_push(&cp
.args
, "mailsplit");
444 argv_array_pushf(&cp
.args
, "-d%d", state
->prec
);
445 argv_array_pushf(&cp
.args
, "-o%s", state
->dir
);
446 argv_array_push(&cp
.args
, "-b");
447 argv_array_push(&cp
.args
, "--");
448 argv_array_pushv(&cp
.args
, paths
);
450 if (capture_command(&cp
, &last
, 8))
454 state
->last
= strtol(last
.buf
, NULL
, 10);
460 * Splits a list of files/directories into individual email patches. Each path
461 * in `paths` must be a file/directory that is formatted according to
464 * Once split out, the individual email patches will be stored in the state
465 * directory, with each patch's filename being its index, padded to state->prec
468 * state->cur will be set to the index of the first mail, and state->last will
469 * be set to the index of the last mail.
471 * Returns 0 on success, -1 on failure.
473 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
476 switch (patch_format
) {
477 case PATCH_FORMAT_MBOX
:
478 return split_mail_mbox(state
, paths
);
480 die("BUG: invalid patch_format");
486 * Setup a new am session for applying patches
488 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
492 patch_format
= detect_patch_format(paths
);
495 fprintf_ln(stderr
, _("Patch format detection failed."));
499 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
500 die_errno(_("failed to create directory '%s'"), state
->dir
);
502 if (split_mail(state
, patch_format
, paths
) < 0) {
504 die(_("Failed to split patches."));
508 * NOTE: Since the "next" and "last" files determine if an am_state
509 * session is in progress, they should be written last.
512 write_file(am_path(state
, "next"), 1, "%d", state
->cur
);
514 write_file(am_path(state
, "last"), 1, "%d", state
->last
);
518 * Increments the patch pointer, and cleans am_state for the application of the
521 static void am_next(struct am_state
*state
)
523 free(state
->author_name
);
524 state
->author_name
= NULL
;
526 free(state
->author_email
);
527 state
->author_email
= NULL
;
529 free(state
->author_date
);
530 state
->author_date
= NULL
;
536 unlink(am_path(state
, "author-script"));
537 unlink(am_path(state
, "final-commit"));
540 write_file(am_path(state
, "next"), 1, "%d", state
->cur
);
544 * Returns the filename of the current patch email.
546 static const char *msgnum(const struct am_state
*state
)
548 static struct strbuf sb
= STRBUF_INIT
;
551 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
557 * Refresh and write index.
559 static void refresh_and_write_cache(void)
561 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
563 hold_locked_index(lock_file
, 1);
564 refresh_cache(REFRESH_QUIET
);
565 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
566 die(_("unable to write index file"));
570 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
571 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
572 * strbuf is provided, the space-separated list of files that differ will be
575 static int index_has_changes(struct strbuf
*sb
)
577 unsigned char head
[GIT_SHA1_RAWSZ
];
580 if (!get_sha1_tree("HEAD", head
)) {
581 struct diff_options opt
;
584 DIFF_OPT_SET(&opt
, EXIT_WITH_STATUS
);
586 DIFF_OPT_SET(&opt
, QUICK
);
587 do_diff_cache(head
, &opt
);
589 for (i
= 0; sb
&& i
< diff_queued_diff
.nr
; i
++) {
591 strbuf_addch(sb
, ' ');
592 strbuf_addstr(sb
, diff_queued_diff
.queue
[i
]->two
->path
);
595 return DIFF_OPT_TST(&opt
, HAS_CHANGES
) != 0;
597 for (i
= 0; sb
&& i
< active_nr
; i
++) {
599 strbuf_addch(sb
, ' ');
600 strbuf_addstr(sb
, active_cache
[i
]->name
);
607 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
608 * state->msg will be set to the patch message. state->author_name,
609 * state->author_email and state->author_date will be set to the patch author's
610 * name, email and date respectively. The patch body will be written to the
611 * state directory's "patch" file.
613 * Returns 1 if the patch should be skipped, 0 otherwise.
615 static int parse_mail(struct am_state
*state
, const char *mail
)
618 struct child_process cp
= CHILD_PROCESS_INIT
;
619 struct strbuf sb
= STRBUF_INIT
;
620 struct strbuf msg
= STRBUF_INIT
;
621 struct strbuf author_name
= STRBUF_INIT
;
622 struct strbuf author_date
= STRBUF_INIT
;
623 struct strbuf author_email
= STRBUF_INIT
;
627 cp
.in
= xopen(mail
, O_RDONLY
, 0);
628 cp
.out
= xopen(am_path(state
, "info"), O_WRONLY
| O_CREAT
, 0777);
630 argv_array_push(&cp
.args
, "mailinfo");
631 argv_array_push(&cp
.args
, am_path(state
, "msg"));
632 argv_array_push(&cp
.args
, am_path(state
, "patch"));
634 if (run_command(&cp
) < 0)
635 die("could not parse patch");
640 /* Extract message and author information */
641 fp
= xfopen(am_path(state
, "info"), "r");
642 while (!strbuf_getline(&sb
, fp
, '\n')) {
645 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
647 strbuf_addch(&msg
, '\n');
648 strbuf_addstr(&msg
, x
);
649 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
650 strbuf_addstr(&author_name
, x
);
651 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
652 strbuf_addstr(&author_email
, x
);
653 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
654 strbuf_addstr(&author_date
, x
);
658 /* Skip pine's internal folder data */
659 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
664 if (is_empty_file(am_path(state
, "patch"))) {
665 printf_ln(_("Patch is empty. Was it split wrong?"));
669 strbuf_addstr(&msg
, "\n\n");
670 if (strbuf_read_file(&msg
, am_path(state
, "msg"), 0) < 0)
671 die_errno(_("could not read '%s'"), am_path(state
, "msg"));
674 assert(!state
->author_name
);
675 state
->author_name
= strbuf_detach(&author_name
, NULL
);
677 assert(!state
->author_email
);
678 state
->author_email
= strbuf_detach(&author_email
, NULL
);
680 assert(!state
->author_date
);
681 state
->author_date
= strbuf_detach(&author_date
, NULL
);
684 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
687 strbuf_release(&msg
);
688 strbuf_release(&author_date
);
689 strbuf_release(&author_email
);
690 strbuf_release(&author_name
);
696 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise.
698 static int run_apply(const struct am_state
*state
)
700 struct child_process cp
= CHILD_PROCESS_INIT
;
704 argv_array_push(&cp
.args
, "apply");
705 argv_array_push(&cp
.args
, "--index");
706 argv_array_push(&cp
.args
, am_path(state
, "patch"));
708 if (run_command(&cp
))
711 /* Reload index as git-apply will have modified it. */
719 * Commits the current index with state->msg as the commit message and
720 * state->author_name, state->author_email and state->author_date as the author
723 static void do_commit(const struct am_state
*state
)
725 unsigned char tree
[GIT_SHA1_RAWSZ
], parent
[GIT_SHA1_RAWSZ
],
726 commit
[GIT_SHA1_RAWSZ
];
728 struct commit_list
*parents
= NULL
;
729 const char *reflog_msg
, *author
;
730 struct strbuf sb
= STRBUF_INIT
;
732 if (write_cache_as_tree(tree
, 0, NULL
))
733 die(_("git write-tree failed to write a tree"));
735 if (!get_sha1_commit("HEAD", parent
)) {
737 commit_list_insert(lookup_commit(parent
), &parents
);
740 fprintf_ln(stderr
, _("applying to an empty history"));
743 author
= fmt_ident(state
->author_name
, state
->author_email
,
744 state
->author_date
, IDENT_STRICT
);
746 if (commit_tree(state
->msg
, state
->msg_len
, tree
, parents
, commit
,
748 die(_("failed to write commit object"));
750 reflog_msg
= getenv("GIT_REFLOG_ACTION");
754 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
757 update_ref(sb
.buf
, "HEAD", commit
, ptr
, 0, UPDATE_REFS_DIE_ON_ERR
);
763 * Applies all queued mail.
765 static void am_run(struct am_state
*state
)
767 const char *argv_gc_auto
[] = {"gc", "--auto", NULL
};
768 struct strbuf sb
= STRBUF_INIT
;
770 refresh_and_write_cache();
772 if (index_has_changes(&sb
))
773 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb
.buf
);
777 while (state
->cur
<= state
->last
) {
778 const char *mail
= am_path(state
, msgnum(state
));
780 if (!file_exists(mail
))
783 if (parse_mail(state
, mail
))
784 goto next
; /* mail should be skipped */
786 write_author_script(state
);
787 write_commit_msg(state
);
789 printf_ln(_("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
791 if (run_apply(state
) < 0) {
792 int advice_amworkdir
= 1;
794 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
795 linelen(state
->msg
), state
->msg
);
797 git_config_get_bool("advice.amworkdir", &advice_amworkdir
);
799 if (advice_amworkdir
)
800 printf_ln(_("The copy of the patch that failed is found in: %s"),
801 am_path(state
, "patch"));
813 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
817 * parse_options() callback that validates and sets opt->value to the
818 * PATCH_FORMAT_* enum value corresponding to `arg`.
820 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
822 int *opt_value
= opt
->value
;
824 if (!strcmp(arg
, "mbox"))
825 *opt_value
= PATCH_FORMAT_MBOX
;
827 return error(_("Invalid value for --patch-format: %s"), arg
);
831 int cmd_am(int argc
, const char **argv
, const char *prefix
)
833 struct am_state state
;
834 int patch_format
= PATCH_FORMAT_UNKNOWN
;
836 const char * const usage
[] = {
837 N_("git am [options] [(<mbox>|<Maildir>)...]"),
841 struct option options
[] = {
842 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
843 N_("format the patch(es) are in"),
844 parse_opt_patchformat
),
849 * NEEDSWORK: Once all the features of git-am.sh have been
850 * re-implemented in builtin/am.c, this preamble can be removed.
852 if (!getenv("_GIT_USE_BUILTIN_AM")) {
853 const char *path
= mkpath("%s/git-am", git_exec_path());
855 if (sane_execvp(path
, (char **)argv
) < 0)
856 die_errno("could not exec %s", path
);
858 prefix
= setup_git_directory();
859 trace_repo_setup(prefix
);
863 git_config(git_default_config
, NULL
);
865 am_state_init(&state
, git_path("rebase-apply"));
867 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
869 if (read_index_preload(&the_index
, NULL
) < 0)
870 die(_("failed to read the index"));
872 if (am_in_progress(&state
))
875 struct argv_array paths
= ARGV_ARRAY_INIT
;
878 for (i
= 0; i
< argc
; i
++) {
879 if (is_absolute_path(argv
[i
]) || !prefix
)
880 argv_array_push(&paths
, argv
[i
]);
882 argv_array_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
885 am_setup(&state
, patch_format
, paths
.argv
);
887 argv_array_clear(&paths
);
892 am_state_release(&state
);