ack 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779
  1. #!/usr/bin/env perl
  2. #
  3. # This file, ack, is generated code.
  4. # Please DO NOT EDIT or send patches for it.
  5. #
  6. # Please take a look at the source from
  7. # http://github.com/petdance/ack
  8. # and submit patches against the individual files
  9. # that build ack.
  10. #
  11. use warnings;
  12. use strict;
  13. our $VERSION = '1.94';
  14. # Check http://betterthangrep.com/ for updates
  15. # These are all our globals.
  16. MAIN: {
  17. if ( $App::Ack::VERSION ne $main::VERSION ) {
  18. App::Ack::die( "Program/library version mismatch\n\t$0 is $main::VERSION\n\t$INC{'App/Ack.pm'} is $App::Ack::VERSION" );
  19. }
  20. # Do preliminary arg checking;
  21. my $env_is_usable = 1;
  22. for ( @ARGV ) {
  23. last if ( $_ eq '--' );
  24. # Priorities! Get the --thpppt checking out of the way.
  25. /^--th[pt]+t+$/ && App::Ack::_thpppt($_);
  26. # See if we want to ignore the environment. (Don't tell Al Gore.)
  27. if ( /^--(no)?env$/ ) {
  28. $env_is_usable = defined $1 ? 0 : 1;
  29. }
  30. }
  31. if ( $env_is_usable ) {
  32. unshift( @ARGV, App::Ack::read_ackrc() );
  33. }
  34. else {
  35. my @keys = ( 'ACKRC', grep { /^ACK_/ } keys %ENV );
  36. delete @ENV{@keys};
  37. }
  38. App::Ack::load_colors();
  39. if ( exists $ENV{ACK_SWITCHES} ) {
  40. App::Ack::warn( 'ACK_SWITCHES is no longer supported. Use ACK_OPTIONS.' );
  41. }
  42. if ( !@ARGV ) {
  43. App::Ack::show_help();
  44. exit 1;
  45. }
  46. main();
  47. }
  48. sub main {
  49. my $opt = App::Ack::get_command_line_options();
  50. $| = 1 if $opt->{flush}; # Unbuffer the output if flush mode
  51. if ( App::Ack::input_from_pipe() ) {
  52. # We're going into filter mode
  53. for ( qw( f g l ) ) {
  54. $opt->{$_} and App::Ack::die( "Can't use -$_ when acting as a filter." );
  55. }
  56. $opt->{show_filename} = 0;
  57. $opt->{regex} = App::Ack::build_regex( defined $opt->{regex} ? $opt->{regex} : shift @ARGV, $opt );
  58. if ( my $nargs = @ARGV ) {
  59. my $s = $nargs == 1 ? '' : 's';
  60. App::Ack::warn( "Ignoring $nargs argument$s on the command-line while acting as a filter." );
  61. }
  62. my $res = App::Ack::Resource::Basic->new( '-' );
  63. my $nmatches;
  64. if ( $opt->{count} ) {
  65. $nmatches = App::Ack::search_and_list( $res, $opt );
  66. }
  67. else {
  68. # normal searching
  69. $nmatches = App::Ack::search_resource( $res, $opt );
  70. }
  71. $res->close();
  72. App::Ack::exit_from_ack( $nmatches );
  73. }
  74. my $file_matching = $opt->{f} || $opt->{lines};
  75. if ( $file_matching ) {
  76. App::Ack::die( "Can't specify both a regex ($opt->{regex}) and use one of --line, -f or -g." ) if $opt->{regex};
  77. }
  78. else {
  79. $opt->{regex} = App::Ack::build_regex( defined $opt->{regex} ? $opt->{regex} : shift @ARGV, $opt );
  80. }
  81. # check that all regexes do compile fine
  82. App::Ack::check_regex( $_ ) for ( $opt->{regex}, $opt->{G} );
  83. my $what = App::Ack::get_starting_points( \@ARGV, $opt );
  84. my $iter = App::Ack::get_iterator( $what, $opt );
  85. App::Ack::filetype_setup();
  86. my $nmatches = 0;
  87. App::Ack::set_up_pager( $opt->{pager} ) if defined $opt->{pager};
  88. if ( $opt->{f} ) {
  89. $nmatches = App::Ack::print_files( $iter, $opt );
  90. }
  91. elsif ( $opt->{l} || $opt->{count} ) {
  92. $nmatches = App::Ack::print_files_with_matches( $iter, $opt );
  93. }
  94. else {
  95. $nmatches = App::Ack::print_matches( $iter, $opt );
  96. }
  97. close $App::Ack::fh;
  98. App::Ack::exit_from_ack( $nmatches );
  99. }
  100. =head1 NAME
  101. ack - grep-like text finder
  102. =head1 SYNOPSIS
  103. ack [options] PATTERN [FILE...]
  104. ack -f [options] [DIRECTORY...]
  105. =head1 DESCRIPTION
  106. Ack is designed as a replacement for 99% of the uses of F<grep>.
  107. Ack searches the named input FILEs (or standard input if no files are
  108. named, or the file name - is given) for lines containing a match to the
  109. given PATTERN. By default, ack prints the matching lines.
  110. Ack can also list files that would be searched, without actually searching
  111. them, to let you take advantage of ack's file-type filtering capabilities.
  112. =head1 FILE SELECTION
  113. I<ack> is intelligent about the files it searches. It knows about
  114. certain file types, based on both the extension on the file and,
  115. in some cases, the contents of the file. These selections can be
  116. made with the B<--type> option.
  117. With no file selections, I<ack> only searches files of types that
  118. it recognizes. If you have a file called F<foo.wango>, and I<ack>
  119. doesn't know what a .wango file is, I<ack> won't search it.
  120. The B<-a> option tells I<ack> to select all files, regardless of
  121. type.
  122. Some files will never be selected by I<ack>, even with B<-a>,
  123. including:
  124. =over 4
  125. =item * Backup files: Files matching F<#*#> or ending with F<~>.
  126. =item * Coredumps: Files matching F<core.\d+>
  127. =back
  128. However, I<ack> always searches the files given on the command line,
  129. no matter what type. Furthermore, by specifying the B<-u> option all
  130. files will be searched.
  131. =head1 DIRECTORY SELECTION
  132. I<ack> descends through the directory tree of the starting directories
  133. specified. However, it will ignore the shadow directories used by
  134. many version control systems, and the build directories used by the
  135. Perl MakeMaker system. You may add or remove a directory from this
  136. list with the B<--[no]ignore-dir> option. The option may be repeated
  137. to add/remove multiple directories from the ignore list.
  138. For a complete list of directories that do not get searched, run
  139. F<ack --help>.
  140. =head1 WHEN TO USE GREP
  141. I<ack> trumps I<grep> as an everyday tool 99% of the time, but don't
  142. throw I<grep> away, because there are times you'll still need it.
  143. E.g., searching through huge files looking for regexes that can be
  144. expressed with I<grep> syntax should be quicker with I<grep>.
  145. If your script or parent program uses I<grep> C<--quiet> or
  146. C<--silent> or needs exit 2 on IO error, use I<grep>.
  147. =head1 OPTIONS
  148. =over 4
  149. =item B<-a>, B<--all>
  150. Operate on all files, regardless of type (but still skip directories
  151. like F<blib>, F<CVS>, etc.)
  152. =item B<-A I<NUM>>, B<--after-context=I<NUM>>
  153. Print I<NUM> lines of trailing context after matching lines.
  154. =item B<-B I<NUM>>, B<--before-context=I<NUM>>
  155. Print I<NUM> lines of leading context before matching lines.
  156. =item B<-C [I<NUM>]>, B<--context[=I<NUM>]>
  157. Print I<NUM> lines (default 2) of context around matching lines.
  158. =item B<-c>, B<--count>
  159. Suppress normal output; instead print a count of matching lines for
  160. each input file. If B<-l> is in effect, it will only show the
  161. number of lines for each file that has lines matching. Without
  162. B<-l>, some line counts may be zeroes.
  163. If combined with B<-h> (B<--no-filename>) ack outputs only one total count.
  164. =item B<--color>, B<--nocolor>
  165. B<--color> highlights the matching text. B<--nocolor> supresses
  166. the color. This is on by default unless the output is redirected.
  167. On Windows, this option is off by default unless the
  168. L<Win32::Console::ANSI> module is installed or the C<ACK_PAGER_COLOR>
  169. environment variable is used.
  170. =item B<--color-filename=I<color>>
  171. Sets the color to be used for filenames.
  172. =item B<--color-match=I<color>>
  173. Sets the color to be used for matches.
  174. =item B<--color-lineno=I<color>>
  175. Sets the color to be used for line numbers.
  176. =item B<--column>
  177. Show the column number of the first match. This is helpful for editors
  178. that can place your cursor at a given position.
  179. =item B<--env>, B<--noenv>
  180. B<--noenv> disables all environment processing. No F<.ackrc> is read
  181. and all environment variables are ignored. By default, F<ack> considers
  182. F<.ackrc> and settings in the environment.
  183. =item B<--flush>
  184. B<--flush> flushes output immediately. This is off by default
  185. unless ack is running interactively (when output goes to a pipe
  186. or file).
  187. =item B<-f>
  188. Only print the files that would be searched, without actually doing
  189. any searching. PATTERN must not be specified, or it will be taken as
  190. a path to search.
  191. =item B<--follow>, B<--nofollow>
  192. Follow or don't follow symlinks, other than whatever starting files
  193. or directories were specified on the command line.
  194. This is off by default.
  195. =item B<-G I<REGEX>>
  196. Only paths matching I<REGEX> are included in the search. The entire
  197. path and filename are matched against I<REGEX>, and I<REGEX> is a
  198. Perl regular expression, not a shell glob.
  199. The options B<-i>, B<-w>, B<-v>, and B<-Q> do not apply to this I<REGEX>.
  200. =item B<-g I<REGEX>>
  201. Print files where the relative path + filename matches I<REGEX>. This option is
  202. a convenience shortcut for B<-f> B<-G I<REGEX>>.
  203. The options B<-i>, B<-w>, B<-v>, and B<-Q> do not apply to this I<REGEX>.
  204. =item B<--group>, B<--nogroup>
  205. B<--group> groups matches by file name with. This is the default when
  206. used interactively.
  207. B<--nogroup> prints one result per line, like grep. This is the default
  208. when output is redirected.
  209. =item B<-H>, B<--with-filename>
  210. Print the filename for each match.
  211. =item B<-h>, B<--no-filename>
  212. Suppress the prefixing of filenames on output when multiple files are
  213. searched.
  214. =item B<--help>
  215. Print a short help statement.
  216. =item B<-i>, B<--ignore-case>
  217. Ignore case in the search strings.
  218. This applies only to the PATTERN, not to the regexes given for the B<-g>
  219. and B<-G> options.
  220. =item B<--[no]ignore-dir=I<DIRNAME>>
  221. Ignore directory (as CVS, .svn, etc are ignored). May be used multiple times
  222. to ignore multiple directories. For example, mason users may wish to include
  223. B<--ignore-dir=data>. The B<--noignore-dir> option allows users to search
  224. directories which would normally be ignored (perhaps to research the contents
  225. of F<.svn/props> directories).
  226. The I<DIRNAME> must always be a simple directory name. Nested directories like
  227. F<foo/bar> are NOT supported. You would need to specify B<--ignore-dir=foo> and
  228. then no files from any foo directory are taken into account by ack unless given
  229. explicitly on the command line.
  230. =item B<--line=I<NUM>>
  231. Only print line I<NUM> of each file. Multiple lines can be given with multiple
  232. B<--line> options or as a comma separated list (B<--line=3,5,7>). B<--line=4-7>
  233. also works. The lines are always output in ascending order, no matter the
  234. order given on the command line.
  235. =item B<-l>, B<--files-with-matches>
  236. Only print the filenames of matching files, instead of the matching text.
  237. =item B<-L>, B<--files-without-matches>
  238. Only print the filenames of files that do I<NOT> match. This is equivalent
  239. to specifying B<-l> and B<-v>.
  240. =item B<--match I<REGEX>>
  241. Specify the I<REGEX> explicitly. This is helpful if you don't want to put the
  242. regex as your first argument, e.g. when executing multiple searches over the
  243. same set of files.
  244. # search for foo and bar in given files
  245. ack file1 t/file* --match foo
  246. ack file1 t/file* --match bar
  247. =item B<-m=I<NUM>>, B<--max-count=I<NUM>>
  248. Stop reading a file after I<NUM> matches.
  249. =item B<--man>
  250. Print this manual page.
  251. =item B<-n>, B<--no-recurse>
  252. No descending into subdirectories.
  253. =item B<-o>
  254. Show only the part of each line matching PATTERN (turns off text
  255. highlighting)
  256. =item B<--output=I<expr>>
  257. Output the evaluation of I<expr> for each line (turns off text
  258. highlighting)
  259. =item B<--pager=I<program>>
  260. Direct ack's output through I<program>. This can also be specified
  261. via the C<ACK_PAGER> and C<ACK_PAGER_COLOR> environment variables.
  262. Using --pager does not suppress grouping and coloring like piping
  263. output on the command-line does.
  264. =item B<--passthru>
  265. Prints all lines, whether or not they match the expression. Highlighting
  266. will still work, though, so it can be used to highlight matches while
  267. still seeing the entire file, as in:
  268. # Watch a log file, and highlight a certain IP address
  269. $ tail -f ~/access.log | ack --passthru 123.45.67.89
  270. =item B<--print0>
  271. Only works in conjunction with -f, -g, -l or -c (filename output). The filenames
  272. are output separated with a null byte instead of the usual newline. This is
  273. helpful when dealing with filenames that contain whitespace, e.g.
  274. # remove all files of type html
  275. ack -f --html --print0 | xargs -0 rm -f
  276. =item B<-Q>, B<--literal>
  277. Quote all metacharacters in PATTERN, it is treated as a literal.
  278. This applies only to the PATTERN, not to the regexes given for the B<-g>
  279. and B<-G> options.
  280. =item B<-r>, B<-R>, B<--recurse>
  281. Recurse into sub-directories. This is the default and just here for
  282. compatibility with grep. You can also use it for turning B<--no-recurse> off.
  283. =item B<--smart-case>, B<--no-smart-case>
  284. Ignore case in the search strings if PATTERN contains no uppercase
  285. characters. This is similar to C<smartcase> in vim. This option is
  286. off by default.
  287. B<-i> always overrides this option.
  288. This applies only to the PATTERN, not to the regexes given for the
  289. B<-g> and B<-G> options.
  290. =item B<--sort-files>
  291. Sorts the found files lexically. Use this if you want your file
  292. listings to be deterministic between runs of I<ack>.
  293. =item B<--show-types>
  294. Outputs the filetypes that ack associates with each file.
  295. Works with B<-f> and B<-g> options.
  296. =item B<--thpppt>
  297. Display the all-important Bill The Cat logo. Note that the exact
  298. spelling of B<--thpppppt> is not important. It's checked against
  299. a regular expression.
  300. =item B<--type=TYPE>, B<--type=noTYPE>
  301. Specify the types of files to include or exclude from a search.
  302. TYPE is a filetype, like I<perl> or I<xml>. B<--type=perl> can
  303. also be specified as B<--perl>, and B<--type=noperl> can be done
  304. as B<--noperl>.
  305. If a file is of both type "foo" and "bar", specifying --foo and
  306. --nobar will exclude the file, because an exclusion takes precedence
  307. over an inclusion.
  308. Type specifications can be repeated and are ORed together.
  309. See I<ack --help=types> for a list of valid types.
  310. =item B<--type-add I<TYPE>=I<.EXTENSION>[,I<.EXT2>[,...]]>
  311. Files with the given EXTENSION(s) are recognized as being of (the
  312. existing) type TYPE. See also L</"Defining your own types">.
  313. =item B<--type-set I<TYPE>=I<.EXTENSION>[,I<.EXT2>[,...]]>
  314. Files with the given EXTENSION(s) are recognized as being of type
  315. TYPE. This replaces an existing definition for type TYPE. See also
  316. L</"Defining your own types">.
  317. =item B<-u>, B<--unrestricted>
  318. All files and directories (including blib/, core.*, ...) are searched,
  319. nothing is skipped. When both B<-u> and B<--ignore-dir> are used, the
  320. B<--ignore-dir> option has no effect.
  321. =item B<-v>, B<--invert-match>
  322. Invert match: select non-matching lines
  323. This applies only to the PATTERN, not to the regexes given for the B<-g>
  324. and B<-G> options.
  325. =item B<--version>
  326. Display version and copyright information.
  327. =item B<-w>, B<--word-regexp>
  328. Force PATTERN to match only whole words. The PATTERN is wrapped with
  329. C<\b> metacharacters.
  330. This applies only to the PATTERN, not to the regexes given for the B<-g>
  331. and B<-G> options.
  332. =item B<-1>
  333. Stops after reporting first match of any kind. This is different
  334. from B<--max-count=1> or B<-m1>, where only one match per file is
  335. shown. Also, B<-1> works with B<-f> and B<-g>, where B<-m> does
  336. not.
  337. =back
  338. =head1 THE .ackrc FILE
  339. The F<.ackrc> file contains command-line options that are prepended
  340. to the command line before processing. Multiple options may live
  341. on multiple lines. Lines beginning with a # are ignored. A F<.ackrc>
  342. might look like this:
  343. # Always sort the files
  344. --sort-files
  345. # Always color, even if piping to a another program
  346. --color
  347. # Use "less -r" as my pager
  348. --pager=less -r
  349. Note that arguments with spaces in them do not need to be quoted,
  350. as they are not interpreted by the shell. Basically, each I<line>
  351. in the F<.ackrc> file is interpreted as one element of C<@ARGV>.
  352. F<ack> looks in your home directory for the F<.ackrc>. You can
  353. specify another location with the F<ACKRC> variable, below.
  354. If B<--noenv> is specified on the command line, the F<.ackrc> file
  355. is ignored.
  356. =head1 Defining your own types
  357. ack allows you to define your own types in addition to the predefined
  358. types. This is done with command line options that are best put into
  359. an F<.ackrc> file - then you do not have to define your types over and
  360. over again. In the following examples the options will always be shown
  361. on one command line so that they can be easily copy & pasted.
  362. I<ack --perl foo> searches for foo in all perl files. I<ack --help=types>
  363. tells you, that perl files are files ending
  364. in .pl, .pm, .pod or .t. So what if you would like to include .xs
  365. files as well when searching for --perl files? I<ack --type-add perl=.xs --perl foo>
  366. does this for you. B<--type-add> appends
  367. additional extensions to an existing type.
  368. If you want to define a new type, or completely redefine an existing
  369. type, then use B<--type-set>. I<ack --type-set
  370. eiffel=.e,.eiffel> defines the type I<eiffel> to include files with
  371. the extensions .e or .eiffel. So to search for all eiffel files
  372. containing the word Bertrand use I<ack --type-set eiffel=.e,.eiffel --eiffel Bertrand>.
  373. As usual, you can also write B<--type=eiffel>
  374. instead of B<--eiffel>. Negation also works, so B<--noeiffel> excludes
  375. all eiffel files from a search. Redefining also works: I<ack --type-set cc=.c,.h>
  376. and I<.xs> files no longer belong to the type I<cc>.
  377. When defining your own types in the F<.ackrc> file you have to use
  378. the following:
  379. --type-set=eiffel=.e,.eiffel
  380. or writing on separate lines
  381. --type-set
  382. eiffel=.e,.eiffel
  383. The following does B<NOT> work in the F<.ackrc> file:
  384. --type-set eiffel=.e,.eiffel
  385. In order to see all currently defined types, use I<--help types>, e.g.
  386. I<ack --type-set backup=.bak --type-add perl=.perl --help types>
  387. Restrictions:
  388. =over 4
  389. =item
  390. The types 'skipped', 'make', 'binary' and 'text' are considered "builtin" and
  391. cannot be altered.
  392. =item
  393. The shebang line recognition of the types 'perl', 'ruby', 'php', 'python',
  394. 'shell' and 'xml' cannot be redefined by I<--type-set>, it is always
  395. active. However, the shebang line is only examined for files where the
  396. extension is not recognised. Therefore it is possible to say
  397. I<ack --type-set perl=.perl --type-set foo=.pl,.pm,.pod,.t --perl --nofoo> and
  398. only find your shiny new I<.perl> files (and all files with unrecognized extension
  399. and perl on the shebang line).
  400. =back
  401. =head1 ENVIRONMENT VARIABLES
  402. For commonly-used ack options, environment variables can make life much easier.
  403. These variables are ignored if B<--noenv> is specified on the command line.
  404. =over 4
  405. =item ACKRC
  406. Specifies the location of the F<.ackrc> file. If this file doesn't
  407. exist, F<ack> looks in the default location.
  408. =item ACK_OPTIONS
  409. This variable specifies default options to be placed in front of
  410. any explicit options on the command line.
  411. =item ACK_COLOR_FILENAME
  412. Specifies the color of the filename when it's printed in B<--group>
  413. mode. By default, it's "bold green".
  414. The recognized attributes are clear, reset, dark, bold, underline,
  415. underscore, blink, reverse, concealed black, red, green, yellow,
  416. blue, magenta, on_black, on_red, on_green, on_yellow, on_blue,
  417. on_magenta, on_cyan, and on_white. Case is not significant.
  418. Underline and underscore are equivalent, as are clear and reset.
  419. The color alone sets the foreground color, and on_color sets the
  420. background color.
  421. This option can also be set with B<--color-filename>.
  422. =item ACK_COLOR_MATCH
  423. Specifies the color of the matching text when printed in B<--color>
  424. mode. By default, it's "black on_yellow".
  425. This option can also be set with B<--color-match>.
  426. See B<ACK_COLOR_FILENAME> for the color specifications.
  427. =item ACK_COLOR_LINENO
  428. Specifies the color of the line number when printed in B<--color>
  429. mode. By default, it's "bold yellow".
  430. This option can also be set with B<--color-lineno>.
  431. See B<ACK_COLOR_FILENAME> for the color specifications.
  432. =item ACK_PAGER
  433. Specifies a pager program, such as C<more>, C<less> or C<most>, to which
  434. ack will send its output.
  435. Using C<ACK_PAGER> does not suppress grouping and coloring like
  436. piping output on the command-line does, except that on Windows
  437. ack will assume that C<ACK_PAGER> does not support color.
  438. C<ACK_PAGER_COLOR> overrides C<ACK_PAGER> if both are specified.
  439. =item ACK_PAGER_COLOR
  440. Specifies a pager program that understands ANSI color sequences.
  441. Using C<ACK_PAGER_COLOR> does not suppress grouping and coloring
  442. like piping output on the command-line does.
  443. If you are not on Windows, you never need to use C<ACK_PAGER_COLOR>.
  444. =back
  445. =head1 ACK & OTHER TOOLS
  446. =head2 Vim integration
  447. F<ack> integrates easily with the Vim text editor. Set this in your
  448. F<.vimrc> to use F<ack> instead of F<grep>:
  449. set grepprg=ack\ -a
  450. That examples uses C<-a> to search through all files, but you may
  451. use other default flags. Now you can search with F<ack> and easily
  452. step through the results in Vim:
  453. :grep Dumper perllib
  454. =head2 Emacs integration
  455. Phil Jackson put together an F<ack.el> extension that "provides a
  456. simple compilation mode ... has the ability to guess what files you
  457. want to search for based on the major-mode."
  458. L<http://www.shellarchive.co.uk/content/emacs.html>
  459. =head2 TextMate integration
  460. Pedro Melo is a TextMate user who writes "I spend my day mostly
  461. inside TextMate, and the built-in find-in-project sucks with large
  462. projects. So I hacked a TextMate command that was using find +
  463. grep to use ack. The result is the Search in Project with ack, and
  464. you can find it here:
  465. L<http://www.simplicidade.org/notes/archives/2008/03/search_in_proje.html>"
  466. =head2 Shell and Return Code
  467. For greater compatibility with I<grep>, I<ack> in normal use returns
  468. shell return or exit code of 0 only if something is found and 1 if
  469. no match is found.
  470. (Shell exit code 1 is C<$?=256> in perl with C<system> or backticks.)
  471. The I<grep> code 2 for errors is not used.
  472. If C<-f> or C<-g> are specified, then 0 is returned if at least one
  473. file is found. If no files are found, then 1 is returned.
  474. =cut
  475. =head1 DEBUGGING ACK PROBLEMS
  476. If ack gives you output you're not expecting, start with a few simple steps.
  477. =head2 Use B<--noenv>
  478. Your environment variables and F<.ackrc> may be doing things you're
  479. not expecting, or forgotten you specified. Use B<--noenv> to ignore
  480. your environment and F<.ackrc>.
  481. =head2 Use B<-f> to see what files you're scanning
  482. The reason I created B<-f> in the first place was as a debugging
  483. tool. If ack is not finding matches you think it should find, run
  484. F<ack -f> to see what files are being checked.
  485. =head1 TIPS
  486. =head2 Use the F<.ackrc> file.
  487. The F<.ackrc> is the place to put all your options you use most of
  488. the time but don't want to remember. Put all your --type-add and
  489. --type-set definitions in it. If you like --smart-case, set it
  490. there, too. I also set --sort-files there.
  491. =head2 Use F<-f> for working with big codesets
  492. Ack does more than search files. C<ack -f --perl> will create a
  493. list of all the Perl files in a tree, ideal for sending into F<xargs>.
  494. For example:
  495. # Change all "this" to "that" in all Perl files in a tree.
  496. ack -f --perl | xargs perl -p -i -e's/this/that/g'
  497. or if you prefer:
  498. perl -p -i -e's/this/thatg/' $(ack -f --perl)
  499. =head2 Use F<-Q> when in doubt about metacharacters
  500. If you're searching for something with a regular expression
  501. metacharacter, most often a period in a filename or IP address, add
  502. the -Q to avoid false positives without all the backslashing. See
  503. the following example for more...
  504. =head2 Use ack to watch log files
  505. Here's one I used the other day to find trouble spots for a website
  506. visitor. The user had a problem loading F<troublesome.gif>, so I
  507. took the access log and scanned it with ack twice.
  508. ack -Q aa.bb.cc.dd /path/to/access.log | ack -Q -B5 troublesome.gif
  509. The first ack finds only the lines in the Apache log for the given
  510. IP. The second finds the match on my troublesome GIF, and shows
  511. the previous five lines from the log in each case.
  512. =head2 Share your knowledge
  513. Join the ack-users mailing list. Send me your tips and I may add
  514. them here.
  515. =head1 FAQ
  516. =head2 Why isn't ack finding a match in (some file)?
  517. Probably because it's of a type that ack doesn't recognize. ack's
  518. searching behavior is driven by filetype. B<If ack doesn't know
  519. what kind of file it is, ack ignores the file.>
  520. Use the C<-f> switch to see a list of files that ack will search
  521. for you.
  522. If you want ack to search files that it doesn't recognize, use the
  523. C<-a> switch.
  524. If you want ack to search every file, even ones that it always
  525. ignores like coredumps and backup files, use the C<-u> switch.
  526. =head2 Why does ack ignore unknown files by default?
  527. ack is designed by a programmer, for programmers, for searching
  528. large trees of code. Most codebases have a lot files in them which
  529. aren't source files (like compiled object files, source control
  530. metadata, etc), and grep wastes a lot of time searching through all
  531. of those as well and returning matches from those files.
  532. That's why ack's behavior of not searching things it doesn't recognize
  533. is one of its greatest strengths: the speed you get from only
  534. searching the things that you want to be looking at.
  535. =head2 Wouldn't it be great if F<ack> did search & replace?
  536. No, ack will always be read-only. Perl has a perfectly good way
  537. to do search & replace in files, using the C<-i>, C<-p> and C<-n>
  538. switches.
  539. You can certainly use ack to select your files to update. For
  540. example, to change all "foo" to "bar" in all PHP files, you can do
  541. this from the Unix shell:
  542. $ perl -i -p -e's/foo/bar/g' $(ack -f --php)
  543. =head2 Can you make ack recognize F<.xyz> files?
  544. That's an enhancement. Please see the section in the manual about
  545. enhancements.
  546. =head2 There's already a program/package called ack.
  547. Yes, I know.
  548. =head2 Why is it called ack if it's called ack-grep?
  549. The name of the program is "ack". Some packagers have called it
  550. "ack-grep" when creating packages because there's already a package
  551. out there called "ack" that has nothing to do with this ack.
  552. I suggest you make a symlink named F<ack> that points to F<ack-grep>
  553. because one of the crucial benefits of ack is having a name that's
  554. so short and simple to type.
  555. To do that, run this with F<sudo> or as root:
  556. ln -s /usr/bin/ack-grep /usr/bin/ack
  557. =head2 What does F<ack> mean?
  558. Nothing. I wanted a name that was easy to type and that you could
  559. pronounce as a single syllable.
  560. =head2 Can I do multi-line regexes?
  561. No, ack does not support regexes that match multiple lines. Doing
  562. so would require reading in the entire file at a time.
  563. If you want to see lines near your match, use the C<--A>, C<--B>
  564. and C<--C> switches for displaying context.
  565. =head1 AUTHOR
  566. Andy Lester, C<< <andy at petdance.com> >>
  567. =head1 BUGS
  568. Please report any bugs or feature requests to the issues list at
  569. Github: L<http://github.com/petdance/ack/issues>
  570. =head1 ENHANCEMENTS
  571. All enhancement requests MUST first be posted to the ack-users
  572. mailing list at L<http://groups.google.com/group/ack-users>. I
  573. will not consider a request without it first getting seen by other
  574. ack users. This includes requests for new filetypes.
  575. There is a list of enhancements I want to make to F<ack> in the ack
  576. issues list at Github: L<http://github.com/petdance/ack/issues>
  577. Patches are always welcome, but patches with tests get the most
  578. attention.
  579. =head1 SUPPORT
  580. Support for and information about F<ack> can be found at:
  581. =over 4
  582. =item * The ack homepage
  583. L<http://betterthangrep.com/>
  584. =item * The ack issues list at Github
  585. L<http://github.com/petdance/ack/issues>
  586. =item * AnnoCPAN: Annotated CPAN documentation
  587. L<http://annocpan.org/dist/ack>
  588. =item * CPAN Ratings
  589. L<http://cpanratings.perl.org/d/ack>
  590. =item * Search CPAN
  591. L<http://search.cpan.org/dist/ack>
  592. =item * Git source repository
  593. L<http://github.com/petdance/ack>
  594. =back
  595. =head1 ACKNOWLEDGEMENTS
  596. How appropriate to have I<ack>nowledgements!
  597. Thanks to everyone who has contributed to ack in any way, including
  598. Nick Hooey,
  599. Bo Borgerson,
  600. Mark Szymanski,
  601. Marq Schneider,
  602. Packy Anderson,
  603. JR Boyens,
  604. Dan Sully,
  605. Ryan Niebur,
  606. Kent Fredric,
  607. Mike Morearty,
  608. Ingmar Vanhassel,
  609. Eric Van Dewoestine,
  610. Sitaram Chamarty,
  611. Adam James,
  612. Richard Carlsson,
  613. Pedro Melo,
  614. AJ Schuster,
  615. Phil Jackson,
  616. Michael Schwern,
  617. Jan Dubois,
  618. Christopher J. Madsen,
  619. Matthew Wickline,
  620. David Dyck,
  621. Jason Porritt,
  622. Jjgod Jiang,
  623. Thomas Klausner,
  624. Uri Guttman,
  625. Peter Lewis,
  626. Kevin Riggle,
  627. Ori Avtalion,
  628. Torsten Blix,
  629. Nigel Metheringham,
  630. GE<aacute>bor SzabE<oacute>,
  631. Tod Hagan,
  632. Michael Hendricks,
  633. E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason,
  634. Piers Cawley,
  635. Stephen Steneker,
  636. Elias Lutfallah,
  637. Mark Leighton Fisher,
  638. Matt Diephouse,
  639. Christian Jaeger,
  640. Bill Sully,
  641. Bill Ricker,
  642. David Golden,
  643. Nilson Santos F. Jr,
  644. Elliot Shank,
  645. Merijn Broeren,
  646. Uwe Voelker,
  647. Rick Scott,
  648. Ask BjE<oslash>rn Hansen,
  649. Jerry Gay,
  650. Will Coleda,
  651. Mike O'Regan,
  652. Slaven ReziE<0x107>,
  653. Mark Stosberg,
  654. David Alan Pisoni,
  655. Adriano Ferreira,
  656. James Keenan,
  657. Leland Johnson,
  658. Ricardo Signes
  659. and Pete Krawczyk.
  660. =head1 COPYRIGHT & LICENSE
  661. Copyright 2005-2010 Andy Lester.
  662. This program is free software; you can redistribute it and/or modify
  663. it under the terms of the Artistic License v2.0.
  664. =cut
  665. package File::Next;
  666. use strict;
  667. use warnings;
  668. our $VERSION = '1.06';
  669. use File::Spec ();
  670. our $name; # name of the current file
  671. our $dir; # dir of the current file
  672. our %files_defaults;
  673. our %skip_dirs;
  674. BEGIN {
  675. %files_defaults = (
  676. file_filter => undef,
  677. descend_filter => undef,
  678. error_handler => sub { CORE::die @_ },
  679. sort_files => undef,
  680. follow_symlinks => 1,
  681. );
  682. %skip_dirs = map {($_,1)} (File::Spec->curdir, File::Spec->updir);
  683. }
  684. sub files {
  685. ($_[0] eq __PACKAGE__) && die 'File::Next::files must not be invoked as File::Next->files';
  686. my ($parms,@queue) = _setup( \%files_defaults, @_ );
  687. my $filter = $parms->{file_filter};
  688. return sub {
  689. while (@queue) {
  690. my ($dir,$file,$fullpath) = splice( @queue, 0, 3 );
  691. if ( -f $fullpath ) {
  692. if ( $filter ) {
  693. local $_ = $file;
  694. local $File::Next::dir = $dir;
  695. local $File::Next::name = $fullpath;
  696. next if not $filter->();
  697. }
  698. return wantarray ? ($dir,$file,$fullpath) : $fullpath;
  699. }
  700. elsif ( -d _ ) {
  701. unshift( @queue, _candidate_files( $parms, $fullpath ) );
  702. }
  703. } # while
  704. return;
  705. }; # iterator
  706. }
  707. sub sort_standard($$) { return $_[0]->[1] cmp $_[1]->[1] }
  708. sub sort_reverse($$) { return $_[1]->[1] cmp $_[0]->[1] }
  709. sub reslash {
  710. my $path = shift;
  711. my @parts = split( /\//, $path );
  712. return $path if @parts < 2;
  713. return File::Spec->catfile( @parts );
  714. }
  715. sub _setup {
  716. my $defaults = shift;
  717. my $passed_parms = ref $_[0] eq 'HASH' ? {%{+shift}} : {}; # copy parm hash
  718. my %passed_parms = %{$passed_parms};
  719. my $parms = {};
  720. for my $key ( keys %{$defaults} ) {
  721. $parms->{$key} =
  722. exists $passed_parms{$key}
  723. ? delete $passed_parms{$key}
  724. : $defaults->{$key};
  725. }
  726. # Any leftover keys are bogus
  727. for my $badkey ( keys %passed_parms ) {
  728. my $sub = (caller(1))[3];
  729. $parms->{error_handler}->( "Invalid option passed to $sub(): $badkey" );
  730. }
  731. # If it's not a code ref, assume standard sort
  732. if ( $parms->{sort_files} && ( ref($parms->{sort_files}) ne 'CODE' ) ) {
  733. $parms->{sort_files} = \&sort_standard;
  734. }
  735. my @queue;
  736. for ( @_ ) {
  737. my $start = reslash( $_ );
  738. if (-d $start) {
  739. push @queue, ($start,undef,$start);
  740. }
  741. else {
  742. push @queue, (undef,$start,$start);
  743. }
  744. }
  745. return ($parms,@queue);
  746. }
  747. sub _candidate_files {
  748. my $parms = shift;
  749. my $dir = shift;
  750. my $dh;
  751. if ( !opendir $dh, $dir ) {
  752. $parms->{error_handler}->( "$dir: $!" );
  753. return;
  754. }
  755. my @newfiles;
  756. my $descend_filter = $parms->{descend_filter};
  757. my $follow_symlinks = $parms->{follow_symlinks};
  758. my $sort_sub = $parms->{sort_files};
  759. for my $file ( grep { !exists $skip_dirs{$_} } readdir $dh ) {
  760. my $has_stat;
  761. # Only do directory checking if we have a descend_filter
  762. my $fullpath = File::Spec->catdir( $dir, $file );
  763. if ( !$follow_symlinks ) {
  764. next if -l $fullpath;
  765. $has_stat = 1;
  766. }
  767. if ( $descend_filter ) {
  768. if ( $has_stat ? (-d _) : (-d $fullpath) ) {
  769. local $File::Next::dir = $fullpath;
  770. local $_ = $file;
  771. next if not $descend_filter->();
  772. }
  773. }
  774. if ( $sort_sub ) {
  775. push( @newfiles, [ $dir, $file, $fullpath ] );
  776. }
  777. else {
  778. push( @newfiles, $dir, $file, $fullpath );
  779. }
  780. }
  781. closedir $dh;
  782. if ( $sort_sub ) {
  783. return map { @{$_} } sort $sort_sub @newfiles;
  784. }
  785. return @newfiles;
  786. }
  787. 1; # End of File::Next
  788. package App::Ack;
  789. use warnings;
  790. use strict;
  791. our $VERSION;
  792. our $COPYRIGHT;
  793. BEGIN {
  794. $VERSION = '1.94';
  795. $COPYRIGHT = 'Copyright 2005-2010 Andy Lester.';
  796. }
  797. our $fh;
  798. BEGIN {
  799. $fh = *STDOUT;
  800. }
  801. our %types;
  802. our %type_wanted;
  803. our %mappings;
  804. our %ignore_dirs;
  805. our $input_from_pipe;
  806. our $output_to_pipe;
  807. our $dir_sep_chars;
  808. our $is_cygwin;
  809. our $is_windows;
  810. use File::Spec ();
  811. use File::Glob ':glob';
  812. use Getopt::Long ();
  813. BEGIN {
  814. %ignore_dirs = (
  815. '.bzr' => 'Bazaar',
  816. '.cdv' => 'Codeville',
  817. '~.dep' => 'Interface Builder',
  818. '~.dot' => 'Interface Builder',
  819. '~.nib' => 'Interface Builder',
  820. '~.plst' => 'Interface Builder',
  821. '.git' => 'Git',
  822. '.hg' => 'Mercurial',
  823. '.pc' => 'quilt',
  824. '.svn' => 'Subversion',
  825. _MTN => 'Monotone',
  826. blib => 'Perl module building',
  827. CVS => 'CVS',
  828. RCS => 'RCS',
  829. SCCS => 'SCCS',
  830. _darcs => 'darcs',
  831. _sgbak => 'Vault/Fortress',
  832. 'autom4te.cache' => 'autoconf',
  833. 'cover_db' => 'Devel::Cover',
  834. _build => 'Module::Build',
  835. );
  836. %mappings = (
  837. actionscript => [qw( as mxml )],
  838. ada => [qw( ada adb ads )],
  839. asm => [qw( asm s )],
  840. batch => [qw( bat cmd )],
  841. binary => q{Binary files, as defined by Perl's -B op (default: off)},
  842. cc => [qw( c h xs )],
  843. cfmx => [qw( cfc cfm cfml )],
  844. clojure => [qw( clj )],
  845. cpp => [qw( cpp cc cxx m hpp hh h hxx )],
  846. csharp => [qw( cs )],
  847. css => [qw( css )],
  848. delphi => [qw( pas int dfm nfm dof dpk dproj groupproj bdsgroup bdsproj )],
  849. elisp => [qw( el )],
  850. erlang => [qw( erl hrl )],
  851. fortran => [qw( f f77 f90 f95 f03 for ftn fpp )],
  852. go => [qw( go )],
  853. haskell => [qw( hs lhs )],
  854. hh => [qw( h )],
  855. html => [qw( htm html shtml xhtml )],
  856. java => [qw( java properties )],
  857. js => [qw( js )],
  858. jsp => [qw( jsp jspx jhtm jhtml )],
  859. lisp => [qw( lisp lsp )],
  860. lua => [qw( lua )],
  861. make => q{Makefiles (including *.mk and *.mak)},
  862. mason => [qw( mas mhtml mpl mtxt )],
  863. objc => [qw( m h )],
  864. objcpp => [qw( mm h )],
  865. ocaml => [qw( ml mli )],
  866. parrot => [qw( pir pasm pmc ops pod pg tg )],
  867. perl => [qw( pl pm pod t )],
  868. php => [qw( php phpt php3 php4 php5 phtml)],
  869. plone => [qw( pt cpt metadata cpy py )],
  870. python => [qw( py )],
  871. rake => q{Rakefiles},
  872. ruby => [qw( rb rhtml rjs rxml erb rake spec )],
  873. scala => [qw( scala )],
  874. scheme => [qw( scm ss )],
  875. shell => [qw( sh bash csh tcsh ksh zsh )],
  876. skipped => q{Files, but not directories, normally skipped by ack (default: off)},
  877. smalltalk => [qw( st )],
  878. sql => [qw( sql ctl )],
  879. tcl => [qw( tcl itcl itk )],
  880. tex => [qw( tex cls sty )],
  881. text => q{Text files, as defined by Perl's -T op (default: off)},
  882. tt => [qw( tt tt2 ttml )],
  883. vb => [qw( bas cls frm ctl vb resx )],
  884. verilog => [qw( v vh sv )],
  885. vhdl => [qw( vhd vhdl )],
  886. vim => [qw( vim )],
  887. yaml => [qw( yaml yml )],
  888. xml => [qw( xml dtd xsl xslt ent )],
  889. );
  890. while ( my ($type,$exts) = each %mappings ) {
  891. if ( ref $exts ) {
  892. for my $ext ( @{$exts} ) {
  893. push( @{$types{$ext}}, $type );
  894. }
  895. }
  896. }
  897. # add manually Makefile extensions
  898. push @{$types{$_}}, 'make' for qw{ mk mak };
  899. # These have to be checked before any filehandle diddling.
  900. $output_to_pipe = not -t *STDOUT;
  901. $input_from_pipe = -p STDIN;
  902. $is_cygwin = ($^O eq 'cygwin');
  903. $is_windows = ($^O =~ /MSWin32/);
  904. $dir_sep_chars = $is_windows ? quotemeta( '\\/' ) : quotemeta( File::Spec->catfile( '', '' ) );
  905. }
  906. sub read_ackrc {
  907. my @files = ( $ENV{ACKRC} );
  908. my @dirs =
  909. $is_windows
  910. ? ( $ENV{HOME}, $ENV{USERPROFILE} )
  911. : ( '~', $ENV{HOME} );
  912. for my $dir ( grep { defined } @dirs ) {
  913. for my $file ( '.ackrc', '_ackrc' ) {
  914. push( @files, bsd_glob( "$dir/$file", GLOB_TILDE ) );
  915. }
  916. }
  917. for my $filename ( @files ) {
  918. if ( defined $filename && -e $filename ) {
  919. open( my $fh, '<', $filename ) or App::Ack::die( "$filename: $!\n" );
  920. my @lines = grep { /./ && !/^\s*#/ } <$fh>;
  921. chomp @lines;
  922. close $fh or App::Ack::die( "$filename: $!\n" );
  923. # get rid of leading and trailing whitespaces
  924. for ( @lines ) {
  925. s/^\s+//;
  926. s/\s+$//;
  927. }
  928. return @lines;
  929. }
  930. }
  931. return;
  932. }
  933. sub get_command_line_options {
  934. my %opt = (
  935. pager => $ENV{ACK_PAGER_COLOR} || $ENV{ACK_PAGER},
  936. );
  937. my $getopt_specs = {
  938. 1 => sub { $opt{1} = $opt{m} = 1 },
  939. 'A|after-context=i' => \$opt{after_context},
  940. 'B|before-context=i' => \$opt{before_context},
  941. 'C|context:i' => sub { shift; my $val = shift; $opt{before_context} = $opt{after_context} = ($val || 2) },
  942. 'a|all-types' => \$opt{all},
  943. 'break!' => \$opt{break},
  944. c => \$opt{count},
  945. 'color|colour!' => \$opt{color},
  946. 'color-match=s' => \$ENV{ACK_COLOR_MATCH},
  947. 'color-filename=s' => \$ENV{ACK_COLOR_FILENAME},
  948. 'color-lineno=s' => \$ENV{ACK_COLOR_LINENO},
  949. 'column!' => \$opt{column},
  950. count => \$opt{count},
  951. 'env!' => sub { }, # ignore this option, it is handled beforehand
  952. f => \$opt{f},
  953. flush => \$opt{flush},
  954. 'follow!' => \$opt{follow},
  955. 'g=s' => sub { shift; $opt{G} = shift; $opt{f} = 1 },
  956. 'G=s' => \$opt{G},
  957. 'group!' => sub { shift; $opt{heading} = $opt{break} = shift },
  958. 'heading!' => \$opt{heading},
  959. 'h|no-filename' => \$opt{h},
  960. 'H|with-filename' => \$opt{H},
  961. 'i|ignore-case' => \$opt{i},
  962. 'invert-file-match' => \$opt{invert_file_match},
  963. 'lines=s' => sub { shift; my $val = shift; push @{$opt{lines}}, $val },
  964. 'l|files-with-matches' => \$opt{l},
  965. 'L|files-without-matches' => sub { $opt{l} = $opt{v} = 1 },
  966. 'm|max-count=i' => \$opt{m},
  967. 'match=s' => \$opt{regex},
  968. 'n|no-recurse' => \$opt{n},
  969. o => sub { $opt{output} = '$&' },
  970. 'output=s' => \$opt{output},
  971. 'pager=s' => \$opt{pager},
  972. 'nopager' => sub { $opt{pager} = undef },
  973. 'passthru' => \$opt{passthru},
  974. 'print0' => \$opt{print0},
  975. 'Q|literal' => \$opt{Q},
  976. 'r|R|recurse' => sub { $opt{n} = 0 },
  977. 'show-types' => \$opt{show_types},
  978. 'smart-case!' => \$opt{smart_case},
  979. 'sort-files' => \$opt{sort_files},
  980. 'u|unrestricted' => \$opt{u},
  981. 'v|invert-match' => \$opt{v},
  982. 'w|word-regexp' => \$opt{w},
  983. 'ignore-dirs=s' => sub { shift; my $dir = remove_dir_sep( shift ); $ignore_dirs{$dir} = '--ignore-dirs' },
  984. 'noignore-dirs=s' => sub { shift; my $dir = remove_dir_sep( shift ); delete $ignore_dirs{$dir} },
  985. 'version' => sub { print_version_statement(); exit; },
  986. 'help|?:s' => sub { shift; show_help(@_); exit; },
  987. 'help-types'=> sub { show_help_types(); exit; },
  988. 'man' => sub {
  989. require Pod::Usage;
  990. Pod::Usage::pod2usage({
  991. -verbose => 2,
  992. -exitval => 0,
  993. });
  994. },
  995. 'type=s' => sub {
  996. # Whatever --type=xxx they specify, set it manually in the hash
  997. my $dummy = shift;
  998. my $type = shift;
  999. my $wanted = ($type =~ s/^no//) ? 0 : 1; # must not be undef later
  1000. if ( exists $type_wanted{ $type } ) {
  1001. $type_wanted{ $type } = $wanted;
  1002. }
  1003. else {
  1004. App::Ack::die( qq{Unknown --type "$type"} );
  1005. }
  1006. }, # type sub
  1007. };
  1008. # Stick any default switches at the beginning, so they can be overridden
  1009. # by the command line switches.
  1010. unshift @ARGV, split( ' ', $ENV{ACK_OPTIONS} ) if defined $ENV{ACK_OPTIONS};
  1011. # first pass through options, looking for type definitions
  1012. def_types_from_ARGV();
  1013. for my $i ( filetypes_supported() ) {
  1014. $getopt_specs->{ "$i!" } = \$type_wanted{ $i };
  1015. }
  1016. my $parser = Getopt::Long::Parser->new();
  1017. $parser->configure( 'bundling', 'no_ignore_case', );
  1018. $parser->getoptions( %{$getopt_specs} ) or
  1019. App::Ack::die( 'See ack --help, ack --help-types or ack --man for options.' );
  1020. my $to_screen = not output_to_pipe();
  1021. my %defaults = (
  1022. all => 0,
  1023. color => $to_screen,
  1024. follow => 0,
  1025. break => $to_screen,
  1026. heading => $to_screen,
  1027. before_context => 0,
  1028. after_context => 0,
  1029. );
  1030. if ( $is_windows && $defaults{color} && not $ENV{ACK_PAGER_COLOR} ) {
  1031. if ( $ENV{ACK_PAGER} || not eval { require Win32::Console::ANSI } ) {
  1032. $defaults{color} = 0;
  1033. }
  1034. }
  1035. if ( $to_screen && $ENV{ACK_PAGER_COLOR} ) {
  1036. $defaults{color} = 1;
  1037. }
  1038. while ( my ($key,$value) = each %defaults ) {
  1039. if ( not defined $opt{$key} ) {
  1040. $opt{$key} = $value;
  1041. }
  1042. }
  1043. if ( defined $opt{m} && $opt{m} <= 0 ) {
  1044. App::Ack::die( '-m must be greater than zero' );
  1045. }
  1046. for ( qw( before_context after_context ) ) {
  1047. if ( defined $opt{$_} && $opt{$_} < 0 ) {
  1048. App::Ack::die( "--$_ may not be negative" );
  1049. }
  1050. }
  1051. if ( defined( my $val = $opt{output} ) ) {
  1052. $opt{output} = eval qq[ sub { "$val" } ];
  1053. }
  1054. if ( defined( my $l = $opt{lines} ) ) {
  1055. # --line=1 --line=5 is equivalent to --line=1,5
  1056. my @lines = split( /,/, join( ',', @{$l} ) );
  1057. # --line=1-3 is equivalent to --line=1,2,3
  1058. @lines = map {
  1059. my @ret;
  1060. if ( /-/ ) {
  1061. my ($from, $to) = split /-/, $_;
  1062. if ( $from > $to ) {
  1063. App::Ack::warn( "ignoring --line=$from-$to" );
  1064. @ret = ();
  1065. }
  1066. else {
  1067. @ret = ( $from .. $to );
  1068. }
  1069. }
  1070. else {
  1071. @ret = ( $_ );
  1072. };
  1073. @ret
  1074. } @lines;
  1075. if ( @lines ) {
  1076. my %uniq;
  1077. @uniq{ @lines } = ();
  1078. $opt{lines} = [ sort { $a <=> $b } keys %uniq ]; # numerical sort and each line occurs only once!
  1079. }
  1080. else {
  1081. # happens if there are only ignored --line directives
  1082. App::Ack::die( 'All --line options are invalid.' );
  1083. }
  1084. }
  1085. return \%opt;
  1086. }
  1087. sub def_types_from_ARGV {
  1088. my @typedef;
  1089. my $parser = Getopt::Long::Parser->new();
  1090. # pass_through => leave unrecognized command line arguments alone
  1091. # no_auto_abbrev => otherwise -c is expanded and not left alone
  1092. $parser->configure( 'no_ignore_case', 'pass_through', 'no_auto_abbrev' );
  1093. $parser->getoptions(
  1094. 'type-set=s' => sub { shift; push @typedef, ['c', shift] },
  1095. 'type-add=s' => sub { shift; push @typedef, ['a', shift] },
  1096. ) or App::Ack::die( 'See ack --help or ack --man for options.' );
  1097. for my $td (@typedef) {
  1098. my ($type, $ext) = split /=/, $td->[1];
  1099. if ( $td->[0] eq 'c' ) {
  1100. # type-set
  1101. if ( exists $mappings{$type} ) {
  1102. # can't redefine types 'make', 'skipped', 'text' and 'binary'
  1103. App::Ack::die( qq{--type-set: Builtin type "$type" cannot be changed.} )
  1104. if ref $mappings{$type} ne 'ARRAY';
  1105. delete_type($type);
  1106. }
  1107. }
  1108. else {
  1109. # type-add
  1110. # can't append to types 'make', 'skipped', 'text' and 'binary'
  1111. App::Ack::die( qq{--type-add: Builtin type "$type" cannot be changed.} )
  1112. if exists $mappings{$type} && ref $mappings{$type} ne 'ARRAY';
  1113. App::Ack::warn( qq{--type-add: Type "$type" does not exist, creating with "$ext" ...} )
  1114. unless exists $mappings{$type};
  1115. }
  1116. my @exts = split /,/, $ext;
  1117. s/^\.// for @exts;
  1118. if ( !exists $mappings{$type} || ref($mappings{$type}) eq 'ARRAY' ) {
  1119. push @{$mappings{$type}}, @exts;
  1120. for my $e ( @exts ) {
  1121. push @{$types{$e}}, $type;
  1122. }
  1123. }
  1124. else {
  1125. App::Ack::die( qq{Cannot append to type "$type".} );
  1126. }
  1127. }
  1128. return;
  1129. }
  1130. sub delete_type {
  1131. my $type = shift;
  1132. App::Ack::die( qq{Internal error: Cannot delete builtin type "$type".} )
  1133. unless ref $mappings{$type} eq 'ARRAY';
  1134. delete $mappings{$type};
  1135. delete $type_wanted{$type};
  1136. for my $ext ( keys %types ) {
  1137. $types{$ext} = [ grep { $_ ne $type } @{$types{$ext}} ];
  1138. }
  1139. }
  1140. sub ignoredir_filter {
  1141. return !exists $ignore_dirs{$_} && !exists $ignore_dirs{$File::Next::dir};
  1142. }
  1143. sub remove_dir_sep {
  1144. my $path = shift;
  1145. $path =~ s/[$dir_sep_chars]$//;
  1146. return $path;
  1147. }
  1148. use constant TEXT => 'text';
  1149. sub filetypes {
  1150. my $filename = shift;
  1151. my $basename = $filename;
  1152. $basename =~ s{.*[$dir_sep_chars]}{};
  1153. return 'skipped' unless is_searchable( $basename );
  1154. my $lc_basename = lc $basename;
  1155. return ('make',TEXT) if $lc_basename eq 'makefile' || $lc_basename eq 'gnumakefile';
  1156. return ('rake','ruby',TEXT) if $lc_basename eq 'rakefile';
  1157. # If there's an extension, look it up
  1158. if ( $filename =~ m{\.([^\.$dir_sep_chars]+)$}o ) {
  1159. my $ref = $types{lc $1};
  1160. return (@{$ref},TEXT) if $ref;
  1161. }
  1162. # At this point, we can't tell from just the name. Now we have to
  1163. # open it and look inside.
  1164. return unless -e $filename;
  1165. # From Elliot Shank:
  1166. # I can't see any reason that -r would fail on these-- the ACLs look
  1167. # fine, and no program has any of them open, so the busted Windows
  1168. # file locking model isn't getting in there. If I comment the if
  1169. # statement out, everything works fine
  1170. # So, for cygwin, don't bother trying to check for readability.
  1171. if ( !$is_cygwin ) {
  1172. if ( !-r $filename ) {
  1173. App::Ack::warn( "$filename: Permission denied" );
  1174. return;
  1175. }
  1176. }
  1177. return 'binary' if -B $filename;
  1178. # If there's no extension, or we don't recognize it, check the shebang line
  1179. my $fh;
  1180. if ( !open( $fh, '<', $filename ) ) {
  1181. App::Ack::warn( "$filename: $!" );
  1182. return;
  1183. }
  1184. my $header = <$fh>;
  1185. close $fh;
  1186. if ( $header =~ /^#!/ ) {
  1187. return ($1,TEXT) if $header =~ /\b(ruby|p(?:erl|hp|ython))\b/;
  1188. return ('shell',TEXT) if $header =~ /\b(?:ba|t?c|k|z)?sh\b/;
  1189. }
  1190. else {
  1191. return ('xml',TEXT) if $header =~ /\Q<?xml /i;
  1192. }
  1193. return (TEXT);
  1194. }
  1195. sub is_searchable {
  1196. my $filename = shift;
  1197. # If these are updated, update the --help message
  1198. return if $filename =~ /[.]bak$/;
  1199. return if $filename =~ /~$/;
  1200. return if $filename =~ m{^#.*#$}o;
  1201. return if $filename =~ m{^core\.\d+$}o;
  1202. return if $filename =~ m{[._].*\.swp$}o;
  1203. return 1;
  1204. }
  1205. sub build_regex {
  1206. my $str = shift;
  1207. my $opt = shift;
  1208. defined $str or App::Ack::die( 'No regular expression found.' );
  1209. $str = quotemeta( $str ) if $opt->{Q};
  1210. if ( $opt->{w} ) {
  1211. $str = "\\b$str" if $str =~ /^\w/;
  1212. $str = "$str\\b" if $str =~ /\w$/;
  1213. }
  1214. my $regex_is_lc = $str eq lc $str;
  1215. if ( $opt->{i} || ($opt->{smart_case} && $regex_is_lc) ) {
  1216. $str = "(?i)$str";
  1217. }
  1218. return $str;
  1219. }
  1220. sub check_regex {
  1221. my $regex = shift;
  1222. return unless defined $regex;
  1223. eval { qr/$regex/ };
  1224. if ($@) {
  1225. (my $error = $@) =~ s/ at \S+ line \d+.*//;
  1226. chomp($error);
  1227. App::Ack::die( "Invalid regex '$regex':\n $error" );
  1228. }
  1229. return;
  1230. }
  1231. sub warn {
  1232. return CORE::warn( _my_program(), ': ', @_, "\n" );
  1233. }
  1234. sub die {
  1235. return CORE::die( _my_program(), ': ', @_, "\n" );
  1236. }
  1237. sub _my_program {
  1238. require File::Basename;
  1239. return File::Basename::basename( $0 );
  1240. }
  1241. sub filetypes_supported {
  1242. return keys %mappings;
  1243. }
  1244. sub _get_thpppt {
  1245. my $y = q{_ /|,\\'!.x',=(www)=, U };
  1246. $y =~ tr/,x!w/\nOo_/;
  1247. return $y;
  1248. }
  1249. sub _thpppt {
  1250. my $y = _get_thpppt();
  1251. App::Ack::print( "$y ack $_[0]!\n" );
  1252. exit 0;
  1253. }
  1254. sub _key {
  1255. my $str = lc shift;
  1256. $str =~ s/[^a-z]//g;
  1257. return $str;
  1258. }
  1259. sub show_help {
  1260. my $help_arg = shift || 0;
  1261. return show_help_types() if $help_arg =~ /^types?/;
  1262. my $ignore_dirs = _listify( sort { _key($a) cmp _key($b) } keys %ignore_dirs );
  1263. App::Ack::print( <<"END_OF_HELP" );
  1264. Usage: ack [OPTION]... PATTERN [FILE]
  1265. Search for PATTERN in each source file in the tree from cwd on down.
  1266. If [FILES] is specified, then only those files/directories are checked.
  1267. ack may also search STDIN, but only if no FILE are specified, or if
  1268. one of FILES is "-".
  1269. Default switches may be specified in ACK_OPTIONS environment variable or
  1270. an .ackrc file. If you want no dependency on the environment, turn it
  1271. off with --noenv.
  1272. Example: ack -i select
  1273. Searching:
  1274. -i, --ignore-case Ignore case distinctions in PATTERN
  1275. --[no]smart-case Ignore case distinctions in PATTERN,
  1276. only if PATTERN contains no upper case
  1277. Ignored if -i is specified
  1278. -v, --invert-match Invert match: select non-matching lines
  1279. -w, --word-regexp Force PATTERN to match only whole words
  1280. -Q, --literal Quote all metacharacters; PATTERN is literal
  1281. Search output:
  1282. --line=NUM Only print line(s) NUM of each file
  1283. -l, --files-with-matches
  1284. Only print filenames containing matches
  1285. -L, --files-without-matches
  1286. Only print filenames with no matches
  1287. -o Show only the part of a line matching PATTERN
  1288. (turns off text highlighting)
  1289. --passthru Print all lines, whether matching or not
  1290. --output=expr Output the evaluation of expr for each line
  1291. (turns off text highlighting)
  1292. --match PATTERN Specify PATTERN explicitly.
  1293. -m, --max-count=NUM Stop searching in each file after NUM matches
  1294. -1 Stop searching after one match of any kind
  1295. -H, --with-filename Print the filename for each match
  1296. -h, --no-filename Suppress the prefixing filename on output
  1297. -c, --count Show number of lines matching per file
  1298. --column Show the column number of the first match
  1299. -A NUM, --after-context=NUM
  1300. Print NUM lines of trailing context after matching
  1301. lines.
  1302. -B NUM, --before-context=NUM
  1303. Print NUM lines of leading context before matching
  1304. lines.
  1305. -C [NUM], --context[=NUM]
  1306. Print NUM lines (default 2) of output context.
  1307. --print0 Print null byte as separator between filenames,
  1308. only works with -f, -g, -l, -L or -c.
  1309. File presentation:
  1310. --pager=COMMAND Pipes all ack output through COMMAND. For example,
  1311. --pager="less -R". Ignored if output is redirected.
  1312. --nopager Do not send output through a pager. Cancels any
  1313. setting in ~/.ackrc, ACK_PAGER or ACK_PAGER_COLOR.
  1314. --[no]heading Print a filename heading above each file's results.
  1315. (default: on when used interactively)
  1316. --[no]break Print a break between results from different files.
  1317. (default: on when used interactively)
  1318. --group Same as --heading --break
  1319. --nogroup Same as --noheading --nobreak
  1320. --[no]color Highlight the matching text (default: on unless
  1321. output is redirected, or on Windows)
  1322. --[no]colour Same as --[no]color
  1323. --color-filename=COLOR
  1324. --color-match=COLOR
  1325. --color-lineno=COLOR Set the color for filenames, matches, and line numbers.
  1326. --flush Flush output immediately, even when ack is used
  1327. non-interactively (when output goes to a pipe or
  1328. file).
  1329. File finding:
  1330. -f Only print the files found, without searching.
  1331. The PATTERN must not be specified.
  1332. -g REGEX Same as -f, but only print files matching REGEX.
  1333. --sort-files Sort the found files lexically.
  1334. --invert-file-match Print/search handle files that do not match -g/-G.
  1335. --show-types Show which types each file has.
  1336. File inclusion/exclusion:
  1337. -a, --all-types All file types searched;
  1338. Ignores CVS, .svn and other ignored directories
  1339. -u, --unrestricted All files and directories searched
  1340. --[no]ignore-dir=name Add/Remove directory from the list of ignored dirs
  1341. -r, -R, --recurse Recurse into subdirectories (ack's default behavior)
  1342. -n, --no-recurse No descending into subdirectories
  1343. -G REGEX Only search files that match REGEX
  1344. --perl Include only Perl files.
  1345. --type=perl Include only Perl files.
  1346. --noperl Exclude Perl files.
  1347. --type=noperl Exclude Perl files.
  1348. See "ack --help type" for supported filetypes.
  1349. --type-set TYPE=.EXTENSION[,.EXT2[,...]]
  1350. Files with the given EXTENSION(s) are recognized as
  1351. being of type TYPE. This replaces an existing
  1352. definition for type TYPE.
  1353. --type-add TYPE=.EXTENSION[,.EXT2[,...]]
  1354. Files with the given EXTENSION(s) are recognized as
  1355. being of (the existing) type TYPE
  1356. --[no]follow Follow symlinks. Default is off.
  1357. Directories ignored by default:
  1358. $ignore_dirs
  1359. Files not checked for type:
  1360. /~\$/ - Unix backup files
  1361. /#.+#\$/ - Emacs swap files
  1362. /[._].*\\.swp\$/ - Vi(m) swap files
  1363. /core\\.\\d+\$/ - core dumps
  1364. Miscellaneous:
  1365. --noenv Ignore environment variables and ~/.ackrc
  1366. --help This help
  1367. --man Man page
  1368. --version Display version & copyright
  1369. --thpppt Bill the Cat
  1370. Exit status is 0 if match, 1 if no match.
  1371. This is version $VERSION of ack.
  1372. END_OF_HELP
  1373. return;
  1374. }
  1375. sub show_help_types {
  1376. App::Ack::print( <<'END_OF_HELP' );
  1377. Usage: ack [OPTION]... PATTERN [FILES]
  1378. The following is the list of filetypes supported by ack. You can
  1379. specify a file type with the --type=TYPE format, or the --TYPE
  1380. format. For example, both --type=perl and --perl work.
  1381. Note that some extensions may appear in multiple types. For example,
  1382. .pod files are both Perl and Parrot.
  1383. END_OF_HELP
  1384. my @types = filetypes_supported();
  1385. my $maxlen = 0;
  1386. for ( @types ) {
  1387. $maxlen = length if $maxlen < length;
  1388. }
  1389. for my $type ( sort @types ) {
  1390. next if $type =~ /^-/; # Stuff to not show
  1391. my $ext_list = $mappings{$type};
  1392. if ( ref $ext_list ) {
  1393. $ext_list = join( ' ', map { ".$_" } @{$ext_list} );
  1394. }
  1395. App::Ack::print( sprintf( " --[no]%-*.*s %s\n", $maxlen, $maxlen, $type, $ext_list ) );
  1396. }
  1397. return;
  1398. }
  1399. sub _listify {
  1400. my @whats = @_;
  1401. return '' if !@whats;
  1402. my $end = pop @whats;
  1403. my $str = @whats ? join( ', ', @whats ) . " and $end" : $end;
  1404. no warnings 'once';
  1405. require Text::Wrap;
  1406. $Text::Wrap::columns = 75;
  1407. return Text::Wrap::wrap( '', ' ', $str );
  1408. }
  1409. sub get_version_statement {
  1410. require Config;
  1411. my $copyright = get_copyright();
  1412. my $this_perl = $Config::Config{perlpath};
  1413. if ($^O ne 'VMS') {
  1414. my $ext = $Config::Config{_exe};
  1415. $this_perl .= $ext unless $this_perl =~ m/$ext$/i;
  1416. }
  1417. my $ver = sprintf( '%vd', $^V );
  1418. return <<"END_OF_VERSION";
  1419. ack $VERSION
  1420. Running under Perl $ver at $this_perl
  1421. $copyright
  1422. This program is free software. You may modify or distribute it
  1423. under the terms of the Artistic License v2.0.
  1424. END_OF_VERSION
  1425. }
  1426. sub print_version_statement {
  1427. App::Ack::print( get_version_statement() );
  1428. return;
  1429. }
  1430. sub get_copyright {
  1431. return $COPYRIGHT;
  1432. }
  1433. sub load_colors {
  1434. eval 'use Term::ANSIColor ()';
  1435. $ENV{ACK_COLOR_MATCH} ||= 'black on_yellow';
  1436. $ENV{ACK_COLOR_FILENAME} ||= 'bold green';
  1437. $ENV{ACK_COLOR_LINENO} ||= 'bold yellow';
  1438. return;
  1439. }
  1440. sub is_interesting {
  1441. return if /^\./;
  1442. my $include;
  1443. for my $type ( filetypes( $File::Next::name ) ) {
  1444. if ( defined $type_wanted{$type} ) {
  1445. if ( $type_wanted{$type} ) {
  1446. $include = 1;
  1447. }
  1448. else {
  1449. return;
  1450. }
  1451. }
  1452. }
  1453. return $include;
  1454. }
  1455. # print subs added in order to make it easy for a third party
  1456. # module (such as App::Wack) to redefine the display methods
  1457. # and show the results in a different way.
  1458. sub print { print {$fh} @_ }
  1459. sub print_first_filename { App::Ack::print( $_[0], "\n" ) }
  1460. sub print_blank_line { App::Ack::print( "\n" ) }
  1461. sub print_separator { App::Ack::print( "--\n" ) }
  1462. sub print_filename { App::Ack::print( $_[0], $_[1] ) }
  1463. sub print_line_no { App::Ack::print( $_[0], $_[1] ) }
  1464. sub print_column_no { App::Ack::print( $_[0], $_[1] ) }
  1465. sub print_count {
  1466. my $filename = shift;
  1467. my $nmatches = shift;
  1468. my $ors = shift;
  1469. my $count = shift;
  1470. my $show_filename = shift;
  1471. if ($show_filename) {
  1472. App::Ack::print( $filename );
  1473. App::Ack::print( ':', $nmatches ) if $count;
  1474. }
  1475. else {
  1476. App::Ack::print( $nmatches ) if $count;
  1477. }
  1478. App::Ack::print( $ors );
  1479. }
  1480. sub print_count0 {
  1481. my $filename = shift;
  1482. my $ors = shift;
  1483. my $show_filename = shift;
  1484. if ($show_filename) {
  1485. App::Ack::print( $filename, ':0', $ors );
  1486. }
  1487. else {
  1488. App::Ack::print( '0', $ors );
  1489. }
  1490. }
  1491. {
  1492. my $filename;
  1493. my $regex;
  1494. my $display_filename;
  1495. my $keep_context;
  1496. my $last_output_line; # number of the last line that has been output
  1497. my $any_output; # has there been any output for the current file yet
  1498. my $context_overall_output_count; # has there been any output at all
  1499. sub search_resource {
  1500. my $res = shift;
  1501. my $opt = shift;
  1502. $filename = $res->name();
  1503. my $v = $opt->{v};
  1504. my $passthru = $opt->{passthru};
  1505. my $max = $opt->{m};
  1506. my $nmatches = 0;
  1507. $display_filename = undef;
  1508. # for --line processing
  1509. my $has_lines = 0;
  1510. my @lines;
  1511. if ( defined $opt->{lines} ) {
  1512. $has_lines = 1;
  1513. @lines = ( @{$opt->{lines}}, -1 );
  1514. undef $regex; # Don't match when printing matching line
  1515. }
  1516. else {
  1517. $regex = qr/$opt->{regex}/;
  1518. }
  1519. # for context processing
  1520. $last_output_line = -1;
  1521. $any_output = 0;
  1522. my $before_context = $opt->{before_context};
  1523. my $after_context = $opt->{after_context};
  1524. $keep_context = ($before_context || $after_context) && !$passthru;
  1525. my @before;
  1526. my $before_starts_at_line;
  1527. my $after = 0; # number of lines still to print after a match
  1528. while ( $res->next_text ) {
  1529. # XXX Optimize away the case when there are no more @lines to find.
  1530. # XXX $has_lines, $passthru and $v never change. Optimize.
  1531. if ( $has_lines
  1532. ? $. != $lines[0] # $lines[0] should be a scalar
  1533. : $v ? m/$regex/ : !m/$regex/ ) {
  1534. if ( $passthru ) {
  1535. App::Ack::print( $_ );
  1536. next;
  1537. }
  1538. if ( $keep_context ) {
  1539. if ( $after ) {
  1540. print_match_or_context( $opt, 0, $., $-[0], $+[0], $_ );
  1541. $after--;
  1542. }
  1543. elsif ( $before_context ) {
  1544. if ( @before ) {
  1545. if ( @before >= $before_context ) {
  1546. shift @before;
  1547. ++$before_starts_at_line;
  1548. }
  1549. }
  1550. else {
  1551. $before_starts_at_line = $.;
  1552. }
  1553. push @before, $_;
  1554. }
  1555. last if $max && ( $nmatches >= $max ) && !$after;
  1556. }
  1557. next;
  1558. } # not a match
  1559. ++$nmatches;
  1560. # print an empty line as a divider before first line in each file (not before the first file)
  1561. if ( !$any_output && $opt->{show_filename} && $opt->{break} && defined( $context_overall_output_count ) ) {
  1562. App::Ack::print_blank_line();
  1563. }
  1564. shift @lines if $has_lines;
  1565. if ( $res->is_binary ) {
  1566. App::Ack::print( "Binary file $filename matches\n" );
  1567. last;
  1568. }
  1569. if ( $keep_context ) {
  1570. if ( @before ) {
  1571. print_match_or_context( $opt, 0, $before_starts_at_line, $-[0], $+[0], @before );
  1572. @before = ();
  1573. $before_starts_at_line = 0;
  1574. }
  1575. if ( $max && $nmatches > $max ) {
  1576. --$after;
  1577. }
  1578. else {
  1579. $after = $after_context;
  1580. }
  1581. }
  1582. print_match_or_context( $opt, 1, $., $-[0], $+[0], $_ );
  1583. last if $max && ( $nmatches >= $max ) && !$after;
  1584. } # while
  1585. return $nmatches;
  1586. } # search_resource()
  1587. sub print_match_or_context {
  1588. my $opt = shift; # opts array
  1589. my $is_match = shift; # is there a match on the line?
  1590. my $line_no = shift;
  1591. my $match_start = shift;
  1592. my $match_end = shift;
  1593. my $color = $opt->{color};
  1594. my $heading = $opt->{heading};
  1595. my $show_filename = $opt->{show_filename};
  1596. my $show_column = $opt->{column};
  1597. if ( $show_filename ) {
  1598. if ( not defined $display_filename ) {
  1599. $display_filename =
  1600. $color
  1601. ? Term::ANSIColor::colored( $filename, $ENV{ACK_COLOR_FILENAME} )
  1602. : $filename;
  1603. if ( $heading && !$any_output ) {
  1604. App::Ack::print_first_filename($display_filename);
  1605. }
  1606. }
  1607. }
  1608. my $sep = $is_match ? ':' : '-';
  1609. my $output_func = $opt->{output};
  1610. for ( @_ ) {
  1611. if ( $keep_context && !$output_func ) {
  1612. if ( ( $last_output_line != $line_no - 1 ) &&
  1613. ( $any_output || ( !$heading && defined( $context_overall_output_count ) ) ) ) {
  1614. App::Ack::print_separator();
  1615. }
  1616. # to ensure separators between different files when --noheading
  1617. $last_output_line = $line_no;
  1618. }
  1619. if ( $show_filename ) {
  1620. App::Ack::print_filename($display_filename, $sep) if not $heading;
  1621. my $display_line_no =
  1622. $color
  1623. ? Term::ANSIColor::colored( $line_no, $ENV{ACK_COLOR_LINENO} )
  1624. : $line_no;
  1625. App::Ack::print_line_no($display_line_no, $sep);
  1626. }
  1627. if ( $output_func ) {
  1628. while ( /$regex/go ) {
  1629. App::Ack::print( $output_func->() . "\n" );
  1630. }
  1631. }
  1632. else {
  1633. if ( $color && $is_match && $regex &&
  1634. s/$regex/Term::ANSIColor::colored( substr($_, $-[0], $+[0] - $-[0]), $ENV{ACK_COLOR_MATCH} )/eg ) {
  1635. # At the end of the line reset the color and remove newline
  1636. s/[\r\n]*\z/\e[0m\e[K/;
  1637. }
  1638. else {
  1639. # remove any kind of newline at the end of the line
  1640. s/[\r\n]*\z//;
  1641. }
  1642. if ( $show_column ) {
  1643. App::Ack::print_column_no( $match_start+1, $sep );
  1644. }
  1645. App::Ack::print($_ . "\n");
  1646. }
  1647. $any_output = 1;
  1648. ++$context_overall_output_count;
  1649. ++$line_no;
  1650. }
  1651. return;
  1652. } # print_match_or_context()
  1653. } # scope around search_resource() and print_match_or_context()
  1654. TOTAL_COUNT_SCOPE: {
  1655. my $total_count;
  1656. sub get_total_count {
  1657. return $total_count;
  1658. }
  1659. sub reset_total_count {
  1660. $total_count = 0;
  1661. }
  1662. sub search_and_list {
  1663. my $res = shift;
  1664. my $opt = shift;
  1665. my $nmatches = 0;
  1666. my $count = $opt->{count};
  1667. my $ors = $opt->{print0} ? "\0" : "\n"; # output record separator
  1668. my $show_filename = $opt->{show_filename};
  1669. my $regex = qr/$opt->{regex}/;
  1670. if ( $opt->{v} ) {
  1671. while ( $res->next_text ) {
  1672. if ( /$regex/ ) {
  1673. return 0 unless $count;
  1674. }
  1675. else {
  1676. ++$nmatches;
  1677. }
  1678. }
  1679. }
  1680. else {
  1681. while ( $res->next_text ) {
  1682. if ( /$regex/ ) {
  1683. ++$nmatches;
  1684. last unless $count;
  1685. }
  1686. }
  1687. }
  1688. if ( $opt->{show_total} ) {
  1689. $total_count += $nmatches;
  1690. }
  1691. else {
  1692. if ( $nmatches ) {
  1693. App::Ack::print_count( $res->name, $nmatches, $ors, $count, $show_filename );
  1694. }
  1695. elsif ( $count && !$opt->{l} ) {
  1696. App::Ack::print_count0( $res->name, $ors, $show_filename );
  1697. }
  1698. }
  1699. return $nmatches ? 1 : 0;
  1700. } # search_and_list()
  1701. } # scope around $total_count
  1702. sub filetypes_supported_set {
  1703. return grep { defined $type_wanted{$_} && ($type_wanted{$_} == 1) } filetypes_supported();
  1704. }
  1705. sub print_files {
  1706. my $iter = shift;
  1707. my $opt = shift;
  1708. my $ors = $opt->{print0} ? "\0" : "\n";
  1709. my $nmatches = 0;
  1710. while ( defined ( my $file = $iter->() ) ) {
  1711. App::Ack::print $file, $opt->{show_types} ? " => " . join( ',', filetypes( $file ) ) : (), $ors;
  1712. $nmatches++;
  1713. last if $opt->{1};
  1714. }
  1715. return $nmatches;
  1716. }
  1717. sub print_files_with_matches {
  1718. my $iter = shift;
  1719. my $opt = shift;
  1720. # if we have -l and only 1 file given on command line (this means
  1721. # show_filename is set to 0), we want to see the filename nevertheless
  1722. $opt->{show_filename} = 1 if $opt->{l};
  1723. $opt->{show_filename} = 0 if $opt->{h};
  1724. $opt->{show_filename} = 1 if $opt->{H};
  1725. # abuse options to hand in the show_total parameter to search_and_list
  1726. $opt->{show_total} = $opt->{count} && !$opt->{show_filename};
  1727. reset_total_count();
  1728. my $nmatches = 0;
  1729. while ( defined ( my $filename = $iter->() ) ) {
  1730. my $repo = App::Ack::Repository::Basic->new( $filename );
  1731. my $res;
  1732. while ( $res = $repo->next_resource() ) {
  1733. $nmatches += search_and_list( $res, $opt );
  1734. $res->close();
  1735. last if $nmatches && $opt->{1};
  1736. }
  1737. $repo->close();
  1738. }
  1739. if ( $nmatches && $opt->{show_total} ) {
  1740. App::Ack::print_count('', get_total_count(), "\n", 1, 0 )
  1741. }
  1742. return $nmatches;
  1743. }
  1744. sub print_matches {
  1745. my $iter = shift;
  1746. my $opt = shift;
  1747. $opt->{show_filename} = 0 if $opt->{h};
  1748. $opt->{show_filename} = 1 if $opt->{H};
  1749. my $nmatches = 0;
  1750. while ( defined ( my $filename = $iter->() ) ) {
  1751. my $repo;
  1752. my $tarballs_work = 0;
  1753. if ( $tarballs_work && $filename =~ /\.tar\.gz$/ ) {
  1754. App::Ack::die( 'Not working here yet' );
  1755. require App::Ack::Repository::Tar; # XXX Error checking
  1756. $repo = App::Ack::Repository::Tar->new( $filename );
  1757. }
  1758. else {
  1759. $repo = App::Ack::Repository::Basic->new( $filename );
  1760. }
  1761. $repo or next;
  1762. while ( my $res = $repo->next_resource() ) {
  1763. my $needs_line_scan;
  1764. if ( $opt->{regex} && !$opt->{passthru} ) {
  1765. $needs_line_scan = $res->needs_line_scan( $opt );
  1766. if ( $needs_line_scan ) {
  1767. $res->reset();
  1768. }
  1769. }
  1770. else {
  1771. $needs_line_scan = 1;
  1772. }
  1773. if ( $needs_line_scan ) {
  1774. $nmatches += search_resource( $res, $opt );
  1775. }
  1776. $res->close();
  1777. }
  1778. last if $nmatches && $opt->{1};
  1779. $repo->close();
  1780. }
  1781. return $nmatches;
  1782. }
  1783. sub filetype_setup {
  1784. my $filetypes_supported_set = filetypes_supported_set();
  1785. # If anyone says --no-whatever, we assume all other types must be on.
  1786. if ( !$filetypes_supported_set ) {
  1787. for my $i ( keys %type_wanted ) {
  1788. $type_wanted{$i} = 1 unless ( defined( $type_wanted{$i} ) || $i eq 'binary' || $i eq 'text' || $i eq 'skipped' );
  1789. }
  1790. }
  1791. return;
  1792. }
  1793. EXPAND_FILENAMES_SCOPE: {
  1794. my $filter;
  1795. sub expand_filenames {
  1796. my $argv = shift;
  1797. my $attr;
  1798. my @files;
  1799. foreach my $pattern ( @{$argv} ) {
  1800. my @results = bsd_glob( $pattern );
  1801. if (@results == 0) {
  1802. @results = $pattern; # Glob didn't match, pass it thru unchanged
  1803. }
  1804. elsif ( (@results > 1) or ($results[0] ne $pattern) ) {
  1805. if (not defined $filter) {
  1806. eval 'require Win32::File;';
  1807. if ($@) {
  1808. $filter = 0;
  1809. }
  1810. else {
  1811. $filter = Win32::File::HIDDEN()|Win32::File::SYSTEM();
  1812. }
  1813. } # end unless we've tried to load Win32::File
  1814. if ( $filter ) {
  1815. # Filter out hidden and system files:
  1816. @results = grep { not(Win32::File::GetAttributes($_, $attr) and $attr & $filter) } @results;
  1817. App::Ack::warn( "$pattern: Matched only hidden files" ) unless @results;
  1818. } # end if we can filter by file attributes
  1819. } # end elsif this pattern got expanded
  1820. push @files, @results;
  1821. } # end foreach pattern
  1822. return \@files;
  1823. } # end expand_filenames
  1824. } # EXPAND_FILENAMES_SCOPE
  1825. sub get_starting_points {
  1826. my $argv = shift;
  1827. my $opt = shift;
  1828. my @what;
  1829. if ( @{$argv} ) {
  1830. @what = @{ $is_windows ? expand_filenames($argv) : $argv };
  1831. $_ = File::Next::reslash( $_ ) for @what;
  1832. # Show filenames unless we've specified one single file
  1833. $opt->{show_filename} = (@what > 1) || (!-f $what[0]);
  1834. }
  1835. else {
  1836. @what = '.'; # Assume current directory
  1837. $opt->{show_filename} = 1;
  1838. }
  1839. for my $start_point (@what) {
  1840. App::Ack::warn( "$start_point: No such file or directory" ) unless -e $start_point;
  1841. }
  1842. return \@what;
  1843. }
  1844. sub _match {
  1845. my ( $target, $expression, $invert_flag ) = @_;
  1846. if ( $invert_flag ) {
  1847. return $target !~ $expression;
  1848. }
  1849. else {
  1850. return $target =~ $expression;
  1851. }
  1852. }
  1853. sub get_iterator {
  1854. my $what = shift;
  1855. my $opt = shift;
  1856. # Starting points are always searched, no matter what
  1857. my %starting_point = map { ($_ => 1) } @{$what};
  1858. my $g_regex = defined $opt->{G} ? qr/$opt->{G}/ : undef;
  1859. my $file_filter;
  1860. if ( $g_regex ) {
  1861. $file_filter
  1862. = $opt->{u} ? sub { _match( $File::Next::name, qr/$g_regex/, $opt->{invert_file_match} ) } # XXX Maybe this should be a 1, no?
  1863. : $opt->{all} ? sub { $starting_point{ $File::Next::name } || ( _match( $File::Next::name, qr/$g_regex/, $opt->{invert_file_match} ) && is_searchable( $_ ) ) }
  1864. : sub { $starting_point{ $File::Next::name } || ( _match( $File::Next::name, qr/$g_regex/, $opt->{invert_file_match} ) && is_interesting( @ _) ) }
  1865. ;
  1866. }
  1867. else {
  1868. $file_filter
  1869. = $opt->{u} ? sub {1}
  1870. : $opt->{all} ? sub { $starting_point{ $File::Next::name } || is_searchable( $_ ) }
  1871. : sub { $starting_point{ $File::Next::name } || is_interesting( @_ ) }
  1872. ;
  1873. }
  1874. my $descend_filter
  1875. = $opt->{n} ? sub {0}
  1876. : $opt->{u} ? sub {1}
  1877. : \&ignoredir_filter;
  1878. my $iter =
  1879. File::Next::files( {
  1880. file_filter => $file_filter,
  1881. descend_filter => $descend_filter,
  1882. error_handler => sub { my $msg = shift; App::Ack::warn( $msg ) },
  1883. sort_files => $opt->{sort_files},
  1884. follow_symlinks => $opt->{follow},
  1885. }, @{$what} );
  1886. return $iter;
  1887. }
  1888. sub set_up_pager {
  1889. my $command = shift;
  1890. return if App::Ack::output_to_pipe();
  1891. my $pager;
  1892. if ( not open( $pager, '|-', $command ) ) {
  1893. App::Ack::die( qq{Unable to pipe to pager "$command": $!} );
  1894. }
  1895. $fh = $pager;
  1896. return;
  1897. }
  1898. sub input_from_pipe {
  1899. return $input_from_pipe;
  1900. }
  1901. sub output_to_pipe {
  1902. return $output_to_pipe;
  1903. }
  1904. sub exit_from_ack {
  1905. my $nmatches = shift;
  1906. my $rc = $nmatches ? 0 : 1;
  1907. exit $rc;
  1908. }
  1909. 1; # End of App::Ack
  1910. package App::Ack::Repository;
  1911. use warnings;
  1912. use strict;
  1913. sub FAIL {
  1914. require Carp;
  1915. Carp::confess( 'Must be overloaded' );
  1916. }
  1917. sub new {
  1918. FAIL();
  1919. }
  1920. sub next_resource {
  1921. FAIL();
  1922. }
  1923. sub close {
  1924. FAIL();
  1925. }
  1926. 1;
  1927. package App::Ack::Resource;
  1928. use warnings;
  1929. use strict;
  1930. sub FAIL {
  1931. require Carp;
  1932. Carp::confess( 'Must be overloaded' );
  1933. }
  1934. sub new {
  1935. FAIL();
  1936. }
  1937. sub name {
  1938. FAIL();
  1939. }
  1940. sub is_binary {
  1941. FAIL();
  1942. }
  1943. sub needs_line_scan {
  1944. FAIL();
  1945. }
  1946. sub reset {
  1947. FAIL();
  1948. }
  1949. sub next_text {
  1950. FAIL();
  1951. }
  1952. sub close {
  1953. FAIL();
  1954. }
  1955. 1;
  1956. package App::Ack::Plugin::Basic;
  1957. package App::Ack::Resource::Basic;
  1958. use warnings;
  1959. use strict;
  1960. our @ISA = qw( App::Ack::Resource );
  1961. sub new {
  1962. my $class = shift;
  1963. my $filename = shift;
  1964. my $self = bless {
  1965. filename => $filename,
  1966. fh => undef,
  1967. could_be_binary => undef,
  1968. opened => undef,
  1969. id => undef,
  1970. }, $class;
  1971. if ( $self->{filename} eq '-' ) {
  1972. $self->{fh} = *STDIN;
  1973. $self->{could_be_binary} = 0;
  1974. }
  1975. else {
  1976. if ( !open( $self->{fh}, '<', $self->{filename} ) ) {
  1977. App::Ack::warn( "$self->{filename}: $!" );
  1978. return;
  1979. }
  1980. $self->{could_be_binary} = 1;
  1981. }
  1982. return $self;
  1983. }
  1984. sub name {
  1985. my $self = shift;
  1986. return $self->{filename};
  1987. }
  1988. sub is_binary {
  1989. my $self = shift;
  1990. if ( $self->{could_be_binary} ) {
  1991. return -B $self->{filename};
  1992. }
  1993. return 0;
  1994. }
  1995. sub needs_line_scan {
  1996. my $self = shift;
  1997. my $opt = shift;
  1998. return 1 if $opt->{v};
  1999. my $size = -s $self->{fh};
  2000. if ( $size == 0 ) {
  2001. return 0;
  2002. }
  2003. elsif ( $size > 100_000 ) {
  2004. return 1;
  2005. }
  2006. my $buffer;
  2007. my $rc = sysread( $self->{fh}, $buffer, $size );
  2008. if ( not defined $rc ) {
  2009. App::Ack::warn( "$self->{filename}: $!" );
  2010. return 1;
  2011. }
  2012. return 0 unless $rc && ( $rc == $size );
  2013. my $regex = $opt->{regex};
  2014. return $buffer =~ /$regex/m;
  2015. }
  2016. sub reset {
  2017. my $self = shift;
  2018. seek( $self->{fh}, 0, 0 )
  2019. or App::Ack::warn( "$self->{filename}: $!" );
  2020. return;
  2021. }
  2022. sub next_text {
  2023. if ( defined ($_ = readline $_[0]->{fh}) ) {
  2024. $. = ++$_[0]->{line};
  2025. return 1;
  2026. }
  2027. return;
  2028. }
  2029. sub close {
  2030. my $self = shift;
  2031. if ( not close $self->{fh} ) {
  2032. App::Ack::warn( $self->name() . ": $!" );
  2033. }
  2034. return;
  2035. }
  2036. package App::Ack::Repository::Basic;
  2037. our @ISA = qw( App::Ack::Repository );
  2038. use warnings;
  2039. use strict;
  2040. sub new {
  2041. my $class = shift;
  2042. my $filename = shift;
  2043. my $self = bless {
  2044. filename => $filename,
  2045. nexted => 0,
  2046. }, $class;
  2047. return $self;
  2048. }
  2049. sub next_resource {
  2050. my $self = shift;
  2051. return if $self->{nexted};
  2052. $self->{nexted} = 1;
  2053. return App::Ack::Resource::Basic->new( $self->{filename} );
  2054. }
  2055. sub close {
  2056. }
  2057. 1;