Debian Codegraph @

hgext/extdiff.py

raw
1 # extdiff.py - external diff program support for mercurial
2 #
3 # Copyright 2006 Vadim Gelfer <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 '''command to allow external programs to compare revisions
9
10 The extdiff Mercurial extension allows you to use external programs
11 to compare revisions, or revision with working directory. The external
12 diff programs are called with a configurable set of options and two
13 non-option arguments: paths to directories containing snapshots of
14 files to compare.
15
16 If there is more than one file being compared and the "child" revision
17 is the working directory, any modifications made in the external diff
18 program will be copied back to the working directory from the temporary
19 directory.
20
21 The extdiff extension also allows you to configure new diff commands, so
22 you do not need to type :hg:`extdiff -p kdiff3` always. ::
23
24 [extdiff]
25 # add new command that runs GNU diff(1) in 'context diff' mode
26 cdiff = gdiff -Nprc5
27 ## or the old way:
28 #cmd.cdiff = gdiff
29 #opts.cdiff = -Nprc5
30
31 # add new command called meld, runs meld (no need to name twice). If
32 # the meld executable is not available, the meld tool in [merge-tools]
33 # will be used, if available
34 meld =
35
36 # add new command called vimdiff, runs gvimdiff with DirDiff plugin
37 # (see http://www.vim.org/scripts/script.php?script_id=102) Non
38 # English user, be sure to put "let g:DirDiffDynamicDiffText = 1" in
39 # your .vimrc
40 vimdiff = gvim -f "+next" \\
41 "+execute 'DirDiff' fnameescape(argv(0)) fnameescape(argv(1))"
42
43 Tool arguments can include variables that are expanded at runtime::
44
45 $parent1, $plabel1 - filename, descriptive label of first parent
46 $child, $clabel - filename, descriptive label of child revision
47 $parent2, $plabel2 - filename, descriptive label of second parent
48 $root - repository root
49 $parent is an alias for $parent1.
50
51 The extdiff extension will look in your [diff-tools] and [merge-tools]
52 sections for diff tool arguments, when none are specified in [extdiff].
53
54 ::
55
56 [extdiff]
57 kdiff3 =
58
59 [diff-tools]
60 kdiff3.diffargs=--L1 '$plabel1' --L2 '$clabel' $parent $child
61
62 If a program has a graphical interface, it might be interesting to tell
63 Mercurial about it. It will prevent the program from being mistakenly
64 used in a terminal-only environment (such as an SSH terminal session),
65 and will make :hg:`extdiff --per-file` open multiple file diffs at once
66 instead of one by one (if you still want to open file diffs one by one,
67 you can use the --confirm option).
68
69 Declaring that a tool has a graphical interface can be done with the
70 ``gui`` flag next to where ``diffargs`` are specified:
71
72 ::
73
74 [diff-tools]
75 kdiff3.diffargs=--L1 '$plabel1' --L2 '$clabel' $parent $child
76 kdiff3.gui = true
77
78 You can use -I/-X and list of file or directory names like normal
79 :hg:`diff` command. The extdiff extension makes snapshots of only
80 needed files, so running the external diff program will actually be
81 pretty fast (at least faster than having to compare the entire tree).
82 '''
83
84 from __future__ import annotations
85
86 import os
87 import re
88 import shutil
89 import stat
90 import subprocess
91 import typing
92
93 from mercurial.i18n import _
94 from mercurial.node import (
95 nullrev,
96 short,
97 )
98 from mercurial import (
99 archival,
100 cmdutil,
101 encoding,
102 error,
103 filemerge,
104 formatter,
105 logcmdutil,
106 pycompat,
107 registrar,
108 scmutil,
109 util,
110 )
111 from mercurial.utils import (
112 procutil,
113 stringutil,
114 )
115
116 if typing.TYPE_CHECKING:
117 from mercurial import (
118 localrepo,
119 ui as uimod,
120 )
121
122 cmdtable = {}
123 command = registrar.command(cmdtable)
124
125 configtable = {}
126 configitem = registrar.configitem(configtable)
127
128 configitem(
129 b'extdiff',
130 br'opts\..*',
131 default=b'',
132 generic=True,
133 )
134
135 configitem(
136 b'extdiff',
137 br'gui\..*',
138 generic=True,
139 )
140
141 configitem(
142 b'diff-tools',
143 br'.*\.diffargs$',
144 default=None,
145 generic=True,
146 )
147
148 configitem(
149 b'diff-tools',
150 br'.*\.gui$',
151 generic=True,
152 )
153
154 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
155 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
156 # be specifying the version(s) of Mercurial they are tested with, or
157 # leave the attribute unspecified.
158 testedwith = b'ships-with-hg-core'
159
160
161 def snapshot(
162 ui: uimod.ui,
163 repo: localrepo.localrepository,
164 files,
165 node: bytes | None,
166 tmproot: bytes,
167 listsubrepos: bool,
168 ) -> tuple[bytes, list[tuple[bytes, bytes, os.stat_result]]]:
169 """snapshot files as of some revision
170 if not using snapshot, -I/-X does not work and recursive diff
171 in tools like kdiff3 and meld displays too many files."""
172 dirname = os.path.basename(repo.root)
173 if dirname == b"":
174 dirname = b"root"
175 if node is not None:
176 dirname = b'%s.%s' % (dirname, short(node))
177 base = os.path.join(tmproot, dirname)
178 os.mkdir(base)
179 fnsandstat = []
180
181 if node is not None:
182 ui.note(
183 _(b'making snapshot of %d files from rev %s\n')
184 % (len(files), short(node))
185 )
186 else:
187 ui.note(
188 _(b'making snapshot of %d files from working directory\n')
189 % (len(files))
190 )
191
192 if files:
193 repo.ui.setconfig(b"ui", b"archivemeta", False)
194
195 archival.archive(
196 repo,
197 base,
198 node,
199 b'files',
200 match=scmutil.matchfiles(repo, files),
201 subrepos=listsubrepos,
202 )
203
204 for fn in sorted(files):
205 wfn = util.pconvert(fn)
206 ui.note(b' %s\n' % wfn)
207
208 if node is None:
209 dest = os.path.join(base, wfn)
210
211 fnsandstat.append((dest, repo.wjoin(fn), os.lstat(dest)))
212 return dirname, fnsandstat
213
214
215 def formatcmdline(
216 cmdline,
217 repo_root,
218 do3way,
219 parent1,
220 plabel1,
221 parent2,
222 plabel2,
223 child,
224 clabel,
225 ):
226 # Function to quote file/dir names in the argument string.
227 # When not operating in 3-way mode, an empty string is
228 # returned for parent2
229 replace = {
230 b'parent': parent1,
231 b'parent1': parent1,
232 b'parent2': parent2,
233 b'plabel1': plabel1,
234 b'plabel2': plabel2,
235 b'child': child,
236 b'clabel': clabel,
237 b'root': repo_root,
238 }
239
240 def quote(match):
241 pre = match.group(2)
242 key = match.group(3)
243 if not do3way and key == b'parent2':
244 return pre
245 return pre + procutil.shellquote(replace[key])
246
247 # Match parent2 first, so 'parent1?' will match both parent1 and parent
248 regex = (
249 br'''(['"]?)([^\s'"$]*)'''
250 br'\$(parent2|parent1?|child|plabel1|plabel2|clabel|root)\1'
251 )
252 if not do3way and not re.search(regex, cmdline):
253 cmdline += b' $parent1 $child'
254 return re.sub(regex, quote, cmdline)
255
256
257 def _systembackground(cmd, environ=None, cwd=None):
258 """like 'procutil.system', but returns the Popen object directly
259 so we don't have to wait on it.
260 """
261 env = procutil.shellenviron(environ)
262 proc = subprocess.Popen(
263 procutil.tonativestr(cmd),
264 shell=True,
265 close_fds=procutil.closefds,
266 env=procutil.tonativeenv(env),
267 cwd=pycompat.rapply(procutil.tonativestr, cwd),
268 )
269 return proc
270
271
272 def _runperfilediff(
273 cmdline,
274 repo_root,
275 ui,
276 guitool,
277 do3way,
278 confirm,
279 commonfiles,
280 tmproot,
281 dir1a,
282 dir1b,
283 dir2,
284 rev1a,
285 rev1b,
286 rev2,
287 ):
288 # Note that we need to sort the list of files because it was
289 # built in an "unstable" way and it's annoying to get files in a
290 # random order, especially when "confirm" mode is enabled.
291 waitprocs = []
292 totalfiles = len(commonfiles)
293 for idx, commonfile in enumerate(sorted(commonfiles)):
294 path1a = os.path.join(dir1a, commonfile)
295 label1a = commonfile + rev1a
296 if not os.path.isfile(path1a):
297 path1a = pycompat.osdevnull
298
299 path1b = b''
300 label1b = b''
301 if do3way:
302 path1b = os.path.join(dir1b, commonfile)
303 label1b = commonfile + rev1b
304 if not os.path.isfile(path1b):
305 path1b = pycompat.osdevnull
306
307 path2 = os.path.join(dir2, commonfile)
308 label2 = commonfile + rev2
309
310 if confirm:
311 # Prompt before showing this diff
312 difffiles = _(b'diff %s (%d of %d)') % (
313 commonfile,
314 idx + 1,
315 totalfiles,
316 )
317 responses = _(
318 b'[Yns?]'
319 b'$$ &Yes, show diff'
320 b'$$ &No, skip this diff'
321 b'$$ &Skip remaining diffs'
322 b'$$ &? (display help)'
323 )
324 r = ui.promptchoice(b'%s %s' % (difffiles, responses))
325 if r == 3: # ?
326 while r == 3:
327 for c, t in ui.extractchoices(responses)[1]:
328 ui.write(b'%s - %s\n' % (c, encoding.lower(t)))
329 r = ui.promptchoice(b'%s %s' % (difffiles, responses))
330 if r == 0: # yes
331 pass
332 elif r == 1: # no
333 continue
334 elif r == 2: # skip
335 break
336
337 curcmdline = formatcmdline(
338 cmdline,
339 repo_root,
340 do3way=do3way,
341 parent1=path1a,
342 plabel1=label1a,
343 parent2=path1b,
344 plabel2=label1b,
345 child=path2,
346 clabel=label2,
347 )
348
349 if confirm or not guitool:
350 # Run the comparison program and wait for it to exit
351 # before we show the next file.
352 # This is because either we need to wait for confirmation
353 # from the user between each invocation, or because, as far
354 # as we know, the tool doesn't have a GUI, in which case
355 # we can't run multiple CLI programs at the same time.
356 ui.debug(
357 b'running %r in %s\n' % (pycompat.bytestr(curcmdline), tmproot)
358 )
359 ui.system(curcmdline, cwd=tmproot, blockedtag=b'extdiff')
360 else:
361 # Run the comparison program but don't wait, as we're
362 # going to rapid-fire each file diff and then wait on
363 # the whole group.
364 ui.debug(
365 b'running %r in %s (backgrounded)\n'
366 % (pycompat.bytestr(curcmdline), tmproot)
367 )
368 proc = _systembackground(curcmdline, cwd=tmproot)
369 waitprocs.append(proc)
370
371 if waitprocs:
372 with ui.timeblockedsection(b'extdiff'):
373 for proc in waitprocs:
374 proc.wait()
375
376
377 def diffpatch(ui, repo, node1, node2, tmproot, matcher, cmdline):
378 template = b'hg-%h.patch'
379 # write patches to temporary files
380 with formatter.nullformatter(ui, b'extdiff', {}) as fm:
381 cmdutil.export(
382 repo,
383 [repo[node1].rev(), repo[node2].rev()],
384 fm,
385 fntemplate=repo.vfs.reljoin(tmproot, template),
386 match=matcher,
387 )
388 label1 = cmdutil.makefilename(repo[node1], template)
389 label2 = cmdutil.makefilename(repo[node2], template)
390 file1 = repo.vfs.reljoin(tmproot, label1)
391 file2 = repo.vfs.reljoin(tmproot, label2)
392 cmdline = formatcmdline(
393 cmdline,
394 repo.root,
395 # no 3way while comparing patches
396 do3way=False,
397 parent1=file1,
398 plabel1=label1,
399 # while comparing patches, there is no second parent
400 parent2=None,
401 plabel2=None,
402 child=file2,
403 clabel=label2,
404 )
405 ui.debug(b'running %r in %s\n' % (pycompat.bytestr(cmdline), tmproot))
406 ui.system(cmdline, cwd=tmproot, blockedtag=b'extdiff')
407 return 1
408
409
410 def diffrevs(
411 ui,
412 repo,
413 ctx1a,
414 ctx1b,
415 ctx2,
416 matcher,
417 tmproot,
418 cmdline,
419 do3way,
420 guitool,
421 opts,
422 ):
423 subrepos = opts.get(b'subrepos')
424
425 # calculate list of files changed between both revs
426 st = ctx1a.status(ctx2, matcher, listsubrepos=subrepos)
427 mod_a, add_a, rem_a = set(st.modified), set(st.added), set(st.removed)
428 if do3way:
429 stb = ctx1b.status(ctx2, matcher, listsubrepos=subrepos)
430 mod_b, add_b, rem_b = (
431 set(stb.modified),
432 set(stb.added),
433 set(stb.removed),
434 )
435 else:
436 mod_b, add_b, rem_b = set(), set(), set()
437 modadd = mod_a | add_a | mod_b | add_b
438 common = modadd | rem_a | rem_b
439 if not common:
440 return 0
441
442 # Always make a copy of ctx1a (and ctx1b, if applicable)
443 # dir1a should contain files which are:
444 # * modified or removed from ctx1a to ctx2
445 # * modified or added from ctx1b to ctx2
446 # (except file added from ctx1a to ctx2 as they were not present in
447 # ctx1a)
448 dir1a_files = mod_a | rem_a | ((mod_b | add_b) - add_a)
449 dir1a = snapshot(ui, repo, dir1a_files, ctx1a.node(), tmproot, subrepos)[0]
450 rev1a = b'' if ctx1a.rev() is None else b'@%d' % ctx1a.rev()
451 if do3way:
452 # file calculation criteria same as dir1a
453 dir1b_files = mod_b | rem_b | ((mod_a | add_a) - add_b)
454 dir1b = snapshot(
455 ui, repo, dir1b_files, ctx1b.node(), tmproot, subrepos
456 )[0]
457 rev1b = b'@%d' % ctx1b.rev()
458 else:
459 dir1b = None
460 rev1b = b''
461
462 fnsandstat = []
463
464 # If ctx2 is not the wc or there is >1 change, copy it
465 dir2root = b''
466 rev2 = b''
467 if ctx2.node() is not None:
468 dir2 = snapshot(ui, repo, modadd, ctx2.node(), tmproot, subrepos)[0]
469 rev2 = b'@%d' % ctx2.rev()
470 elif len(common) > 1:
471 # we only actually need to get the files to copy back to
472 # the working dir in this case (because the other cases
473 # are: diffing 2 revisions or single file -- in which case
474 # the file is already directly passed to the diff tool).
475 dir2, fnsandstat = snapshot(ui, repo, modadd, None, tmproot, subrepos)
476 else:
477 # This lets the diff tool open the changed file directly
478 dir2 = b''
479 dir2root = repo.root
480
481 label1a = rev1a
482 label1b = rev1b
483 label2 = rev2
484
485 if not opts.get(b'per_file'):
486 # If only one change, diff the files instead of the directories
487 # Handle bogus modifies correctly by checking if the files exist
488 if len(common) == 1:
489 common_file = util.localpath(common.pop())
490 dir1a = os.path.join(tmproot, dir1a, common_file)
491 label1a = common_file + rev1a
492 if not os.path.isfile(dir1a):
493 dir1a = pycompat.osdevnull
494 if do3way:
495 dir1b = os.path.join(tmproot, dir1b, common_file)
496 label1b = common_file + rev1b
497 if not os.path.isfile(dir1b):
498 dir1b = pycompat.osdevnull
499 dir2 = os.path.join(dir2root, dir2, common_file)
500 label2 = common_file + rev2
501
502 # Run the external tool on the 2 temp directories or the patches
503 cmdline = formatcmdline(
504 cmdline,
505 repo.root,
506 do3way=do3way,
507 parent1=dir1a,
508 plabel1=label1a,
509 parent2=dir1b,
510 plabel2=label1b,
511 child=dir2,
512 clabel=label2,
513 )
514 ui.debug(b'running %r in %s\n' % (pycompat.bytestr(cmdline), tmproot))
515 ui.system(cmdline, cwd=tmproot, blockedtag=b'extdiff')
516 else:
517 # Run the external tool once for each pair of files
518 _runperfilediff(
519 cmdline,
520 repo.root,
521 ui,
522 guitool=guitool,
523 do3way=do3way,
524 confirm=opts.get(b'confirm'),
525 commonfiles=common,
526 tmproot=tmproot,
527 dir1a=os.path.join(tmproot, dir1a),
528 dir1b=os.path.join(tmproot, dir1b) if do3way else None,
529 dir2=os.path.join(dir2root, dir2),
530 rev1a=rev1a,
531 rev1b=rev1b,
532 rev2=rev2,
533 )
534
535 for copy_fn, working_fn, st in fnsandstat:
536 cpstat = os.lstat(copy_fn)
537 # Some tools copy the file and attributes, so mtime may not detect
538 # all changes. A size check will detect more cases, but not all.
539 # The only certain way to detect every case is to diff all files,
540 # which could be expensive.
541 # copyfile() carries over the permission, so the mode check could
542 # be in an 'elif' branch, but for the case where the file has
543 # changed without affecting mtime or size.
544 if (
545 cpstat[stat.ST_MTIME] != st[stat.ST_MTIME]
546 or cpstat.st_size != st.st_size
547 or (cpstat.st_mode & 0o100) != (st.st_mode & 0o100)
548 ):
549 ui.debug(
550 b'file changed while diffing. '
551 b'Overwriting: %s (src: %s)\n' % (working_fn, copy_fn)
552 )
553 util.copyfile(copy_fn, working_fn)
554
555 return 1
556
557
558 def dodiff(ui, repo, cmdline, pats, opts, guitool=False):
559 """Do the actual diff:
560
561 - copy to a temp structure if diffing 2 internal revisions
562 - copy to a temp structure if diffing working revision with
563 another one and more than 1 file is changed
564 - just invoke the diff for a single file in the working dir
565 """
566
567 cmdutil.check_at_most_one_arg(opts, b'rev', b'change')
568 revs = opts.get(b'rev')
569 from_rev = opts.get(b'from')
570 to_rev = opts.get(b'to')
571 change = opts.get(b'change')
572 do3way = b'$parent2' in cmdline
573
574 if change:
575 ctx2 = logcmdutil.revsingle(repo, change, None)
576 ctx1a, ctx1b = ctx2.p1(), ctx2.p2()
577 elif from_rev or to_rev:
578 repo = scmutil.unhidehashlikerevs(
579 repo, [from_rev] + [to_rev], b'nowarn'
580 )
581 ctx1a = logcmdutil.revsingle(repo, from_rev, None)
582 ctx1b = repo[nullrev]
583 ctx2 = logcmdutil.revsingle(repo, to_rev, None)
584 else:
585 ctx1a, ctx2 = logcmdutil.revpair(repo, revs)
586 if not revs:
587 ctx1b = repo[None].p2()
588 else:
589 ctx1b = repo[nullrev]
590
591 # Disable 3-way merge if there is only one parent
592 if do3way:
593 if ctx1b.rev() == nullrev:
594 do3way = False
595
596 matcher = scmutil.match(ctx2, pats, opts)
597
598 if opts.get(b'patch'):
599 if opts.get(b'subrepos'):
600 raise error.Abort(_(b'--patch cannot be used with --subrepos'))
601 if opts.get(b'per_file'):
602 raise error.Abort(_(b'--patch cannot be used with --per-file'))
603 if ctx2.node() is None:
604 raise error.Abort(_(b'--patch requires two revisions'))
605
606 tmproot = pycompat.mkdtemp(prefix=b'extdiff.')
607 try:
608 if opts.get(b'patch'):
609 return diffpatch(
610 ui, repo, ctx1a.node(), ctx2.node(), tmproot, matcher, cmdline
611 )
612
613 return diffrevs(
614 ui,
615 repo,
616 ctx1a,
617 ctx1b,
618 ctx2,
619 matcher,
620 tmproot,
621 cmdline,
622 do3way,
623 guitool,
624 opts,
625 )
626
627 finally:
628 ui.note(_(b'cleaning up temp directory\n'))
629 shutil.rmtree(tmproot)
630
631
632 extdiffopts = (
633 [
634 (
635 b'o',
636 b'option',
637 [],
638 _(b'pass option to comparison program'),
639 _(b'OPT'),
640 ),
641 (b'r', b'rev', [], _(b'revision (DEPRECATED)'), _(b'REV')),
642 (b'', b'from', b'', _(b'revision to diff from'), _(b'REV1')),
643 (b'', b'to', b'', _(b'revision to diff to'), _(b'REV2')),
644 (b'c', b'change', b'', _(b'change made by revision'), _(b'REV')),
645 (
646 b'',
647 b'per-file',
648 False,
649 _(b'compare each file instead of revision snapshots'),
650 ),
651 (
652 b'',
653 b'confirm',
654 False,
655 _(b'prompt user before each external program invocation'),
656 ),
657 (b'', b'patch', None, _(b'compare patches for two revisions')),
658 ]
659 + cmdutil.walkopts
660 + cmdutil.subrepoopts
661 )
662
663
664 @command(
665 b'extdiff',
666 [
667 (b'p', b'program', b'', _(b'comparison program to run'), _(b'CMD')),
668 ]
669 + extdiffopts,
670 _(b'hg extdiff [OPT]... [FILE]...'),
671 helpcategory=command.CATEGORY_FILE_CONTENTS,
672 inferrepo=True,
673 )
674 def extdiff(ui, repo, *pats, **opts):
675 """use external program to diff repository (or selected files)
676
677 Show differences between revisions for the specified files, using
678 an external program. The default program used is diff, with
679 default options "-Npru".
680
681 To select a different program, use the -p/--program option. The
682 program will be passed the names of two directories to compare,
683 unless the --per-file option is specified (see below). To pass
684 additional options to the program, use -o/--option. These will be
685 passed before the names of the directories or files to compare.
686
687 The --from, --to, and --change options work the same way they do for
688 :hg:`diff`.
689
690 The --per-file option runs the external program repeatedly on each
691 file to diff, instead of once on two directories. By default,
692 this happens one by one, where the next file diff is open in the
693 external program only once the previous external program (for the
694 previous file diff) has exited. If the external program has a
695 graphical interface, it can open all the file diffs at once instead
696 of one by one. See :hg:`help -e extdiff` for information about how
697 to tell Mercurial that a given program has a graphical interface.
698
699 The --confirm option will prompt the user before each invocation of
700 the external program. It is ignored if --per-file isn't specified.
701 """
702 opts = pycompat.byteskwargs(opts)
703 program = opts.get(b'program')
704 option = opts.get(b'option')
705 if not program:
706 program = b'diff'
707 option = option or [b'-Npru']
708 cmdline = b' '.join(map(procutil.shellquote, [program] + option))
709 return dodiff(ui, repo, cmdline, pats, opts)
710
711
712 class savedcmd:
713 """use external program to diff repository (or selected files)
714
715 Show differences between revisions for the specified files, using
716 the following program::
717
718 %(path)s
719
720 When two revision arguments are given, then changes are shown
721 between those revisions. If only one revision is specified then
722 that revision is compared to the working directory, and, when no
723 revisions are specified, the working directory files are compared
724 to its parent.
725 """
726
727 def __init__(self, cmd, path, cmdline, isgui):
728 # We can't pass non-ASCII through docstrings (and path is
729 # in an unknown encoding anyway), but avoid double separators on
730 # Windows
731 docpath = stringutil.escapestr(path).replace(b'\\\\', b'\\')
732 self.__doc__ %= {'path': pycompat.sysstr(stringutil.uirepr(docpath))}
733 self._name = cmd
734 self._cmdline = cmdline
735 self._isgui = isgui
736
737 def __call__(self, ui, repo, *pats, **opts):
738 if self._isgui and not procutil.gui():
739 msg = _(b"tool '%s' requires a GUI") % self._name
740 hint = (
741 _(b"to override, use: --config diff-tools.%s.gui=False")
742 % self._name
743 )
744 raise error.Abort(msg, hint=hint)
745 opts = pycompat.byteskwargs(opts)
746 options = b' '.join(map(procutil.shellquote, opts[b'option']))
747 if options:
748 options = b' ' + options
749 return dodiff(
750 ui, repo, self._cmdline + options, pats, opts, guitool=self._isgui
751 )
752
753
754 def _gettooldetails(ui, cmd, path):
755 """
756 returns following things for a
757 ```
758 [extdiff]
759 <cmd> = <path>
760 ```
761 entry:
762
763 cmd: command/tool name
764 path: path to the tool
765 cmdline: the command which should be run
766 isgui: whether the tool uses GUI or not
767
768 Reads all external tools related configs, whether it be extdiff section,
769 diff-tools or merge-tools section, or its specified in an old format or
770 the latest format.
771 """
772 path = util.expandpath(path)
773 if cmd.startswith(b'cmd.'):
774 cmd = cmd[4:]
775 if not path:
776 path = procutil.findexe(cmd)
777 if path is None:
778 path = filemerge.findexternaltool(ui, cmd) or cmd
779 diffopts = ui.config(b'extdiff', b'opts.' + cmd)
780 cmdline = procutil.shellquote(path)
781 if diffopts:
782 cmdline += b' ' + diffopts
783 isgui = ui.configbool(b'extdiff', b'gui.' + cmd)
784 else:
785 if path:
786 # case "cmd = path opts"
787 cmdline = path
788 diffopts = len(pycompat.shlexsplit(cmdline)) > 1
789 else:
790 # case "cmd ="
791 path = procutil.findexe(cmd)
792 if path is None:
793 path = filemerge.findexternaltool(ui, cmd) or cmd
794 cmdline = procutil.shellquote(path)
795 diffopts = False
796 isgui = ui.configbool(b'extdiff', b'gui.' + cmd)
797 # look for diff arguments in [diff-tools] then [merge-tools]
798 if not diffopts:
799 key = cmd + b'.diffargs'
800 for section in (b'diff-tools', b'merge-tools'):
801 args = ui.config(section, key)
802 if args:
803 cmdline += b' ' + args
804 break
805 if isgui is None:
806 key = cmd + b'.gui'
807 for section in (b'diff-tools', b'merge-tools'):
808 isgui = ui.configbool(section, key)
809 if isgui is not None:
810 break
811 if isgui is None:
812 isgui = False
813 return cmd, path, cmdline, isgui
814
815
816 def uisetup(ui):
817 for cmd, path in ui.configitems(b'extdiff'):
818 if cmd.startswith(b'opts.') or cmd.startswith(b'gui.'):
819 continue
820 cmd, path, cmdline, isgui = _gettooldetails(ui, cmd, path)
821 command(
822 cmd,
823 extdiffopts[:],
824 _(b'hg %s [OPTION]... [FILE]...') % cmd,
825 helpcategory=command.CATEGORY_FILE_CONTENTS,
826 inferrepo=True,
827 )(savedcmd(cmd, path, cmdline, isgui))
828
829
830 # tell hggettext to extract docstrings from these functions:
831 i18nfunctions = [savedcmd]