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"
19 * Returns 1 if the file is empty or does not exist, 0 otherwise.
21 static int is_empty_file(const char *filename
)
25 if (stat(filename
, &st
) < 0) {
28 die_errno(_("could not stat %s"), filename
);
35 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
37 static int strbuf_getline_crlf(struct strbuf
*sb
, FILE *fp
)
39 if (strbuf_getwholeline(sb
, fp
, '\n'))
41 if (sb
->buf
[sb
->len
- 1] == '\n') {
42 strbuf_setlen(sb
, sb
->len
- 1);
43 if (sb
->len
> 0 && sb
->buf
[sb
->len
- 1] == '\r')
44 strbuf_setlen(sb
, sb
->len
- 1);
50 * Returns the length of the first line of msg.
52 static int linelen(const char *msg
)
54 return strchrnul(msg
, '\n') - msg
;
58 PATCH_FORMAT_UNKNOWN
= 0,
63 /* state directory path */
66 /* current and last patch numbers, 1-indexed */
70 /* commit metadata and message */
77 /* number of digits in patch filename */
82 * Initializes am_state with the default values. The state directory is set to
85 static void am_state_init(struct am_state
*state
, const char *dir
)
87 memset(state
, 0, sizeof(*state
));
90 state
->dir
= xstrdup(dir
);
96 * Releases memory allocated by an am_state.
98 static void am_state_release(struct am_state
*state
)
101 free(state
->author_name
);
102 free(state
->author_email
);
103 free(state
->author_date
);
108 * Returns path relative to the am_state directory.
110 static inline const char *am_path(const struct am_state
*state
, const char *path
)
112 return mkpath("%s/%s", state
->dir
, path
);
116 * Returns 1 if there is an am session in progress, 0 otherwise.
118 static int am_in_progress(const struct am_state
*state
)
122 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
124 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
126 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
132 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
133 * number of bytes read on success, -1 if the file does not exist. If `trim` is
134 * set, trailing whitespace will be removed.
136 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
137 const char *file
, int trim
)
141 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
151 die_errno(_("could not read '%s'"), am_path(state
, file
));
155 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
156 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
157 * match `key`. Returns NULL on failure.
159 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
162 static char *read_shell_var(FILE *fp
, const char *key
)
164 struct strbuf sb
= STRBUF_INIT
;
167 if (strbuf_getline(&sb
, fp
, '\n'))
170 if (!skip_prefix(sb
.buf
, key
, &str
))
173 if (!skip_prefix(str
, "=", &str
))
176 strbuf_remove(&sb
, 0, str
- sb
.buf
);
178 str
= sq_dequote(sb
.buf
);
182 return strbuf_detach(&sb
, NULL
);
190 * Reads and parses the state directory's "author-script" file, and sets
191 * state->author_name, state->author_email and state->author_date accordingly.
192 * Returns 0 on success, -1 if the file could not be parsed.
194 * The author script is of the format:
196 * GIT_AUTHOR_NAME='$author_name'
197 * GIT_AUTHOR_EMAIL='$author_email'
198 * GIT_AUTHOR_DATE='$author_date'
200 * where $author_name, $author_email and $author_date are quoted. We are strict
201 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
202 * script, and thus if the file differs from what this function expects, it is
203 * better to bail out than to do something that the user does not expect.
205 static int read_author_script(struct am_state
*state
)
207 const char *filename
= am_path(state
, "author-script");
210 assert(!state
->author_name
);
211 assert(!state
->author_email
);
212 assert(!state
->author_date
);
214 fp
= fopen(filename
, "r");
218 die_errno(_("could not open '%s' for reading"), filename
);
221 state
->author_name
= read_shell_var(fp
, "GIT_AUTHOR_NAME");
222 if (!state
->author_name
) {
227 state
->author_email
= read_shell_var(fp
, "GIT_AUTHOR_EMAIL");
228 if (!state
->author_email
) {
233 state
->author_date
= read_shell_var(fp
, "GIT_AUTHOR_DATE");
234 if (!state
->author_date
) {
239 if (fgetc(fp
) != EOF
) {
249 * Saves state->author_name, state->author_email and state->author_date in the
250 * state directory's "author-script" file.
252 static void write_author_script(const struct am_state
*state
)
254 struct strbuf sb
= STRBUF_INIT
;
256 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
257 sq_quote_buf(&sb
, state
->author_name
);
258 strbuf_addch(&sb
, '\n');
260 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
261 sq_quote_buf(&sb
, state
->author_email
);
262 strbuf_addch(&sb
, '\n');
264 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
265 sq_quote_buf(&sb
, state
->author_date
);
266 strbuf_addch(&sb
, '\n');
268 write_file(am_path(state
, "author-script"), 1, "%s", sb
.buf
);
274 * Reads the commit message from the state directory's "final-commit" file,
275 * setting state->msg to its contents and state->msg_len to the length of its
278 * Returns 0 on success, -1 if the file does not exist.
280 static int read_commit_msg(struct am_state
*state
)
282 struct strbuf sb
= STRBUF_INIT
;
286 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
291 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
296 * Saves state->msg in the state directory's "final-commit" file.
298 static void write_commit_msg(const struct am_state
*state
)
301 const char *filename
= am_path(state
, "final-commit");
303 fd
= xopen(filename
, O_WRONLY
| O_CREAT
, 0666);
304 if (write_in_full(fd
, state
->msg
, state
->msg_len
) < 0)
305 die_errno(_("could not write to %s"), filename
);
310 * Loads state from disk.
312 static void am_load(struct am_state
*state
)
314 struct strbuf sb
= STRBUF_INIT
;
316 if (read_state_file(&sb
, state
, "next", 1) < 0)
317 die("BUG: state file 'next' does not exist");
318 state
->cur
= strtol(sb
.buf
, NULL
, 10);
320 if (read_state_file(&sb
, state
, "last", 1) < 0)
321 die("BUG: state file 'last' does not exist");
322 state
->last
= strtol(sb
.buf
, NULL
, 10);
324 if (read_author_script(state
) < 0)
325 die(_("could not parse author script"));
327 read_commit_msg(state
);
333 * Removes the am_state directory, forcefully terminating the current am
336 static void am_destroy(const struct am_state
*state
)
338 struct strbuf sb
= STRBUF_INIT
;
340 strbuf_addstr(&sb
, state
->dir
);
341 remove_dir_recursively(&sb
, 0);
346 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
347 * non-indented lines and checking if they look like they begin with valid
348 * header field names.
350 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
352 static int is_mail(FILE *fp
)
354 const char *header_regex
= "^[!-9;-~]+:";
355 struct strbuf sb
= STRBUF_INIT
;
359 if (fseek(fp
, 0L, SEEK_SET
))
360 die_errno(_("fseek failed"));
362 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
363 die("invalid pattern: %s", header_regex
);
365 while (!strbuf_getline_crlf(&sb
, fp
)) {
367 break; /* End of header */
369 /* Ignore indented folded lines */
370 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
373 /* It's a header if it matches header_regex */
374 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
387 * Attempts to detect the patch_format of the patches contained in `paths`,
388 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
391 static int detect_patch_format(const char **paths
)
393 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
394 struct strbuf l1
= STRBUF_INIT
;
398 * We default to mbox format if input is from stdin and for directories
400 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
401 return PATCH_FORMAT_MBOX
;
404 * Otherwise, check the first few lines of the first patch, starting
405 * from the first non-blank line, to try to detect its format.
408 fp
= xfopen(*paths
, "r");
410 while (!strbuf_getline_crlf(&l1
, fp
)) {
415 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
416 ret
= PATCH_FORMAT_MBOX
;
420 if (l1
.len
&& is_mail(fp
)) {
421 ret
= PATCH_FORMAT_MBOX
;
432 * Splits out individual email patches from `paths`, where each path is either
433 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
435 static int split_mail_mbox(struct am_state
*state
, const char **paths
)
437 struct child_process cp
= CHILD_PROCESS_INIT
;
438 struct strbuf last
= STRBUF_INIT
;
441 argv_array_push(&cp
.args
, "mailsplit");
442 argv_array_pushf(&cp
.args
, "-d%d", state
->prec
);
443 argv_array_pushf(&cp
.args
, "-o%s", state
->dir
);
444 argv_array_push(&cp
.args
, "-b");
445 argv_array_push(&cp
.args
, "--");
446 argv_array_pushv(&cp
.args
, paths
);
448 if (capture_command(&cp
, &last
, 8))
452 state
->last
= strtol(last
.buf
, NULL
, 10);
458 * Splits a list of files/directories into individual email patches. Each path
459 * in `paths` must be a file/directory that is formatted according to
462 * Once split out, the individual email patches will be stored in the state
463 * directory, with each patch's filename being its index, padded to state->prec
466 * state->cur will be set to the index of the first mail, and state->last will
467 * be set to the index of the last mail.
469 * Returns 0 on success, -1 on failure.
471 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
474 switch (patch_format
) {
475 case PATCH_FORMAT_MBOX
:
476 return split_mail_mbox(state
, paths
);
478 die("BUG: invalid patch_format");
484 * Setup a new am session for applying patches
486 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
490 patch_format
= detect_patch_format(paths
);
493 fprintf_ln(stderr
, _("Patch format detection failed."));
497 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
498 die_errno(_("failed to create directory '%s'"), state
->dir
);
500 if (split_mail(state
, patch_format
, paths
) < 0) {
502 die(_("Failed to split patches."));
506 * NOTE: Since the "next" and "last" files determine if an am_state
507 * session is in progress, they should be written last.
510 write_file(am_path(state
, "next"), 1, "%d", state
->cur
);
512 write_file(am_path(state
, "last"), 1, "%d", state
->last
);
516 * Increments the patch pointer, and cleans am_state for the application of the
519 static void am_next(struct am_state
*state
)
521 free(state
->author_name
);
522 state
->author_name
= NULL
;
524 free(state
->author_email
);
525 state
->author_email
= NULL
;
527 free(state
->author_date
);
528 state
->author_date
= NULL
;
534 unlink(am_path(state
, "author-script"));
535 unlink(am_path(state
, "final-commit"));
538 write_file(am_path(state
, "next"), 1, "%d", state
->cur
);
542 * Returns the filename of the current patch email.
544 static const char *msgnum(const struct am_state
*state
)
546 static struct strbuf sb
= STRBUF_INIT
;
549 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
555 * Refresh and write index.
557 static void refresh_and_write_cache(void)
559 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
561 hold_locked_index(lock_file
, 1);
562 refresh_cache(REFRESH_QUIET
);
563 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
564 die(_("unable to write index file"));
568 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
569 * state->msg will be set to the patch message. state->author_name,
570 * state->author_email and state->author_date will be set to the patch author's
571 * name, email and date respectively. The patch body will be written to the
572 * state directory's "patch" file.
574 * Returns 1 if the patch should be skipped, 0 otherwise.
576 static int parse_mail(struct am_state
*state
, const char *mail
)
579 struct child_process cp
= CHILD_PROCESS_INIT
;
580 struct strbuf sb
= STRBUF_INIT
;
581 struct strbuf msg
= STRBUF_INIT
;
582 struct strbuf author_name
= STRBUF_INIT
;
583 struct strbuf author_date
= STRBUF_INIT
;
584 struct strbuf author_email
= STRBUF_INIT
;
588 cp
.in
= xopen(mail
, O_RDONLY
, 0);
589 cp
.out
= xopen(am_path(state
, "info"), O_WRONLY
| O_CREAT
, 0777);
591 argv_array_push(&cp
.args
, "mailinfo");
592 argv_array_push(&cp
.args
, am_path(state
, "msg"));
593 argv_array_push(&cp
.args
, am_path(state
, "patch"));
595 if (run_command(&cp
) < 0)
596 die("could not parse patch");
601 /* Extract message and author information */
602 fp
= xfopen(am_path(state
, "info"), "r");
603 while (!strbuf_getline(&sb
, fp
, '\n')) {
606 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
608 strbuf_addch(&msg
, '\n');
609 strbuf_addstr(&msg
, x
);
610 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
611 strbuf_addstr(&author_name
, x
);
612 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
613 strbuf_addstr(&author_email
, x
);
614 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
615 strbuf_addstr(&author_date
, x
);
619 /* Skip pine's internal folder data */
620 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
625 if (is_empty_file(am_path(state
, "patch"))) {
626 printf_ln(_("Patch is empty. Was it split wrong?"));
630 strbuf_addstr(&msg
, "\n\n");
631 if (strbuf_read_file(&msg
, am_path(state
, "msg"), 0) < 0)
632 die_errno(_("could not read '%s'"), am_path(state
, "msg"));
635 assert(!state
->author_name
);
636 state
->author_name
= strbuf_detach(&author_name
, NULL
);
638 assert(!state
->author_email
);
639 state
->author_email
= strbuf_detach(&author_email
, NULL
);
641 assert(!state
->author_date
);
642 state
->author_date
= strbuf_detach(&author_date
, NULL
);
645 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
648 strbuf_release(&msg
);
649 strbuf_release(&author_date
);
650 strbuf_release(&author_email
);
651 strbuf_release(&author_name
);
657 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise.
659 static int run_apply(const struct am_state
*state
)
661 struct child_process cp
= CHILD_PROCESS_INIT
;
665 argv_array_push(&cp
.args
, "apply");
666 argv_array_push(&cp
.args
, "--index");
667 argv_array_push(&cp
.args
, am_path(state
, "patch"));
669 if (run_command(&cp
))
672 /* Reload index as git-apply will have modified it. */
680 * Commits the current index with state->msg as the commit message and
681 * state->author_name, state->author_email and state->author_date as the author
684 static void do_commit(const struct am_state
*state
)
686 unsigned char tree
[GIT_SHA1_RAWSZ
], parent
[GIT_SHA1_RAWSZ
],
687 commit
[GIT_SHA1_RAWSZ
];
689 struct commit_list
*parents
= NULL
;
690 const char *reflog_msg
, *author
;
691 struct strbuf sb
= STRBUF_INIT
;
693 if (write_cache_as_tree(tree
, 0, NULL
))
694 die(_("git write-tree failed to write a tree"));
696 if (!get_sha1_commit("HEAD", parent
)) {
698 commit_list_insert(lookup_commit(parent
), &parents
);
701 fprintf_ln(stderr
, _("applying to an empty history"));
704 author
= fmt_ident(state
->author_name
, state
->author_email
,
705 state
->author_date
, IDENT_STRICT
);
707 if (commit_tree(state
->msg
, state
->msg_len
, tree
, parents
, commit
,
709 die(_("failed to write commit object"));
711 reflog_msg
= getenv("GIT_REFLOG_ACTION");
715 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
718 update_ref(sb
.buf
, "HEAD", commit
, ptr
, 0, UPDATE_REFS_DIE_ON_ERR
);
724 * Applies all queued mail.
726 static void am_run(struct am_state
*state
)
728 const char *argv_gc_auto
[] = {"gc", "--auto", NULL
};
730 refresh_and_write_cache();
732 while (state
->cur
<= state
->last
) {
733 const char *mail
= am_path(state
, msgnum(state
));
735 if (!file_exists(mail
))
738 if (parse_mail(state
, mail
))
739 goto next
; /* mail should be skipped */
741 write_author_script(state
);
742 write_commit_msg(state
);
744 printf_ln(_("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
746 if (run_apply(state
) < 0) {
747 int advice_amworkdir
= 1;
749 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
750 linelen(state
->msg
), state
->msg
);
752 git_config_get_bool("advice.amworkdir", &advice_amworkdir
);
754 if (advice_amworkdir
)
755 printf_ln(_("The copy of the patch that failed is found in: %s"),
756 am_path(state
, "patch"));
768 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
772 * parse_options() callback that validates and sets opt->value to the
773 * PATCH_FORMAT_* enum value corresponding to `arg`.
775 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
777 int *opt_value
= opt
->value
;
779 if (!strcmp(arg
, "mbox"))
780 *opt_value
= PATCH_FORMAT_MBOX
;
782 return error(_("Invalid value for --patch-format: %s"), arg
);
786 int cmd_am(int argc
, const char **argv
, const char *prefix
)
788 struct am_state state
;
789 int patch_format
= PATCH_FORMAT_UNKNOWN
;
791 const char * const usage
[] = {
792 N_("git am [options] [(<mbox>|<Maildir>)...]"),
796 struct option options
[] = {
797 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
798 N_("format the patch(es) are in"),
799 parse_opt_patchformat
),
804 * NEEDSWORK: Once all the features of git-am.sh have been
805 * re-implemented in builtin/am.c, this preamble can be removed.
807 if (!getenv("_GIT_USE_BUILTIN_AM")) {
808 const char *path
= mkpath("%s/git-am", git_exec_path());
810 if (sane_execvp(path
, (char **)argv
) < 0)
811 die_errno("could not exec %s", path
);
813 prefix
= setup_git_directory();
814 trace_repo_setup(prefix
);
818 git_config(git_default_config
, NULL
);
820 am_state_init(&state
, git_path("rebase-apply"));
822 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
824 if (read_index_preload(&the_index
, NULL
) < 0)
825 die(_("failed to read the index"));
827 if (am_in_progress(&state
))
830 struct argv_array paths
= ARGV_ARRAY_INIT
;
833 for (i
= 0; i
< argc
; i
++) {
834 if (is_absolute_path(argv
[i
]) || !prefix
)
835 argv_array_push(&paths
, argv
[i
]);
837 argv_array_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
840 am_setup(&state
, patch_format
, paths
.argv
);
842 argv_array_clear(&paths
);
847 am_state_release(&state
);