ack 135 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161
  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. # https://github.com/petdance/ack2
  8. # and submit patches against the individual files
  9. # that build ack.
  10. #
  11. package main;
  12. use strict;
  13. use warnings;
  14. our $VERSION = '2.14'; # Check http://beyondgrep.com/ for updates
  15. use 5.008008;
  16. use Getopt::Long 2.35 ();
  17. use Carp 1.04 ();
  18. use File::Spec ();
  19. # XXX Don't make this so brute force
  20. # See also: https://github.com/petdance/ack2/issues/89
  21. # These are all our globals.
  22. MAIN: {
  23. $App::Ack::orig_program_name = $0;
  24. $0 = join(' ', 'ack', $0);
  25. if ( $App::Ack::VERSION ne $main::VERSION ) {
  26. App::Ack::die( "Program/library version mismatch\n\t$0 is $main::VERSION\n\t$INC{'App/Ack.pm'} is $App::Ack::VERSION" );
  27. }
  28. # Do preliminary arg checking;
  29. my $env_is_usable = 1;
  30. for my $arg ( @ARGV ) {
  31. last if ( $arg eq '--' );
  32. # Get the --thpppt, --bar, --cathy checking out of the way.
  33. $arg =~ /^--th[pt]+t+$/ and App::Ack::_thpppt($arg);
  34. $arg eq '--bar' and App::Ack::_bar();
  35. $arg eq '--cathy' and App::Ack::_cathy();
  36. # See if we want to ignore the environment. (Don't tell Al Gore.)
  37. $arg eq '--env' and $env_is_usable = 1;
  38. $arg eq '--noenv' and $env_is_usable = 0;
  39. }
  40. if ( !$env_is_usable ) {
  41. my @keys = ( 'ACKRC', grep { /^ACK_/ } keys %ENV );
  42. delete @ENV{@keys};
  43. }
  44. load_colors();
  45. Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
  46. Getopt::Long::Configure('pass_through', 'no_auto_abbrev');
  47. Getopt::Long::GetOptions(
  48. 'help' => sub { App::Ack::show_help(); exit; },
  49. 'version' => sub { App::Ack::print_version_statement(); exit; },
  50. 'man' => sub { App::Ack::show_man(); exit; },
  51. );
  52. Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
  53. if ( !@ARGV ) {
  54. App::Ack::show_help();
  55. exit 1;
  56. }
  57. main();
  58. }
  59. sub _compile_descend_filter {
  60. my ( $opt ) = @_;
  61. my $idirs = $opt->{idirs};
  62. my $dont_ignore_dirs = $opt->{no_ignore_dirs};
  63. # if we have one or more --noignore-dir directives, we can't ignore
  64. # entire subdirectory hierarchies, so we return an "accept all"
  65. # filter and scrutinize the files more in _compile_file_filter
  66. return if $dont_ignore_dirs;
  67. return unless $idirs && @{$idirs};
  68. my %ignore_dirs;
  69. foreach my $idir (@{$idirs}) {
  70. if ( $idir =~ /^(\w+):(.*)/ ) {
  71. if ( $1 eq 'is') {
  72. $ignore_dirs{$2} = 1;
  73. }
  74. else {
  75. Carp::croak( 'Non-is filters are not yet supported for --ignore-dir' );
  76. }
  77. }
  78. else {
  79. Carp::croak( qq{Invalid filter specification "$idir"} );
  80. }
  81. }
  82. return sub {
  83. return !exists $ignore_dirs{$_} && !exists $ignore_dirs{$File::Next::dir};
  84. };
  85. }
  86. sub _compile_file_filter {
  87. my ( $opt, $start ) = @_;
  88. my $ifiles = $opt->{ifiles};
  89. $ifiles ||= [];
  90. my $ifiles_filters = App::Ack::Filter::Collection->new();
  91. foreach my $filter_spec (@{$ifiles}) {
  92. if ( $filter_spec =~ /^(\w+):(.+)/ ) {
  93. my ($how,$what) = ($1,$2);
  94. my $filter = App::Ack::Filter->create_filter($how, split(/,/, $what));
  95. $ifiles_filters->add($filter);
  96. }
  97. else {
  98. Carp::croak( qq{Invalid filter specification "$filter_spec"} );
  99. }
  100. }
  101. my $filters = $opt->{'filters'} || [];
  102. my $direct_filters = App::Ack::Filter::Collection->new();
  103. my $inverse_filters = App::Ack::Filter::Collection->new();
  104. foreach my $filter (@{$filters}) {
  105. if ($filter->is_inverted()) {
  106. # We want to check if files match the uninverted filters
  107. $inverse_filters->add($filter->invert());
  108. }
  109. else {
  110. $direct_filters->add($filter);
  111. }
  112. }
  113. my %is_member_of_starting_set = map { (get_file_id($_) => 1) } @{$start};
  114. my $ignore_dir_list = $opt->{idirs};
  115. my $dont_ignore_dir_list = $opt->{no_ignore_dirs};
  116. my %ignore_dir_set;
  117. my %dont_ignore_dir_set;
  118. foreach my $filter (@{ $ignore_dir_list }) {
  119. if ( $filter =~ /^(\w+):(.*)/ ) {
  120. if ( $1 eq 'is' ) {
  121. $ignore_dir_set{ $2 } = 1;
  122. } else {
  123. Carp::croak( 'Non-is filters are not yet supported for --ignore-dir' );
  124. }
  125. } else {
  126. Carp::croak( qq{Invalid filter specification "$filter"} );
  127. }
  128. }
  129. foreach my $filter (@{ $dont_ignore_dir_list }) {
  130. if ( $filter =~ /^(\w+):(.*)/ ) {
  131. if ( $1 eq 'is' ) {
  132. $dont_ignore_dir_set{ $2 } = 1;
  133. } else {
  134. Carp::croak( 'Non-is filters are not yet supported for --ignore-dir' );
  135. }
  136. } else {
  137. Carp::croak( qq{Invalid filter specification "$filter"} );
  138. }
  139. }
  140. my $match_filenames = $opt->{g};
  141. my $match_regex = $opt->{regex};
  142. my $is_inverted = $opt->{v};
  143. return sub {
  144. if ( $match_filenames ) {
  145. if ( $File::Next::name =~ /$match_regex/ && $is_inverted ) {
  146. return;
  147. }
  148. if ( $File::Next::name !~ /$match_regex/ && !$is_inverted ) {
  149. return;
  150. }
  151. }
  152. # ack always selects files that are specified on the command
  153. # line, regardless of filetype. If you want to ack a JPEG,
  154. # and say "ack foo whatever.jpg" it will do it for you.
  155. return 1 if $is_member_of_starting_set{ get_file_id($File::Next::name) };
  156. if ( $dont_ignore_dir_list ) {
  157. my ( undef, $dirname ) = File::Spec->splitpath($File::Next::name);
  158. my @dirs = File::Spec->splitdir($dirname);
  159. my $is_ignoring = 0;
  160. foreach my $dir ( @dirs ) {
  161. if ( $ignore_dir_set{ $dir } ) {
  162. $is_ignoring = 1;
  163. }
  164. elsif ( $dont_ignore_dir_set{ $dir } ) {
  165. $is_ignoring = 0;
  166. }
  167. }
  168. if ( $is_ignoring ) {
  169. return 0;
  170. }
  171. }
  172. # Ignore named pipes found in directory searching. Named
  173. # pipes created by subprocesses get specified on the command
  174. # line, so the rule of "always select whatever is on the
  175. # command line" wins.
  176. return 0 if -p $File::Next::name;
  177. # We can't handle unreadable filenames; report them.
  178. if ( not -r _ ) {
  179. use filetest 'access';
  180. if ( not -R $File::Next::name ) {
  181. if ( $App::Ack::report_bad_filenames ) {
  182. App::Ack::warn( "${File::Next::name}: cannot open file for reading" );
  183. }
  184. return 0;
  185. }
  186. }
  187. my $resource = App::Ack::Resource::Basic->new($File::Next::name);
  188. return 0 if !$resource || $ifiles_filters->filter($resource);
  189. my $match_found = $direct_filters->filter($resource);
  190. # Don't bother invoking inverse filters unless we consider the current resource a match
  191. if ( $match_found && $inverse_filters->filter( $resource ) ) {
  192. $match_found = 0;
  193. }
  194. return $match_found;
  195. };
  196. }
  197. sub show_types {
  198. my $resource = shift;
  199. my $ors = shift;
  200. my @types = filetypes( $resource );
  201. my $types = join( ',', @types );
  202. my $arrow = @types ? ' => ' : ' =>';
  203. App::Ack::print( $resource->name, $arrow, join( ',', @types ), $ors );
  204. return;
  205. }
  206. # Set default colors, load Term::ANSIColor
  207. sub load_colors {
  208. eval 'use Term::ANSIColor 1.10 ()';
  209. eval 'use Win32::Console::ANSI' if $App::Ack::is_windows;
  210. $ENV{ACK_COLOR_MATCH} ||= 'black on_yellow';
  211. $ENV{ACK_COLOR_FILENAME} ||= 'bold green';
  212. $ENV{ACK_COLOR_LINENO} ||= 'bold yellow';
  213. return;
  214. }
  215. sub filetypes {
  216. my ( $resource ) = @_;
  217. my @matches;
  218. foreach my $k (keys %App::Ack::mappings) {
  219. my $filters = $App::Ack::mappings{$k};
  220. foreach my $filter (@{$filters}) {
  221. # clone the resource
  222. my $clone = $resource->clone;
  223. if ( $filter->filter($clone) ) {
  224. push @matches, $k;
  225. last;
  226. }
  227. }
  228. }
  229. # http://search.cpan.org/dist/Perl-Critic/lib/Perl/Critic/Policy/Subroutines/ProhibitReturnSort.pm
  230. @matches = sort @matches;
  231. return @matches;
  232. }
  233. # Returns a (fairly) unique identifier for a file.
  234. # Use this function to compare two files to see if they're
  235. # equal (ie. the same file, but with a different path/links/etc).
  236. sub get_file_id {
  237. my ( $filename ) = @_;
  238. if ( $App::Ack::is_windows ) {
  239. return File::Next::reslash( $filename );
  240. }
  241. else {
  242. # XXX is this the best method? it always hits the FS
  243. if( my ( $dev, $inode ) = (stat($filename))[0, 1] ) {
  244. return join(':', $dev, $inode);
  245. }
  246. else {
  247. # XXX this could be better
  248. return $filename;
  249. }
  250. }
  251. }
  252. # Returns a regex object based on a string and command-line options.
  253. # Dies when the regex $str is undefined (i.e. not given on command line).
  254. sub build_regex {
  255. my $str = shift;
  256. my $opt = shift;
  257. defined $str or App::Ack::die( 'No regular expression found.' );
  258. $str = quotemeta( $str ) if $opt->{Q};
  259. if ( $opt->{w} ) {
  260. my $pristine_str = $str;
  261. $str = "(?:$str)";
  262. $str = "\\b$str" if $pristine_str =~ /^\w/;
  263. $str = "$str\\b" if $pristine_str =~ /\w$/;
  264. }
  265. my $regex_is_lc = $str eq lc $str;
  266. if ( $opt->{i} || ($opt->{smart_case} && $regex_is_lc) ) {
  267. $str = "(?i)$str";
  268. }
  269. my $re = eval { qr/$str/ };
  270. if ( !$re ) {
  271. die "Invalid regex '$str':\n $@";
  272. }
  273. return $re;
  274. }
  275. {
  276. my @before_ctx_lines;
  277. my @after_ctx_lines;
  278. my $is_iterating;
  279. my $has_printed_something;
  280. BEGIN {
  281. $has_printed_something = 0;
  282. }
  283. sub print_matches_in_resource {
  284. my ( $resource, $opt ) = @_;
  285. my $passthru = $opt->{passthru};
  286. my $max_count = $opt->{m} || -1;
  287. my $nmatches = 0;
  288. my $filename = $resource->name;
  289. my $break = $opt->{break};
  290. my $heading = $opt->{heading};
  291. my $ors = $opt->{print0} ? "\0" : "\n";
  292. my $color = $opt->{color};
  293. my $print_filename = $opt->{show_filename};
  294. my $has_printed_for_this_resource = 0;
  295. $is_iterating = 1;
  296. local $opt->{before_context} = $opt->{output} ? 0 : $opt->{before_context};
  297. local $opt->{after_context} = $opt->{output} ? 0 : $opt->{after_context};
  298. my $n_before_ctx_lines = $opt->{before_context} || 0;
  299. my $n_after_ctx_lines = $opt->{after_context} || 0;
  300. @after_ctx_lines = @before_ctx_lines = ();
  301. my $fh = $resource->open();
  302. if ( !$fh ) {
  303. if ( $App::Ack::report_bad_filenames ) {
  304. App::Ack::warn( "$filename: $!" );
  305. }
  306. return 0;
  307. }
  308. my $display_filename = $filename;
  309. if ( $print_filename && $heading && $color ) {
  310. $display_filename = Term::ANSIColor::colored($display_filename, $ENV{ACK_COLOR_FILENAME});
  311. }
  312. # check for context before the main loop, so we don't
  313. # pay for it if we don't need it
  314. if ( $n_before_ctx_lines || $n_after_ctx_lines ) {
  315. my $current_line = <$fh>; # prime the first line of input
  316. while ( defined $current_line ) {
  317. while ( (@after_ctx_lines < $n_after_ctx_lines) && defined($_ = <$fh>) ) {
  318. push @after_ctx_lines, $_;
  319. }
  320. local $_ = $current_line;
  321. my $former_dot_period = $.;
  322. $. -= @after_ctx_lines;
  323. if ( does_match($opt, $_) ) {
  324. if ( !$has_printed_for_this_resource ) {
  325. if ( $break && $has_printed_something ) {
  326. App::Ack::print_blank_line();
  327. }
  328. if ( $print_filename && $heading ) {
  329. App::Ack::print_filename( $display_filename, $ors );
  330. }
  331. }
  332. print_line_with_context($opt, $filename, $_, $.);
  333. $has_printed_for_this_resource = 1;
  334. $nmatches++;
  335. $max_count--;
  336. }
  337. elsif ( $passthru ) {
  338. chomp; # XXX proper newline handling?
  339. # XXX inline this call?
  340. if ( $break && !$has_printed_for_this_resource && $has_printed_something ) {
  341. App::Ack::print_blank_line();
  342. }
  343. print_line_with_options($opt, $filename, $_, $., ':');
  344. $has_printed_for_this_resource = 1;
  345. }
  346. last unless $max_count != 0;
  347. # I tried doing this with local(), but for some reason,
  348. # $. continued to have its new value after the exit of the
  349. # enclosing block. I'm guessing that $. has some extra
  350. # magic associated with it or something. If someone can
  351. # tell me why this happened, I would love to know!
  352. $. = $former_dot_period; # XXX this won't happen on an exception
  353. if ( $n_before_ctx_lines ) {
  354. push @before_ctx_lines, $current_line;
  355. shift @before_ctx_lines while @before_ctx_lines > $n_before_ctx_lines;
  356. }
  357. if ( $n_after_ctx_lines ) {
  358. $current_line = shift @after_ctx_lines;
  359. }
  360. else {
  361. $current_line = <$fh>;
  362. }
  363. }
  364. }
  365. else {
  366. local $_;
  367. while ( <$fh> ) {
  368. if ( does_match($opt, $_) ) {
  369. if ( !$has_printed_for_this_resource ) {
  370. if ( $break && $has_printed_something ) {
  371. App::Ack::print_blank_line();
  372. }
  373. if ( $print_filename && $heading ) {
  374. App::Ack::print_filename( $display_filename, $ors );
  375. }
  376. }
  377. print_line_with_context($opt, $filename, $_, $.);
  378. $has_printed_for_this_resource = 1;
  379. $nmatches++;
  380. $max_count--;
  381. }
  382. elsif ( $passthru ) {
  383. chomp; # XXX proper newline handling?
  384. if ( $break && !$has_printed_for_this_resource && $has_printed_something ) {
  385. App::Ack::print_blank_line();
  386. }
  387. print_line_with_options($opt, $filename, $_, $., ':');
  388. $has_printed_for_this_resource = 1;
  389. }
  390. last unless $max_count != 0;
  391. }
  392. }
  393. $is_iterating = 0; # XXX this won't happen on an exception
  394. # then again, do we care? ack doesn't really
  395. # handle exceptions anyway.
  396. return $nmatches;
  397. }
  398. sub print_line_with_options {
  399. my ( $opt, $filename, $line, $line_no, $separator ) = @_;
  400. $has_printed_something = 1;
  401. my $print_filename = $opt->{show_filename};
  402. my $print_column = $opt->{column};
  403. my $ors = $opt->{print0} ? "\0" : "\n";
  404. my $heading = $opt->{heading};
  405. my $output_expr = $opt->{output};
  406. my $color = $opt->{color};
  407. my @line_parts;
  408. if( $color ) {
  409. $filename = Term::ANSIColor::colored($filename,
  410. $ENV{ACK_COLOR_FILENAME});
  411. $line_no = Term::ANSIColor::colored($line_no,
  412. $ENV{ACK_COLOR_LINENO});
  413. }
  414. if($print_filename) {
  415. if( $heading ) {
  416. push @line_parts, $line_no;
  417. }
  418. else {
  419. push @line_parts, $filename, $line_no;
  420. }
  421. if( $print_column ) {
  422. push @line_parts, get_match_column();
  423. }
  424. }
  425. if( $output_expr ) {
  426. while ( $line =~ /$opt->{regex}/og ) {
  427. # XXX We need to stop using eval() for --output. See https://github.com/petdance/ack2/issues/421
  428. my $output = eval $output_expr;
  429. App::Ack::print( join( $separator, @line_parts, $output ), $ors );
  430. }
  431. }
  432. else {
  433. if ( $color ) {
  434. $line =~ /$opt->{regex}/o; # this match is redundant, but we need
  435. # to perfom it in order to get if
  436. # capture groups are set
  437. if ( @+ > 1 ) { # if we have captures
  438. while ( $line =~ /$opt->{regex}/og ) {
  439. my $offset = 0; # additional offset for when we add stuff
  440. my $previous_match_end = 0;
  441. for ( my $i = 1; $i < @+; $i++ ) {
  442. my ( $match_start, $match_end ) = ( $-[$i], $+[$i] );
  443. next unless defined($match_start);
  444. next if $match_start < $previous_match_end;
  445. my $substring = substr( $line,
  446. $offset + $match_start, $match_end - $match_start );
  447. my $substitution = Term::ANSIColor::colored( $substring,
  448. $ENV{ACK_COLOR_MATCH} );
  449. substr( $line, $offset + $match_start,
  450. $match_end - $match_start, $substitution );
  451. $previous_match_end = $match_end; # offsets do not need to be applied
  452. $offset += length( $substitution ) - length( $substring );
  453. }
  454. pos($line) = $+[0] + $offset;
  455. }
  456. }
  457. else {
  458. my $matched = 0; # flag; if matched, need to escape afterwards
  459. while ( $line =~ /$opt->{regex}/og ) {
  460. $matched = 1;
  461. my ( $match_start, $match_end ) = ($-[0], $+[0]);
  462. next unless defined($match_start);
  463. my $substring = substr( $line, $match_start,
  464. $match_end - $match_start );
  465. my $substitution = Term::ANSIColor::colored( $substring,
  466. $ENV{ACK_COLOR_MATCH} );
  467. substr( $line, $match_start, $match_end - $match_start,
  468. $substitution );
  469. pos($line) = $match_end +
  470. (length( $substitution ) - length( $substring ));
  471. }
  472. # XXX why do we do this?
  473. $line .= "\033[0m\033[K" if $matched;
  474. }
  475. }
  476. push @line_parts, $line;
  477. App::Ack::print( join( $separator, @line_parts ), $ors );
  478. }
  479. return;
  480. }
  481. sub iterate {
  482. my ( $resource, $opt, $cb ) = @_;
  483. $is_iterating = 1;
  484. local $opt->{before_context} = $opt->{output} ? 0 : $opt->{before_context};
  485. local $opt->{after_context} = $opt->{output} ? 0 : $opt->{after_context};
  486. my $n_before_ctx_lines = $opt->{before_context} || 0;
  487. my $n_after_ctx_lines = $opt->{after_context} || 0;
  488. @after_ctx_lines = @before_ctx_lines = ();
  489. my $fh = $resource->open();
  490. if ( !$fh ) {
  491. if ( $App::Ack::report_bad_filenames ) {
  492. App::Ack::warn( $resource->name . ': ' . $! );
  493. }
  494. return;
  495. }
  496. # Check for context before the main loop, so we don't pay for it if we don't need it.
  497. if ( $n_before_ctx_lines || $n_after_ctx_lines ) {
  498. my $current_line = <$fh>; # prime the first line of input
  499. while ( defined $current_line ) {
  500. while ( (@after_ctx_lines < $n_after_ctx_lines) && defined($_ = <$fh>) ) {
  501. push @after_ctx_lines, $_;
  502. }
  503. local $_ = $current_line;
  504. my $former_dot_period = $.;
  505. $. -= @after_ctx_lines;
  506. last unless $cb->();
  507. # I tried doing this with local(), but for some reason,
  508. # $. continued to have its new value after the exit of the
  509. # enclosing block. I'm guessing that $. has some extra
  510. # magic associated with it or something. If someone can
  511. # tell me why this happened, I would love to know!
  512. $. = $former_dot_period; # XXX this won't happen on an exception
  513. if ( $n_before_ctx_lines ) {
  514. push @before_ctx_lines, $current_line;
  515. shift @before_ctx_lines while @before_ctx_lines > $n_before_ctx_lines;
  516. }
  517. if ( $n_after_ctx_lines ) {
  518. $current_line = shift @after_ctx_lines;
  519. }
  520. else {
  521. $current_line = <$fh>;
  522. }
  523. }
  524. }
  525. else {
  526. local $_;
  527. while ( <$fh> ) {
  528. last unless $cb->();
  529. }
  530. }
  531. $is_iterating = 0; # XXX this won't happen on an exception
  532. # then again, do we care? ack doesn't really
  533. # handle exceptions anyway.
  534. return;
  535. }
  536. sub get_context {
  537. if ( not $is_iterating ) {
  538. Carp::croak( 'get_context() called outside of iterate()' );
  539. }
  540. return (
  541. scalar(@before_ctx_lines) ? \@before_ctx_lines : undef,
  542. scalar(@after_ctx_lines) ? \@after_ctx_lines : undef,
  543. );
  544. }
  545. }
  546. {
  547. my $is_first_match;
  548. my $previous_file_processed;
  549. my $previous_line_printed;
  550. BEGIN {
  551. $is_first_match = 1;
  552. $previous_line_printed = -1;
  553. }
  554. sub print_line_with_context {
  555. my ( $opt, $filename, $matching_line, $line_no ) = @_;
  556. my $heading = $opt->{heading};
  557. if( !defined($previous_file_processed) ||
  558. $previous_file_processed ne $filename ) {
  559. $previous_file_processed = $filename;
  560. $previous_line_printed = -1;
  561. if( $heading ) {
  562. $is_first_match = 1;
  563. }
  564. }
  565. my $ors = $opt->{print0} ? "\0" : "\n";
  566. my $match_word = $opt->{w};
  567. my $is_tracking_context = $opt->{after_context} || $opt->{before_context};
  568. my $output_expr = $opt->{output};
  569. $matching_line =~ s/[\r\n]+$//g;
  570. my ( $before_context, $after_context ) = get_context();
  571. if ( $before_context ) {
  572. my $first_line = $. - @{$before_context};
  573. if ( $first_line <= $previous_line_printed ) {
  574. splice @{$before_context}, 0, $previous_line_printed - $first_line + 1;
  575. $first_line = $. - @{$before_context};
  576. }
  577. if ( @{$before_context} ) {
  578. my $offset = @{$before_context};
  579. if( !$is_first_match && $previous_line_printed != $first_line - 1 ) {
  580. App::Ack::print('--', $ors);
  581. }
  582. foreach my $line (@{$before_context}) {
  583. my $context_line_no = $. - $offset;
  584. if ( $context_line_no <= $previous_line_printed ) {
  585. next;
  586. }
  587. chomp $line;
  588. local $opt->{column};
  589. print_line_with_options($opt, $filename, $line, $context_line_no, '-');
  590. $previous_line_printed = $context_line_no;
  591. $offset--;
  592. }
  593. }
  594. }
  595. if ( $. > $previous_line_printed ) {
  596. if( $is_tracking_context && !$is_first_match && $previous_line_printed != $. - 1 ) {
  597. App::Ack::print('--', $ors);
  598. }
  599. print_line_with_options($opt, $filename, $matching_line, $line_no, ':');
  600. $previous_line_printed = $.;
  601. }
  602. if($after_context) {
  603. my $offset = 1;
  604. foreach my $line (@{$after_context}) {
  605. # XXX improve this!
  606. if ( $previous_line_printed >= $. + $offset ) {
  607. $offset++;
  608. next;
  609. }
  610. chomp $line;
  611. if ( $opt->{regex} && does_match( $opt, $line ) ) {
  612. print_line_with_options($opt, $filename, $line, $. + $offset, ':');
  613. }
  614. else {
  615. local $opt->{column};
  616. print_line_with_options($opt, $filename, $line, $. + $offset, '-');
  617. }
  618. $previous_line_printed = $. + $offset;
  619. $offset++;
  620. }
  621. }
  622. $is_first_match = 0;
  623. return;
  624. }
  625. }
  626. {
  627. my $match_column_number;
  628. # does_match() MUST have an $opt->{regex} set.
  629. sub does_match {
  630. my ( $opt, $line ) = @_;
  631. $match_column_number = undef;
  632. if ( $opt->{v} ) {
  633. return ( $line !~ /$opt->{regex}/o );
  634. }
  635. else {
  636. if ( $line =~ /$opt->{regex}/o ) {
  637. # @- = @LAST_MATCH_START
  638. # @+ = @LAST_MATCH_END
  639. $match_column_number = $-[0] + 1;
  640. return 1;
  641. }
  642. else {
  643. return;
  644. }
  645. }
  646. }
  647. sub get_match_column {
  648. return $match_column_number;
  649. }
  650. }
  651. sub resource_has_match {
  652. my ( $resource, $opt ) = @_;
  653. my $has_match = 0;
  654. my $fh = $resource->open();
  655. if ( !$fh ) {
  656. if ( $App::Ack::report_bad_filenames ) {
  657. App::Ack::warn( $resource->name . ': ' . $! );
  658. }
  659. }
  660. else {
  661. my $re = $opt->{regex};
  662. if ( $opt->{v} ) {
  663. while ( <$fh> ) {
  664. if (!/$re/o) {
  665. $has_match = 1;
  666. last;
  667. }
  668. }
  669. }
  670. else {
  671. # XXX read in chunks
  672. # XXX only do this for certain file sizes?
  673. my $content = do {
  674. local $/;
  675. <$fh>;
  676. };
  677. $has_match = $content =~ /$re/og;
  678. }
  679. close $fh;
  680. }
  681. return $has_match;
  682. }
  683. sub count_matches_in_resource {
  684. my ( $resource, $opt ) = @_;
  685. my $nmatches = 0;
  686. my $fh = $resource->open();
  687. if ( !$fh ) {
  688. if ( $App::Ack::report_bad_filenames ) {
  689. App::Ack::warn( $resource->name . ': ' . $! );
  690. }
  691. }
  692. else {
  693. my $re = $opt->{regex};
  694. if ( $opt->{v} ) {
  695. while ( <$fh> ) {
  696. ++$nmatches if (!/$re/o);
  697. }
  698. }
  699. else {
  700. my $content = do {
  701. local $/;
  702. <$fh>;
  703. };
  704. $nmatches =()= ($content =~ /$re/og);
  705. }
  706. close $fh;
  707. }
  708. return $nmatches;
  709. }
  710. sub main {
  711. my @arg_sources = App::Ack::ConfigLoader::retrieve_arg_sources();
  712. my $opt = App::Ack::ConfigLoader::process_args( @arg_sources );
  713. $App::Ack::report_bad_filenames = !$opt->{dont_report_bad_filenames};
  714. if ( $opt->{flush} ) {
  715. $| = 1;
  716. }
  717. if ( !defined($opt->{color}) && !$opt->{g} ) {
  718. my $windows_color = 1;
  719. if ( $App::Ack::is_windows ) {
  720. $windows_color = eval { require Win32::Console::ANSI; };
  721. }
  722. $opt->{color} = !App::Ack::output_to_pipe() && $windows_color;
  723. }
  724. if ( not defined $opt->{heading} and not defined $opt->{break} ) {
  725. $opt->{heading} = $opt->{break} = !App::Ack::output_to_pipe();
  726. }
  727. if ( defined($opt->{H}) || defined($opt->{h}) ) {
  728. $opt->{show_filename}= $opt->{H} && !$opt->{h};
  729. }
  730. if ( my $output = $opt->{output} ) {
  731. $output =~ s{\\}{\\\\}g;
  732. $output =~ s{"}{\\"}g;
  733. $opt->{output} = qq{"$output"};
  734. }
  735. my $resources;
  736. if ( $App::Ack::is_filter_mode && !$opt->{files_from} ) { # probably -x
  737. $resources = App::Ack::Resources->from_stdin( $opt );
  738. my $regex = $opt->{regex};
  739. $regex = shift @ARGV if not defined $regex;
  740. $opt->{regex} = build_regex( $regex, $opt );
  741. }
  742. else {
  743. if ( $opt->{f} || $opt->{lines} ) {
  744. if ( $opt->{regex} ) {
  745. App::Ack::warn( "regex ($opt->{regex}) specified with -f or --lines" );
  746. App::Ack::exit_from_ack( 0 ); # XXX the 0 is misleading
  747. }
  748. }
  749. else {
  750. my $regex = $opt->{regex};
  751. $regex = shift @ARGV if not defined $regex;
  752. $opt->{regex} = build_regex( $regex, $opt );
  753. }
  754. my @start;
  755. if ( not defined $opt->{files_from} ) {
  756. @start = @ARGV;
  757. }
  758. if ( !exists($opt->{show_filename}) ) {
  759. unless(@start == 1 && !(-d $start[0])) {
  760. $opt->{show_filename} = 1;
  761. }
  762. }
  763. if ( defined $opt->{files_from} ) {
  764. $resources = App::Ack::Resources->from_file( $opt, $opt->{files_from} );
  765. exit 1 unless $resources;
  766. }
  767. else {
  768. @start = ('.') unless @start;
  769. foreach my $target (@start) {
  770. if ( !-e $target && $App::Ack::report_bad_filenames) {
  771. App::Ack::warn( "$target: No such file or directory" );
  772. }
  773. }
  774. $opt->{file_filter} = _compile_file_filter($opt, \@start);
  775. $opt->{descend_filter} = _compile_descend_filter($opt);
  776. $resources = App::Ack::Resources->from_argv( $opt, \@start );
  777. }
  778. }
  779. App::Ack::set_up_pager( $opt->{pager} ) if defined $opt->{pager};
  780. my $print_filenames = $opt->{show_filename};
  781. my $max_count = $opt->{m};
  782. my $ors = $opt->{print0} ? "\0" : "\n";
  783. my $only_first = $opt->{1};
  784. my $nmatches = 0;
  785. my $total_count = 0;
  786. RESOURCES:
  787. while ( my $resource = $resources->next ) {
  788. # XXX Combine the -f and -g functions
  789. if ( $opt->{f} ) {
  790. # XXX printing should probably happen inside of App::Ack
  791. if ( $opt->{show_types} ) {
  792. show_types( $resource, $ors );
  793. }
  794. else {
  795. App::Ack::print( $resource->name, $ors );
  796. }
  797. ++$nmatches;
  798. last RESOURCES if defined($max_count) && $nmatches >= $max_count;
  799. }
  800. elsif ( $opt->{g} ) {
  801. if ( $opt->{show_types} ) {
  802. show_types( $resource, $ors );
  803. }
  804. else {
  805. local $opt->{show_filename} = 0; # XXX Why is this local?
  806. print_line_with_options($opt, '', $resource->name, 0, $ors);
  807. }
  808. ++$nmatches;
  809. last RESOURCES if defined($max_count) && $nmatches >= $max_count;
  810. }
  811. elsif ( $opt->{lines} ) {
  812. my $print_filename = $opt->{show_filename};
  813. my $passthru = $opt->{passthru};
  814. my %line_numbers;
  815. foreach my $line ( @{ $opt->{lines} } ) {
  816. my @lines = split /,/, $line;
  817. @lines = map {
  818. /^(\d+)-(\d+)$/
  819. ? ( $1 .. $2 )
  820. : $_
  821. } @lines;
  822. @line_numbers{@lines} = (1) x @lines;
  823. }
  824. my $filename = $resource->name;
  825. local $opt->{color} = 0;
  826. iterate($resource, $opt, sub {
  827. chomp;
  828. if ( $line_numbers{$.} ) {
  829. print_line_with_context($opt, $filename, $_, $.);
  830. }
  831. elsif ( $passthru ) {
  832. print_line_with_options($opt, $filename, $_, $., ':');
  833. }
  834. return 1;
  835. });
  836. }
  837. elsif ( $opt->{count} ) {
  838. my $matches_for_this_file = count_matches_in_resource( $resource, $opt );
  839. if ( not $opt->{show_filename} ) {
  840. $total_count += $matches_for_this_file;
  841. next RESOURCES;
  842. }
  843. if ( !$opt->{l} || $matches_for_this_file > 0) {
  844. if ( $print_filenames ) {
  845. App::Ack::print( $resource->name, ':', $matches_for_this_file, $ors );
  846. }
  847. else {
  848. App::Ack::print( $matches_for_this_file, $ors );
  849. }
  850. }
  851. }
  852. elsif ( $opt->{l} || $opt->{L} ) {
  853. my $is_match = resource_has_match( $resource, $opt );
  854. if ( $opt->{L} ? !$is_match : $is_match ) {
  855. App::Ack::print( $resource->name, $ors );
  856. ++$nmatches;
  857. last RESOURCES if $only_first;
  858. last RESOURCES if defined($max_count) && $nmatches >= $max_count;
  859. }
  860. }
  861. else {
  862. $nmatches += print_matches_in_resource( $resource, $opt );
  863. if ( $nmatches && $only_first ) {
  864. last RESOURCES;
  865. }
  866. }
  867. }
  868. if ( $opt->{count} && !$opt->{show_filename} ) {
  869. App::Ack::print( $total_count, "\n" );
  870. }
  871. close $App::Ack::fh;
  872. App::Ack::exit_from_ack( $nmatches );
  873. }
  874. =head1 NAME
  875. ack - grep-like text finder
  876. =head1 SYNOPSIS
  877. ack [options] PATTERN [FILE...]
  878. ack -f [options] [DIRECTORY...]
  879. =head1 DESCRIPTION
  880. Ack is designed as an alternative to F<grep> for programmers.
  881. Ack searches the named input FILEs (or standard input if no files
  882. are named, or the file name - is given) for lines containing a match
  883. to the given PATTERN. By default, ack prints the matching lines.
  884. PATTERN is a Perl regular expression. Perl regular expressions
  885. are commonly found in other programming languages, but for the particulars
  886. of their behavior, please consult
  887. L<http://perldoc.perl.org/perlreref.html|perlreref>. If you don't know
  888. how to use regular expression but are interested in learning, you may
  889. consult L<http://perldoc.perl.org/perlretut.html|perlretut>. If you do not
  890. need or want ack to use regular expressions, please see the
  891. C<-Q>/C<--literal> option.
  892. Ack can also list files that would be searched, without actually
  893. searching them, to let you take advantage of ack's file-type filtering
  894. capabilities.
  895. =head1 FILE SELECTION
  896. If files are not specified for searching, either on the command
  897. line or piped in with the C<-x> option, I<ack> delves into
  898. subdirectories selecting files for searching.
  899. I<ack> is intelligent about the files it searches. It knows about
  900. certain file types, based on both the extension on the file and,
  901. in some cases, the contents of the file. These selections can be
  902. made with the B<--type> option.
  903. With no file selection, I<ack> searches through regular files that
  904. are not explicitly excluded by B<--ignore-dir> and B<--ignore-file>
  905. options, either present in F<ackrc> files or on the command line.
  906. The default options for I<ack> ignore certain files and directories. These
  907. include:
  908. =over 4
  909. =item * Backup files: Files matching F<#*#> or ending with F<~>.
  910. =item * Coredumps: Files matching F<core.\d+>
  911. =item * Version control directories like F<.svn> and F<.git>.
  912. =back
  913. Run I<ack> with the C<--dump> option to see what settings are set.
  914. However, I<ack> always searches the files given on the command line,
  915. no matter what type. If you tell I<ack> to search in a coredump,
  916. it will search in a coredump.
  917. =head1 DIRECTORY SELECTION
  918. I<ack> descends through the directory tree of the starting directories
  919. specified. If no directories are specified, the current working directory is
  920. used. However, it will ignore the shadow directories used by
  921. many version control systems, and the build directories used by the
  922. Perl MakeMaker system. You may add or remove a directory from this
  923. list with the B<--[no]ignore-dir> option. The option may be repeated
  924. to add/remove multiple directories from the ignore list.
  925. For a complete list of directories that do not get searched, run
  926. C<ack --dump>.
  927. =head1 WHEN TO USE GREP
  928. I<ack> trumps I<grep> as an everyday tool 99% of the time, but don't
  929. throw I<grep> away, because there are times you'll still need it.
  930. E.g., searching through huge files looking for regexes that can be
  931. expressed with I<grep> syntax should be quicker with I<grep>.
  932. If your script or parent program uses I<grep> C<--quiet> or C<--silent>
  933. or needs exit 2 on IO error, use I<grep>.
  934. =head1 OPTIONS
  935. =over 4
  936. =item B<--ackrc>
  937. Specifies an ackrc file to load after all others; see L</"ACKRC LOCATION SEMANTICS">.
  938. =item B<-A I<NUM>>, B<--after-context=I<NUM>>
  939. Print I<NUM> lines of trailing context after matching lines.
  940. =item B<-B I<NUM>>, B<--before-context=I<NUM>>
  941. Print I<NUM> lines of leading context before matching lines.
  942. =item B<--[no]break>
  943. Print a break between results from different files. On by default
  944. when used interactively.
  945. =item B<-C [I<NUM>]>, B<--context[=I<NUM>]>
  946. Print I<NUM> lines (default 2) of context around matching lines.
  947. =item B<-c>, B<--count>
  948. Suppress normal output; instead print a count of matching lines for
  949. each input file. If B<-l> is in effect, it will only show the
  950. number of lines for each file that has lines matching. Without
  951. B<-l>, some line counts may be zeroes.
  952. If combined with B<-h> (B<--no-filename>) ack outputs only one total
  953. count.
  954. =item B<--[no]color>, B<--[no]colour>
  955. B<--color> highlights the matching text. B<--nocolor> suppresses
  956. the color. This is on by default unless the output is redirected.
  957. On Windows, this option is off by default unless the
  958. L<Win32::Console::ANSI> module is installed or the C<ACK_PAGER_COLOR>
  959. environment variable is used.
  960. =item B<--color-filename=I<color>>
  961. Sets the color to be used for filenames.
  962. =item B<--color-match=I<color>>
  963. Sets the color to be used for matches.
  964. =item B<--color-lineno=I<color>>
  965. Sets the color to be used for line numbers.
  966. =item B<--[no]column>
  967. Show the column number of the first match. This is helpful for
  968. editors that can place your cursor at a given position.
  969. =item B<--create-ackrc>
  970. Dumps the default ack options to standard output. This is useful for
  971. when you want to customize the defaults.
  972. =item B<--dump>
  973. Writes the list of options loaded and where they came from to standard
  974. output. Handy for debugging.
  975. =item B<--[no]env>
  976. B<--noenv> disables all environment processing. No F<.ackrc> is
  977. read and all environment variables are ignored. By default, F<ack>
  978. considers F<.ackrc> and settings in the environment.
  979. =item B<--flush>
  980. B<--flush> flushes output immediately. This is off by default
  981. unless ack is running interactively (when output goes to a pipe or
  982. file).
  983. =item B<-f>
  984. Only print the files that would be searched, without actually doing
  985. any searching. PATTERN must not be specified, or it will be taken
  986. as a path to search.
  987. =item B<--files-from=I<FILE>>
  988. The list of files to be searched is specified in I<FILE>. The list of
  989. files are separated by newlines. If I<FILE> is C<->, the list is loaded
  990. from standard input.
  991. =item B<--[no]filter>
  992. Forces ack to act as if it were receiving input via a pipe.
  993. =item B<--[no]follow>
  994. Follow or don't follow symlinks, other than whatever starting files
  995. or directories were specified on the command line.
  996. This is off by default.
  997. =item B<-g I<PATTERN>>
  998. Print files where the relative path + filename matches I<PATTERN>.
  999. This option can be combined with B<--color> to make it easier to spot
  1000. the match.
  1001. =item B<--[no]group>
  1002. B<--group> groups matches by file name. This is the default
  1003. when used interactively.
  1004. B<--nogroup> prints one result per line, like grep. This is the
  1005. default when output is redirected.
  1006. =item B<-H>, B<--with-filename>
  1007. Print the filename for each match. This is the default unless searching
  1008. a single explicitly specified file.
  1009. =item B<-h>, B<--no-filename>
  1010. Suppress the prefixing of filenames on output when multiple files are
  1011. searched.
  1012. =item B<--[no]heading>
  1013. Print a filename heading above each file's results. This is the default
  1014. when used interactively.
  1015. =item B<--help>, B<-?>
  1016. Print a short help statement.
  1017. =item B<--help-types>, B<--help=types>
  1018. Print all known types.
  1019. =item B<-i>, B<--ignore-case>
  1020. Ignore case distinctions in PATTERN
  1021. =item B<--ignore-ack-defaults>
  1022. Tells ack to completely ignore the default definitions provided with ack.
  1023. This is useful in combination with B<--create-ackrc> if you I<really> want
  1024. to customize ack.
  1025. =item B<--[no]ignore-dir=I<DIRNAME>>, B<--[no]ignore-directory=I<DIRNAME>>
  1026. Ignore directory (as CVS, .svn, etc are ignored). May be used
  1027. multiple times to ignore multiple directories. For example, mason
  1028. users may wish to include B<--ignore-dir=data>. The B<--noignore-dir>
  1029. option allows users to search directories which would normally be
  1030. ignored (perhaps to research the contents of F<.svn/props> directories).
  1031. The I<DIRNAME> must always be a simple directory name. Nested
  1032. directories like F<foo/bar> are NOT supported. You would need to
  1033. specify B<--ignore-dir=foo> and then no files from any foo directory
  1034. are taken into account by ack unless given explicitly on the command
  1035. line.
  1036. =item B<--ignore-file=I<FILTERTYPE:FILTERARGS>>
  1037. Ignore files matching I<FILTERTYPE:FILTERARGS>. The filters are specified
  1038. identically to file type filters as seen in L</"Defining your own types">.
  1039. =item B<-k>, B<--known-types>
  1040. Limit selected files to those with types that ack knows about. This is
  1041. equivalent to the default behavior found in ack 1.
  1042. =item B<--lines=I<NUM>>
  1043. Only print line I<NUM> of each file. Multiple lines can be given with multiple
  1044. B<--lines> options or as a comma separated list (B<--lines=3,5,7>). B<--lines=4-7>
  1045. also works. The lines are always output in ascending order, no matter the
  1046. order given on the command line.
  1047. =item B<-l>, B<--files-with-matches>
  1048. Only print the filenames of matching files, instead of the matching text.
  1049. =item B<-L>, B<--files-without-matches>
  1050. Only print the filenames of files that do I<NOT> match.
  1051. =item B<--match I<PATTERN>>
  1052. Specify the I<PATTERN> explicitly. This is helpful if you don't want to put the
  1053. regex as your first argument, e.g. when executing multiple searches over the
  1054. same set of files.
  1055. # search for foo and bar in given files
  1056. ack file1 t/file* --match foo
  1057. ack file1 t/file* --match bar
  1058. =item B<-m=I<NUM>>, B<--max-count=I<NUM>>
  1059. Stop reading a file after I<NUM> matches.
  1060. =item B<--man>
  1061. Print this manual page.
  1062. =item B<-n>, B<--no-recurse>
  1063. No descending into subdirectories.
  1064. =item B<-o>
  1065. Show only the part of each line matching PATTERN (turns off text
  1066. highlighting)
  1067. =item B<--output=I<expr>>
  1068. Output the evaluation of I<expr> for each line (turns off text
  1069. highlighting)
  1070. If PATTERN matches more than once then a line is output for each non-overlapping match.
  1071. For more information please see the section L</"Examples of F<--output>">.
  1072. =item B<--pager=I<program>>, B<--nopager>
  1073. B<--pager> directs ack's output through I<program>. This can also be specified
  1074. via the C<ACK_PAGER> and C<ACK_PAGER_COLOR> environment variables.
  1075. Using --pager does not suppress grouping and coloring like piping
  1076. output on the command-line does.
  1077. B<--nopager> cancels any setting in ~/.ackrc, C<ACK_PAGER> or C<ACK_PAGER_COLOR>.
  1078. No output will be sent through a pager.
  1079. =item B<--passthru>
  1080. Prints all lines, whether or not they match the expression. Highlighting
  1081. will still work, though, so it can be used to highlight matches while
  1082. still seeing the entire file, as in:
  1083. # Watch a log file, and highlight a certain IP address
  1084. $ tail -f ~/access.log | ack --passthru 123.45.67.89
  1085. =item B<--print0>
  1086. Only works in conjunction with -f, -g, -l or -c (filename output). The filenames
  1087. are output separated with a null byte instead of the usual newline. This is
  1088. helpful when dealing with filenames that contain whitespace, e.g.
  1089. # remove all files of type html
  1090. ack -f --html --print0 | xargs -0 rm -f
  1091. =item B<-Q>, B<--literal>
  1092. Quote all metacharacters in PATTERN, it is treated as a literal.
  1093. =item B<-r>, B<-R>, B<--recurse>
  1094. Recurse into sub-directories. This is the default and just here for
  1095. compatibility with grep. You can also use it for turning B<--no-recurse> off.
  1096. =item B<-s>
  1097. Suppress error messages about nonexistent or unreadable files. This is taken
  1098. from fgrep.
  1099. =item B<--[no]smart-case>, B<--no-smart-case>
  1100. Ignore case in the search strings if PATTERN contains no uppercase
  1101. characters. This is similar to C<smartcase> in vim. This option is
  1102. off by default, and ignored if C<-i> is specified.
  1103. B<-i> always overrides this option.
  1104. =item B<--sort-files>
  1105. Sorts the found files lexicographically. Use this if you want your file
  1106. listings to be deterministic between runs of I<ack>.
  1107. =item B<--show-types>
  1108. Outputs the filetypes that ack associates with each file.
  1109. Works with B<-f> and B<-g> options.
  1110. =item B<--type=[no]TYPE>
  1111. Specify the types of files to include or exclude from a search.
  1112. TYPE is a filetype, like I<perl> or I<xml>. B<--type=perl> can
  1113. also be specified as B<--perl>, and B<--type=noperl> can be done
  1114. as B<--noperl>.
  1115. If a file is of both type "foo" and "bar", specifying --foo and
  1116. --nobar will exclude the file, because an exclusion takes precedence
  1117. over an inclusion.
  1118. Type specifications can be repeated and are ORed together.
  1119. See I<ack --help=types> for a list of valid types.
  1120. =item B<--type-add I<TYPE>:I<FILTER>:I<FILTERARGS>>
  1121. Files with the given FILTERARGS applied to the given FILTER
  1122. are recognized as being of (the existing) type TYPE.
  1123. See also L</"Defining your own types">.
  1124. =item B<--type-set I<TYPE>:I<FILTER>:I<FILTERARGS>>
  1125. Files with the given FILTERARGS applied to the given FILTER are recognized as
  1126. being of type TYPE. This replaces an existing definition for type TYPE. See
  1127. also L</"Defining your own types">.
  1128. =item B<--type-del I<TYPE>>
  1129. The filters associated with TYPE are removed from Ack, and are no longer considered
  1130. for searches.
  1131. =item B<-v>, B<--invert-match>
  1132. Invert match: select non-matching lines
  1133. =item B<--version>
  1134. Display version and copyright information.
  1135. =item B<-w>, B<--word-regexp>
  1136. Force PATTERN to match only whole words. The PATTERN is wrapped with
  1137. C<\b> metacharacters.
  1138. =item B<-x>
  1139. An abbreviation for B<--files-from=->; the list of files to search are read
  1140. from standard input, with one line per file.
  1141. =item B<-1>
  1142. Stops after reporting first match of any kind. This is different
  1143. from B<--max-count=1> or B<-m1>, where only one match per file is
  1144. shown. Also, B<-1> works with B<-f> and B<-g>, where B<-m> does
  1145. not.
  1146. =item B<--thpppt>
  1147. Display the all-important Bill The Cat logo. Note that the exact
  1148. spelling of B<--thpppppt> is not important. It's checked against
  1149. a regular expression.
  1150. =item B<--bar>
  1151. Check with the admiral for traps.
  1152. =item B<--cathy>
  1153. Chocolate, Chocolate, Chocolate!
  1154. =back
  1155. =head1 THE .ackrc FILE
  1156. The F<.ackrc> file contains command-line options that are prepended
  1157. to the command line before processing. Multiple options may live
  1158. on multiple lines. Lines beginning with a # are ignored. A F<.ackrc>
  1159. might look like this:
  1160. # Always sort the files
  1161. --sort-files
  1162. # Always color, even if piping to a another program
  1163. --color
  1164. # Use "less -r" as my pager
  1165. --pager=less -r
  1166. Note that arguments with spaces in them do not need to be quoted,
  1167. as they are not interpreted by the shell. Basically, each I<line>
  1168. in the F<.ackrc> file is interpreted as one element of C<@ARGV>.
  1169. F<ack> looks in several locations for F<.ackrc> files; the searching
  1170. process is detailed in L</"ACKRC LOCATION SEMANTICS">. These
  1171. files are not considered if B<--noenv> is specified on the command line.
  1172. =head1 Defining your own types
  1173. ack allows you to define your own types in addition to the predefined
  1174. types. This is done with command line options that are best put into
  1175. an F<.ackrc> file - then you do not have to define your types over and
  1176. over again. In the following examples the options will always be shown
  1177. on one command line so that they can be easily copy & pasted.
  1178. I<ack --perl foo> searches for foo in all perl files. I<ack --help=types>
  1179. tells you, that perl files are files ending
  1180. in .pl, .pm, .pod or .t. So what if you would like to include .xs
  1181. files as well when searching for --perl files? I<ack --type-add perl:ext:xs --perl foo>
  1182. does this for you. B<--type-add> appends
  1183. additional extensions to an existing type.
  1184. If you want to define a new type, or completely redefine an existing
  1185. type, then use B<--type-set>. I<ack --type-set eiffel:ext:e,eiffel> defines
  1186. the type I<eiffel> to include files with
  1187. the extensions .e or .eiffel. So to search for all eiffel files
  1188. containing the word Bertrand use I<ack --type-set eiffel:ext:e,eiffel --eiffel Bertrand>.
  1189. As usual, you can also write B<--type=eiffel>
  1190. instead of B<--eiffel>. Negation also works, so B<--noeiffel> excludes
  1191. all eiffel files from a search. Redefining also works: I<ack --type-set cc:ext:c,h>
  1192. and I<.xs> files no longer belong to the type I<cc>.
  1193. When defining your own types in the F<.ackrc> file you have to use
  1194. the following:
  1195. --type-set=eiffel:ext:e,eiffel
  1196. or writing on separate lines
  1197. --type-set
  1198. eiffel:ext:e,eiffel
  1199. The following does B<NOT> work in the F<.ackrc> file:
  1200. --type-set eiffel:ext:e,eiffel
  1201. In order to see all currently defined types, use I<--help-types>, e.g.
  1202. I<ack --type-set backup:ext:bak --type-add perl:ext:perl --help-types>
  1203. In addition to filtering based on extension (like ack 1.x allowed), ack 2
  1204. offers additional filter types. The generic syntax is
  1205. I<--type-set TYPE:FILTER:FILTERARGS>; I<FILTERARGS> depends on the value
  1206. of I<FILTER>.
  1207. =over 4
  1208. =item is:I<FILENAME>
  1209. I<is> filters match the target filename exactly. It takes exactly one
  1210. argument, which is the name of the file to match.
  1211. Example:
  1212. --type-set make:is:Makefile
  1213. =item ext:I<EXTENSION>[,I<EXTENSION2>[,...]]
  1214. I<ext> filters match the extension of the target file against a list
  1215. of extensions. No leading dot is needed for the extensions.
  1216. Example:
  1217. --type-set perl:ext:pl,pm,t
  1218. =item match:I<PATTERN>
  1219. I<match> filters match the target filename against a regular expression.
  1220. The regular expression is made case insensitive for the search.
  1221. Example:
  1222. --type-set make:match:/(gnu)?makefile/
  1223. =item firstlinematch:I<PATTERN>
  1224. I<firstlinematch> matches the first line of the target file against a
  1225. regular expression. Like I<match>, the regular expression is made
  1226. case insensitive.
  1227. Example:
  1228. --type-add perl:firstlinematch:/perl/
  1229. =back
  1230. More filter types may be made available in the future.
  1231. =head1 ENVIRONMENT VARIABLES
  1232. For commonly-used ack options, environment variables can make life
  1233. much easier. These variables are ignored if B<--noenv> is specified
  1234. on the command line.
  1235. =over 4
  1236. =item ACKRC
  1237. Specifies the location of the user's F<.ackrc> file. If this file doesn't
  1238. exist, F<ack> looks in the default location.
  1239. =item ACK_OPTIONS
  1240. This variable specifies default options to be placed in front of
  1241. any explicit options on the command line.
  1242. =item ACK_COLOR_FILENAME
  1243. Specifies the color of the filename when it's printed in B<--group>
  1244. mode. By default, it's "bold green".
  1245. The recognized attributes are clear, reset, dark, bold, underline,
  1246. underscore, blink, reverse, concealed black, red, green, yellow,
  1247. blue, magenta, on_black, on_red, on_green, on_yellow, on_blue,
  1248. on_magenta, on_cyan, and on_white. Case is not significant.
  1249. Underline and underscore are equivalent, as are clear and reset.
  1250. The color alone sets the foreground color, and on_color sets the
  1251. background color.
  1252. This option can also be set with B<--color-filename>.
  1253. =item ACK_COLOR_MATCH
  1254. Specifies the color of the matching text when printed in B<--color>
  1255. mode. By default, it's "black on_yellow".
  1256. This option can also be set with B<--color-match>.
  1257. See B<ACK_COLOR_FILENAME> for the color specifications.
  1258. =item ACK_COLOR_LINENO
  1259. Specifies the color of the line number when printed in B<--color>
  1260. mode. By default, it's "bold yellow".
  1261. This option can also be set with B<--color-lineno>.
  1262. See B<ACK_COLOR_FILENAME> for the color specifications.
  1263. =item ACK_PAGER
  1264. Specifies a pager program, such as C<more>, C<less> or C<most>, to which
  1265. ack will send its output.
  1266. Using C<ACK_PAGER> does not suppress grouping and coloring like
  1267. piping output on the command-line does, except that on Windows
  1268. ack will assume that C<ACK_PAGER> does not support color.
  1269. C<ACK_PAGER_COLOR> overrides C<ACK_PAGER> if both are specified.
  1270. =item ACK_PAGER_COLOR
  1271. Specifies a pager program that understands ANSI color sequences.
  1272. Using C<ACK_PAGER_COLOR> does not suppress grouping and coloring
  1273. like piping output on the command-line does.
  1274. If you are not on Windows, you never need to use C<ACK_PAGER_COLOR>.
  1275. =back
  1276. =head1 AVAILABLE COLORS
  1277. F<ack> uses the colors available in Perl's L<Term::ANSIColor> module, which
  1278. provides the following listed values. Note that case does not matter when using
  1279. these values.
  1280. =head2 Foreground colors
  1281. black red green yellow blue magenta cyan white
  1282. bright_black bright_red bright_green bright_yellow
  1283. bright_blue bright_magenta bright_cyan bright_white
  1284. =head2 Background colors
  1285. on_black on_red on_green on_yellow
  1286. on_blue on_magenta on_cyan on_white
  1287. on_bright_black on_bright_red on_bright_green on_bright_yellow
  1288. on_bright_blue on_bright_magenta on_bright_cyan on_bright_white
  1289. =head1 ACK & OTHER TOOLS
  1290. =head2 Vim integration
  1291. F<ack> integrates easily with the Vim text editor. Set this in your
  1292. F<.vimrc> to use F<ack> instead of F<grep>:
  1293. set grepprg=ack\ -k
  1294. That example uses C<-k> to search through only files of the types ack
  1295. knows about, but you may use other default flags. Now you can search
  1296. with F<ack> and easily step through the results in Vim:
  1297. :grep Dumper perllib
  1298. Miles Sterrett has written a Vim plugin for F<ack> which allows you to use
  1299. C<:Ack> instead of C<:grep>, as well as several other advanced features.
  1300. L<https://github.com/mileszs/ack.vim>
  1301. =head2 Emacs integration
  1302. Phil Jackson put together an F<ack.el> extension that "provides a
  1303. simple compilation mode ... has the ability to guess what files you
  1304. want to search for based on the major-mode."
  1305. L<http://www.shellarchive.co.uk/content/emacs.html>
  1306. =head2 TextMate integration
  1307. Pedro Melo is a TextMate user who writes "I spend my day mostly
  1308. inside TextMate, and the built-in find-in-project sucks with large
  1309. projects. So I hacked a TextMate command that was using find +
  1310. grep to use ack. The result is the Search in Project with ack, and
  1311. you can find it here:
  1312. L<http://www.simplicidade.org/notes/archives/2008/03/search_in_proje.html>"
  1313. =head2 Shell and Return Code
  1314. For greater compatibility with I<grep>, I<ack> in normal use returns
  1315. shell return or exit code of 0 only if something is found and 1 if
  1316. no match is found.
  1317. (Shell exit code 1 is C<$?=256> in perl with C<system> or backticks.)
  1318. The I<grep> code 2 for errors is not used.
  1319. If C<-f> or C<-g> are specified, then 0 is returned if at least one
  1320. file is found. If no files are found, then 1 is returned.
  1321. =cut
  1322. =head1 DEBUGGING ACK PROBLEMS
  1323. If ack gives you output you're not expecting, start with a few simple steps.
  1324. =head2 Use B<--noenv>
  1325. Your environment variables and F<.ackrc> may be doing things you're
  1326. not expecting, or forgotten you specified. Use B<--noenv> to ignore
  1327. your environment and F<.ackrc>.
  1328. =head2 Use B<-f> to see what files have been selected
  1329. Ack's B<-f> was originally added as a debugging tool. If ack is
  1330. not finding matches you think it should find, run F<ack -f> to see
  1331. what files have been selected. You can also add the C<--show-types>
  1332. options to show the type of each file selected.
  1333. =head2 Use B<--dump>
  1334. This lists the ackrc files that are loaded and the options loaded
  1335. from them.
  1336. So for example you can find a list of directories that do not get searched or where filetypes are defined.
  1337. =head1 TIPS
  1338. =head2 Use the F<.ackrc> file.
  1339. The F<.ackrc> is the place to put all your options you use most of
  1340. the time but don't want to remember. Put all your --type-add and
  1341. --type-set definitions in it. If you like --smart-case, set it
  1342. there, too. I also set --sort-files there.
  1343. =head2 Use F<-f> for working with big codesets
  1344. Ack does more than search files. C<ack -f --perl> will create a
  1345. list of all the Perl files in a tree, ideal for sending into F<xargs>.
  1346. For example:
  1347. # Change all "this" to "that" in all Perl files in a tree.
  1348. ack -f --perl | xargs perl -p -i -e's/this/that/g'
  1349. or if you prefer:
  1350. perl -p -i -e's/this/that/g' $(ack -f --perl)
  1351. =head2 Use F<-Q> when in doubt about metacharacters
  1352. If you're searching for something with a regular expression
  1353. metacharacter, most often a period in a filename or IP address, add
  1354. the -Q to avoid false positives without all the backslashing. See
  1355. the following example for more...
  1356. =head2 Use ack to watch log files
  1357. Here's one I used the other day to find trouble spots for a website
  1358. visitor. The user had a problem loading F<troublesome.gif>, so I
  1359. took the access log and scanned it with ack twice.
  1360. ack -Q aa.bb.cc.dd /path/to/access.log | ack -Q -B5 troublesome.gif
  1361. The first ack finds only the lines in the Apache log for the given
  1362. IP. The second finds the match on my troublesome GIF, and shows
  1363. the previous five lines from the log in each case.
  1364. =head2 Examples of F<--output>
  1365. Following variables are useful in the expansion string:
  1366. =over 4
  1367. =item C<$&>
  1368. The whole string matched by PATTERN.
  1369. =item C<$1>, C<$2>, ...
  1370. The contents of the 1st, 2nd ... bracketed group in PATTERN.
  1371. =item C<$`>
  1372. The string before the match.
  1373. =item C<$'>
  1374. The string after the match.
  1375. =back
  1376. For more details and other variables see
  1377. L<http://perldoc.perl.org/perlvar.html#Variables-related-to-regular-expressions|perlvar>.
  1378. This example shows how to add text around a particular pattern
  1379. (in this case adding _ around word with "e")
  1380. ack2.pl "\w*e\w*" quick.txt --output="$`_$&_$'"
  1381. _The_ quick brown fox jumps over the lazy dog
  1382. The quick brown fox jumps _over_ the lazy dog
  1383. The quick brown fox jumps over _the_ lazy dog
  1384. This shows how to pick out particular parts of a match using ( ) within regular expression.
  1385. ack '=head(\d+)\s+(.*)' --output=' $1 : $2'
  1386. input file contains "=head1 NAME"
  1387. output "1 : NAME"
  1388. =head2 Share your knowledge
  1389. Join the ack-users mailing list. Send me your tips and I may add
  1390. them here.
  1391. =head1 FAQ
  1392. =head2 Why isn't ack finding a match in (some file)?
  1393. Probably because it's of a type that ack doesn't recognize. ack's
  1394. searching behavior is driven by filetype. B<If ack doesn't know
  1395. what kind of file it is, ack ignores the file.>
  1396. Use the C<-f> switch to see a list of files that ack will search
  1397. for you. You can use the C<--show-types> switch to show which type
  1398. ack thinks each file is.
  1399. =head2 Wouldn't it be great if F<ack> did search & replace?
  1400. No, ack will always be read-only. Perl has a perfectly good way
  1401. to do search & replace in files, using the C<-i>, C<-p> and C<-n>
  1402. switches.
  1403. You can certainly use ack to select your files to update. For
  1404. example, to change all "foo" to "bar" in all PHP files, you can do
  1405. this from the Unix shell:
  1406. $ perl -i -p -e's/foo/bar/g' $(ack -f --php)
  1407. =head2 Can I make ack recognize F<.xyz> files?
  1408. Yes! Please see L</"Defining your own types">. If you think
  1409. that F<ack> should recognize a type by default, please see
  1410. L</"ENHANCEMENTS">.
  1411. =head2 There's already a program/package called ack.
  1412. Yes, I know.
  1413. =head2 Why is it called ack if it's called ack-grep?
  1414. The name of the program is "ack". Some packagers have called it
  1415. "ack-grep" when creating packages because there's already a package
  1416. out there called "ack" that has nothing to do with this ack.
  1417. I suggest you make a symlink named F<ack> that points to F<ack-grep>
  1418. because one of the crucial benefits of ack is having a name that's
  1419. so short and simple to type.
  1420. To do that, run this with F<sudo> or as root:
  1421. ln -s /usr/bin/ack-grep /usr/bin/ack
  1422. Alternatively, you could use a shell alias:
  1423. # bash/zsh
  1424. alias ack=ack-grep
  1425. # csh
  1426. alias ack ack-grep
  1427. =head2 What does F<ack> mean?
  1428. Nothing. I wanted a name that was easy to type and that you could
  1429. pronounce as a single syllable.
  1430. =head2 Can I do multi-line regexes?
  1431. No, ack does not support regexes that match multiple lines. Doing
  1432. so would require reading in the entire file at a time.
  1433. If you want to see lines near your match, use the C<--A>, C<--B>
  1434. and C<--C> switches for displaying context.
  1435. =head2 Why is ack telling me I have an invalid option when searching for C<+foo>?
  1436. ack treats command line options beginning with C<+> or C<-> as options; if you
  1437. would like to search for these, you may prefix your search term with C<--> or
  1438. use the C<--match> option. (However, don't forget that C<+> is a regular
  1439. expression metacharacter!)
  1440. =head2 Why does C<"ack '.{40000,}'"> fail? Isn't that a valid regex?
  1441. The Perl language limits the repetition quanitifier to 32K. You
  1442. can search for C<.{32767}> but not C<.{32768}>.
  1443. =head1 ACKRC LOCATION SEMANTICS
  1444. Ack can load its configuration from many sources. This list
  1445. specifies the sources Ack looks for configuration; each one
  1446. that is found is loaded in the order specified here, and
  1447. each one overrides options set in any of the sources preceding
  1448. it. (For example, if I set --sort-files in my user ackrc, and
  1449. --nosort-files on the command line, the command line takes
  1450. precedence)
  1451. =over 4
  1452. =item *
  1453. Defaults are loaded from App::Ack::ConfigDefaults. This can be omitted
  1454. using C<--ignore-ack-defaults>.
  1455. =item * Global ackrc
  1456. Options are then loaded from the global ackrc. This is located at
  1457. C</etc/ackrc> on Unix-like systems.
  1458. Under Windows XP and earlier, the ackrc is at
  1459. C<C:\Documents and Settings\All Users\Application Data\ackrc>.
  1460. Under Windows Vista/7, the global ackrc is at
  1461. C<C:\ProgramData>
  1462. The C<--noenv> option prevents all ackrc files from being loaded.
  1463. =item * User ackrc
  1464. Options are then loaded from the user's ackrc. This is located at
  1465. C<$HOME/.ackrc> on Unix-like systems.
  1466. Under Windows XP and earlier, the user's ackrc is at
  1467. C<C:\Documents and Settings\$USER\Application Data\ackrc>.
  1468. Under Windows Vista/7, the user's ackrc is at
  1469. <C:\Users\$USER\AppData\Roaming>.
  1470. If you want to load a different user-level ackrc, it may be specified
  1471. with the C<$ACKRC> environment variable.
  1472. The C<--noenv> option prevents all ackrc files from being loaded.
  1473. =item * Project ackrc
  1474. Options are then loaded from the project ackrc. The project ackrc is
  1475. the first ackrc file with the name C<.ackrc> or C<_ackrc>, first searching
  1476. in the current directory, then the parent directory, then the grandparent
  1477. directory, etc. This can be omitted using C<--noenv>.
  1478. =item * --ackrc
  1479. The C<--ackrc> option may be included on the command line to specify an
  1480. ackrc file that can override all others. It is consulted even if C<--noenv>
  1481. is present.
  1482. =item * ACK_OPTIONS
  1483. Options are then loaded from the environment variable C<ACK_OPTIONS>. This can
  1484. be omitted using C<--noenv>.
  1485. =item * Command line
  1486. Options are then loaded from the command line.
  1487. =back
  1488. =head1 DIFFERENCES BETWEEN ACK 1.X AND ACK 2.X
  1489. A lot of changes were made for ack 2; here is a list of them.
  1490. =head2 GENERAL CHANGES
  1491. =over 4
  1492. =item *
  1493. When no selectors are specified, ack 1.x only searches through files that
  1494. it can map to a file type. ack 2.x, by contrast, will search through
  1495. every regular, non-binary file that is not explicitly ignored via
  1496. B<--ignore-file> or B<--ignore-dir>. This is similar to the behavior of the
  1497. B<-a/--all> option in ack 1.x.
  1498. =item *
  1499. A more flexible filter system has been added, so that more powerful file types
  1500. may be created by the user. For details, please consult
  1501. L</"Defining your own types">.
  1502. =item *
  1503. ack now loads multiple ackrc files; see L</"ACKRC LOCATION SEMANTICS"> for
  1504. details.
  1505. =item *
  1506. ack's default filter definitions aren't special; you may tell ack to
  1507. completely disregard them if you don't like them.
  1508. =back
  1509. =head2 REMOVED OPTIONS
  1510. =over 4
  1511. =item *
  1512. Because of the change in default search behavior, the B<-a/--all> and
  1513. B<-u/--unrestricted> options have been removed. In addition, the
  1514. B<-k/--known-types> option was added to cause ack to behave with
  1515. the default search behavior of ack 1.x.
  1516. =item *
  1517. The B<-G> option has been removed. Two regular expressions on the
  1518. command line was considered too confusing; to simulate B<-G>'s functionality,
  1519. you may use the new B<-x> option to pipe filenames from one invocation of
  1520. ack into another.
  1521. =item *
  1522. The B<--binary> option has been removed.
  1523. =item *
  1524. The B<--skipped> option has been removed.
  1525. =item *
  1526. The B<--text> option has been removed.
  1527. =item *
  1528. The B<--invert-file-match> option has been removed. Instead, you may
  1529. use B<-v> with B<-g>.
  1530. =back
  1531. =head2 CHANGED OPTIONS
  1532. =over 4
  1533. =item *
  1534. The options that modify the regular expression's behavior (B<-i>, B<-w>,
  1535. B<-Q>, and B<-v>) may now be used with B<-g>.
  1536. =back
  1537. =head2 ADDED OPTIONS
  1538. =over 4
  1539. =item *
  1540. B<--files-from> was added so that a user may submit a list of filenames as
  1541. a list of files to search.
  1542. =item *
  1543. B<-x> was added to tell ack to accept a list of filenames via standard input;
  1544. this list is the list of filenames that will be used for the search.
  1545. =item *
  1546. B<-s> was added to tell ack to suppress error messages about non-existent or
  1547. unreadable files.
  1548. =item *
  1549. B<--ignore-directory> and B<--noignore-directory> were added as aliases for
  1550. B<--ignore-dir> and B<--noignore-dir> respectively.
  1551. =item *
  1552. B<--ignore-file> was added so that users may specify patterns of files to
  1553. ignore (ex. /.*~$/).
  1554. =item *
  1555. B<--dump> was added to allow users to easily find out which options are
  1556. set where.
  1557. =item *
  1558. B<--create-ackrc> was added so that users may create custom ackrc files based
  1559. on the default settings loaded by ack, and so that users may easily view those
  1560. defaults.
  1561. =item *
  1562. B<--type-del> was added to selectively remove file type definitions.
  1563. =item *
  1564. B<--ignore-ack-defaults> was added so that users may ignore ack's default
  1565. options in favor of their own.
  1566. =item *
  1567. B<--bar> was added so ack users may consult Admiral Ackbar.
  1568. =back
  1569. =head1 AUTHOR
  1570. Andy Lester, C<< <andy at petdance.com> >>
  1571. =head1 BUGS
  1572. Please report any bugs or feature requests to the issues list at
  1573. Github: L<https://github.com/petdance/ack2/issues>
  1574. =head1 ENHANCEMENTS
  1575. All enhancement requests MUST first be posted to the ack-users
  1576. mailing list at L<http://groups.google.com/group/ack-users>. I
  1577. will not consider a request without it first getting seen by other
  1578. ack users. This includes requests for new filetypes.
  1579. There is a list of enhancements I want to make to F<ack> in the ack
  1580. issues list at Github: L<https://github.com/petdance/ack2/issues>
  1581. Patches are always welcome, but patches with tests get the most
  1582. attention.
  1583. =head1 SUPPORT
  1584. Support for and information about F<ack> can be found at:
  1585. =over 4
  1586. =item * The ack homepage
  1587. L<http://beyondgrep.com/>
  1588. =item * The ack-users mailing list
  1589. L<http://groups.google.com/group/ack-users>
  1590. =item * The ack issues list at Github
  1591. L<https://github.com/petdance/ack2/issues>
  1592. =item * AnnoCPAN: Annotated CPAN documentation
  1593. L<http://annocpan.org/dist/ack>
  1594. =item * CPAN Ratings
  1595. L<http://cpanratings.perl.org/d/ack>
  1596. =item * Search CPAN
  1597. L<http://search.cpan.org/dist/ack>
  1598. =item * Git source repository
  1599. L<https://github.com/petdance/ack2>
  1600. =back
  1601. =head1 ACKNOWLEDGEMENTS
  1602. How appropriate to have I<ack>nowledgements!
  1603. Thanks to everyone who has contributed to ack in any way, including
  1604. Stephen Thirlwall,
  1605. Jonah Bishop,
  1606. Chris Rebert,
  1607. Denis Howe,
  1608. RaE<uacute>l GundE<iacute>n,
  1609. James McCoy,
  1610. Daniel Perrett,
  1611. Steven Lee,
  1612. Jonathan Perret,
  1613. Fraser Tweedale,
  1614. RaE<aacute>l GundE<aacute>n,
  1615. Steffen Jaeckel,
  1616. Stephan Hohe,
  1617. Michael Beijen,
  1618. Alexandr Ciornii,
  1619. Christian Walde,
  1620. Charles Lee,
  1621. Joe McMahon,
  1622. John Warwick,
  1623. David Steinbrunner,
  1624. Kara Martens,
  1625. Volodymyr Medvid,
  1626. Ron Savage,
  1627. Konrad Borowski,
  1628. Dale Sedivic,
  1629. Michael McClimon,
  1630. Andrew Black,
  1631. Ralph Bodenner,
  1632. Shaun Patterson,
  1633. Ryan Olson,
  1634. Shlomi Fish,
  1635. Karen Etheridge,
  1636. Olivier Mengue,
  1637. Matthew Wild,
  1638. Scott Kyle,
  1639. Nick Hooey,
  1640. Bo Borgerson,
  1641. Mark Szymanski,
  1642. Marq Schneider,
  1643. Packy Anderson,
  1644. JR Boyens,
  1645. Dan Sully,
  1646. Ryan Niebur,
  1647. Kent Fredric,
  1648. Mike Morearty,
  1649. Ingmar Vanhassel,
  1650. Eric Van Dewoestine,
  1651. Sitaram Chamarty,
  1652. Adam James,
  1653. Richard Carlsson,
  1654. Pedro Melo,
  1655. AJ Schuster,
  1656. Phil Jackson,
  1657. Michael Schwern,
  1658. Jan Dubois,
  1659. Christopher J. Madsen,
  1660. Matthew Wickline,
  1661. David Dyck,
  1662. Jason Porritt,
  1663. Jjgod Jiang,
  1664. Thomas Klausner,
  1665. Uri Guttman,
  1666. Peter Lewis,
  1667. Kevin Riggle,
  1668. Ori Avtalion,
  1669. Torsten Blix,
  1670. Nigel Metheringham,
  1671. GE<aacute>bor SzabE<oacute>,
  1672. Tod Hagan,
  1673. Michael Hendricks,
  1674. E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason,
  1675. Piers Cawley,
  1676. Stephen Steneker,
  1677. Elias Lutfallah,
  1678. Mark Leighton Fisher,
  1679. Matt Diephouse,
  1680. Christian Jaeger,
  1681. Bill Sully,
  1682. Bill Ricker,
  1683. David Golden,
  1684. Nilson Santos F. Jr,
  1685. Elliot Shank,
  1686. Merijn Broeren,
  1687. Uwe Voelker,
  1688. Rick Scott,
  1689. Ask BjE<oslash>rn Hansen,
  1690. Jerry Gay,
  1691. Will Coleda,
  1692. Mike O'Regan,
  1693. Slaven ReziE<0x107>,
  1694. Mark Stosberg,
  1695. David Alan Pisoni,
  1696. Adriano Ferreira,
  1697. James Keenan,
  1698. Leland Johnson,
  1699. Ricardo Signes,
  1700. Pete Krawczyk and
  1701. Rob Hoelz.
  1702. =head1 COPYRIGHT & LICENSE
  1703. Copyright 2005-2014 Andy Lester.
  1704. This program is free software; you can redistribute it and/or modify
  1705. it under the terms of the Artistic License v2.0.
  1706. See http://www.perlfoundation.org/artistic_license_2_0 or the LICENSE.md
  1707. file that comes with the ack distribution.
  1708. =cut
  1709. package App::Ack;
  1710. use warnings;
  1711. use strict;
  1712. our $VERSION;
  1713. our $COPYRIGHT;
  1714. BEGIN {
  1715. $VERSION = '2.14';
  1716. $COPYRIGHT = 'Copyright 2005-2014 Andy Lester.';
  1717. }
  1718. our $fh;
  1719. BEGIN {
  1720. $fh = *STDOUT;
  1721. }
  1722. our %types;
  1723. our %type_wanted;
  1724. our %mappings;
  1725. our %ignore_dirs;
  1726. our $is_filter_mode;
  1727. our $output_to_pipe;
  1728. our $dir_sep_chars;
  1729. our $is_cygwin;
  1730. our $is_windows;
  1731. use File::Spec 1.00015 ();
  1732. BEGIN {
  1733. # These have to be checked before any filehandle diddling.
  1734. $output_to_pipe = not -t *STDOUT;
  1735. $is_filter_mode = -p STDIN;
  1736. $is_cygwin = ($^O eq 'cygwin');
  1737. $is_windows = ($^O eq 'MSWin32');
  1738. $dir_sep_chars = $is_windows ? quotemeta( '\\/' ) : quotemeta( File::Spec->catfile( '', '' ) );
  1739. }
  1740. sub remove_dir_sep {
  1741. my $path = shift;
  1742. $path =~ s/[$dir_sep_chars]$//;
  1743. return $path;
  1744. }
  1745. sub warn {
  1746. return CORE::warn( _my_program(), ': ', @_, "\n" );
  1747. }
  1748. sub die {
  1749. return CORE::die( _my_program(), ': ', @_, "\n" );
  1750. }
  1751. sub _my_program {
  1752. require File::Basename;
  1753. return File::Basename::basename( $0 );
  1754. }
  1755. sub filetypes_supported {
  1756. return keys %mappings;
  1757. }
  1758. sub _get_thpppt {
  1759. my $y = q{_ /|,\\'!.x',=(www)=, U };
  1760. $y =~ tr/,x!w/\nOo_/;
  1761. return $y;
  1762. }
  1763. sub _thpppt {
  1764. my $y = _get_thpppt();
  1765. App::Ack::print( "$y ack $_[0]!\n" );
  1766. exit 0;
  1767. }
  1768. sub _bar {
  1769. my $x;
  1770. $x = <<'_BAR';
  1771. 6?!I'7!I"?%+!
  1772. 3~!I#7#I"7#I!?!+!="+"="+!:!
  1773. 2?#I!7!I!?#I!7!I"+"=%+"=#
  1774. 1?"+!?*+!=#~"=!+#?"="+!
  1775. 0?"+!?"I"?&+!="~!=!~"=!+%="+"
  1776. /I!+!?)+!?!+!=$~!=!~!="+!="+"?!="?!
  1777. .?%I"?%+%='?!=#~$="
  1778. ,,!?%I"?(+$=$~!=#:"~$:!~!
  1779. ,I!?!I!?"I"?!+#?"+!?!+#="~$:!~!:!~!:!,!:!,":#~!
  1780. +I!?&+!="+!?#+$=!~":!~!:!~!:!,!:#,!:!,%:"
  1781. *+!I!?!+$=!+!=!+!?$+#=!~":!~":#,$:",#:!,!:!
  1782. *I!?"+!?!+!=$+!?#+#=#~":$,!:",!:!,&:"
  1783. )I!?$=!~!=#+"?!+!=!+!=!~!="~!:!~":!,'.!,%:!~!
  1784. (=!?"+!?!=!~$?"+!?!+!=#~"=",!="~$,$.",#.!:!=!
  1785. (I"+"="~"=!+&=!~"=!~!,!~!+!=!?!+!?!=!I!?!+"=!.",!.!,":!
  1786. %I$?!+!?!=%+!~!+#~!=!~#:#=!~!+!~!=#:!,%.!,!.!:"
  1787. $I!?!=!?!I!+!?"+!=!~!=!~!?!I!?!=!+!=!~#:",!~"=!~!:"~!=!:",&:" '-/
  1788. $?!+!I!?"+"=!+"~!,!:"+#~#:#,"=!~"=!,!~!,!.",!:".!:! */! !I!t!'!s! !a! !g!r!e!p!!! !/!
  1789. $+"=!+!?!+"~!=!:!~!:"I!+!,!~!=!:!~!,!:!,$:!~".&:"~!,# (-/
  1790. %~!=!~!=!:!.!+"~!:!,!.!,!~!=!:$.!,":!,!.!:!~!,!:!=!.#="~!,!:" ./!
  1791. %=!~!?!+"?"+!=!~",!.!:!?!~!.!:!,!:!,#.!,!:","~!:!=!~!=!:",!~! ./!
  1792. %+"~":!~!=#~!:!~!,!.!~!:",!~!=!~!.!:!,!.",!:!,":!=":!.!,!:!7! -/!
  1793. %~",!:".#:!=!:!,!:"+!:!~!:!.!,!~!,!.#,!.!,$:"~!,":"~!=! */!
  1794. &=!~!=#+!=!~",!.!:",#:#,!.",+:!,!.",!=!+!?!
  1795. &~!=!~!=!~!:"~#:",!.!,#~!:!.!+!,!.",$.",$.#,!+!I!?!
  1796. &~!="~!:!~":!~",!~!=!~":!,!:!~!,!:!,&.$,#."+!?!I!?!I!
  1797. &~!=!~!=!+!,!:!~!:!=!,!:!~&:$,!.!,".!,".!,#."~!+!?$I!
  1798. &~!=!~!="~!=!:!~":!,!~%:#,!:",!.!,#.",#I!7"I!?!+!?"I"
  1799. &+!I!7!:#~"=!~!:!,!:"~$.!=!.!,!~!,$.#,!~!7!I#?!+!?"I"7!
  1800. %7#?!+!~!:!=!~!=!~":!,!:"~":#.!,)7#I"?"I!7&
  1801. %7#I!=":!=!~!:"~$:"~!:#,!:!,!:!~!:#,!7#I!?#7)
  1802. $7$+!,!~!=#~!:!~!:!~$:#,!.!~!:!=!,":!7#I"?#7+=!?!
  1803. $7#I!~!,!~#=!~!:"~!:!,!:!,#:!=!~",":!7$I!?#I!7*+!=!+"
  1804. "I!7$I!,":!,!.!=":$,!:!,$:$7$I!+!?"I!7+?"I!7!I!7!,!
  1805. !,!7%I!:",!."~":!,&.!,!:!~!I!7$I!+!?"I!7,?!I!7',!
  1806. !7(,!.#~":!,%.!,!7%I!7!?#I"7,+!?!7*
  1807. 7+:!,!~#,"=!7'I!?#I"7/+!7+
  1808. 77I!+!7!?!7!I"71+!7,
  1809. _BAR
  1810. return App::Ack::__pic($x);
  1811. }
  1812. sub _cathy {
  1813. my $x = <<'CATHY';
  1814. 0+!--+!
  1815. 0|! "C!H!O!C!O!L!A!T!E!!! !|!
  1816. 0|! "C!H!O!C!O!L!A!T!E!!! !|!
  1817. 0|! "C!H!O!C!O!L!A!T!E!!! !|!
  1818. 0|! $A"C!K!!! $|!
  1819. 0+!--+!
  1820. 6\! 1:!,!.! !
  1821. 7\! /.!M!~!Z!M!~!
  1822. 8\! /~!D! "M! !
  1823. 4.! $\! /M!~!.!8! +.!M# 4
  1824. 0,!.! (\! .~!M!N! ,+!I!.!M!.! 3
  1825. /?!O!.!M!:! '\! .O!.! +~!Z!=!N!.! 4
  1826. ..! !D!Z!.!Z!.! '\! 9=!M".! 6
  1827. /.! !.!~!M".! '\! 8~! 9
  1828. 4M!.! /.!7!N!M!.! F
  1829. 4.! &:!M! !N"M# !M"N!M! #D!M&=! =
  1830. :M!7!M#:! !~!M!7!,!$!M!:! #.! !O!N!.!M!:!M# ;
  1831. 8Z!M"~!N!$!D!.!N!?! !I!N!.! (?!M! !M!,!D!M".! 9
  1832. (?!Z!M!N!:! )=!M!O!8!.!M!+!M! !M!,! !O!M! +,!M!.!M!~!Z!N!M!:! &:!~! 0
  1833. &8!7!.!~!M"D!M!,! &M!?!=!8! !M!,!O! !M!+! !+!O!.!M! $M#~! !.!8!M!Z!.!M! !O!M"Z! %:!~!M!Z!M!Z!.! +
  1834. &:!M!7!,! *M!.!Z!M! !8"M!.!M!~! !.!M!.!=! #~!8!.!M! !7!M! "N!Z#I! !D!M!,!M!.! $."M!,! !M!.! *
  1835. 2$!O! "N! !.!M!I! !7" "M! "+!O! !~!M! !d!O!.!7!I!M!.! !.!O!=!M!.! !M",!M!.! %.!$!O!D! +
  1836. 1~!O! "M!+! !8!$! "M! "?!O! %Z!8!D!M!?!8!I!O!7!M! #M!.!M! "M",!M! 4
  1837. 07!~! ".!8! !.!M! "I!+! !.!M! &Z!D!.!7!=!M! !:!.!M! #:!8"+! !.!+!8! !8! 3
  1838. /~!M! #N! !~!M!$! !.!M! !.!M" &~!M! "~!M!O! "D! $M! !8! "M!,!M!+!D!.! 1
  1839. #.! #?!M!N!.! #~!O! $M!.!7!$! "?" !?!~!M! '7!8!?!M!.!+!M"O! $?"$!D! !.!O! !$!7!I!.! 0
  1840. $,!M!:!O!?! ".! !?!=! $=!:!O! !M! "M! !M! !+!$! (.! +.!M! !M!.! !8! !+"Z!~! $:!M!$! !.! '
  1841. #.!8!.!I!$! $7!I! %M" !=!M! !~!M!D! "7!I! .I!O! %?!=!,!D! !,!M! !D!~!8!~! %D!M! (
  1842. #.!M"?! $=!O! %=!N! "8!.! !Z!M! #M!~! (M!:! #.!M" &O! !M!.! !?!,! !8!.!N!~! $8!N!M!,!.! %
  1843. *$!O! &M!,! "O! !.!M!.! #M! (~!M( &O!.! !7! "M! !.!M!.!M!,! #.!M! !M! &
  1844. )=!8!.! $.!M!O!.! "$!.!I!N! !I!M# (7!M(I! %D"Z!M! "=!I! "M! !M!:! #~!D! '
  1845. )D! &8!N!:! ".!O! !M!="M! "M! (7!M) %." !M!D!."M!.! !$!=! !M!,! +
  1846. (M! &+!.!M! #Z!7!O!M!.!~!8! +,!M#D!?!M#D! #.!Z!M#,!Z!?! !~!N! "N!.! !M! +
  1847. 'D!:! %$!D! !?! #M!Z! !8!.! !M"?!7!?!7! '+!I!D! !?!O!:!M!:! ":!M!:! !M!7".!M! "8!+! !:!D! !.!M! *
  1848. %.!O!:! $.!O!+! !D!.! #M! "M!.!+!N!I!Z! "7!M!N!M!N!?!I!7!Z!=!M'D"~! #M!.!8!$! !:! !.!M! "N!?! !,!O! )
  1849. !.!?!M!:!M!I! %8!,! "M!.! #M! "N! !M!.! !M!.! !+!~! !.!M!.! ':!M! $M! $M!Z!$! !M!.! "D! "M! "?!M! (
  1850. !7!8! !+!I! ".! "$!=! ":!$! "+! !M!.! !O! !M!I!M".! !=!~! ",!O! '=!M! $$!,! #N!:! ":!8!.! !D!~! !,!M!.! !:!M!.! &
  1851. !:!,!.! &Z" #D! !.!8!."M!.! !8!?!Z!M!.!M! #Z!~! !?!M!Z!.! %~!O!.!8!$!N!8!O!I!:!~! !+! #M!.! !.!M!.! !+!M! ".!~!M!+! $
  1852. !.! 'D!I! #?!M!.!M!,! !.!Z! !.!8! #M&O!I!?! (~!I!M"." !M!Z!.! !M!N!.! "+!$!.! "M!.! !M!?!.! "8!M! $
  1853. (O!8! $M! !M!.! ".!:! !+!=! #M! #.!M! !+" *$!M":!.! !M!~! "M!7! #M! #7!Z! "M"$!M!.! !.! #
  1854. '$!Z! #.!7!+!M! $.!,! !+!:! #N! #.!M!.!+!M! +D!M! #=!N! ":!O! #=!M! #Z!D! $M!I! %
  1855. $,! ".! $.!M" %$!.! !?!~! "+!7!." !.!M!,! !M! *,!N!M!.$M!?! "D!,! #M!.! #N! +
  1856. ,M!Z! &M! "I!,! "M! %I!M! !?!=!.! (Z!8!M! $:!M!.! !,!M! $D! #.!M!.! )
  1857. +8!O! &.!8! "I!,! !~!M! &N!M! !M!D! '?!N!O!." $?!7! "?!~! #M!.! #I!D!.! (
  1858. 3M!,! "N!.! !D" &.!+!M!.! !M":!.":!M!7!M!D! 'M!.! "M!.! "M!,! $I! )
  1859. 3I! #M! "M!,! !:! &.!M" ".!,! !.!$!M!I! #.! !:! !.!M!?! "N!+! ".! /
  1860. 1M!,! #.!M!8!M!=!.! +~!N"O!Z"~! *+!M!.! "M! 2
  1861. 0.!M! &M!.! 8:! %.!M!Z! "M!=! *O!,! %
  1862. 0?!$! &N! )." .,! %."M! ":!M!.! 0
  1863. 0N!:! %?!O! #.! ..! &,! &.!D!,! "N!I! 0
  1864. CATHY
  1865. return App::Ack::__pic($x);
  1866. }
  1867. sub __pic {
  1868. my($compressed) = @_;
  1869. $compressed =~ s/(.)(.)/$1x(ord($2)-32)/eg;
  1870. App::Ack::print( $compressed );
  1871. exit 0;
  1872. }
  1873. sub show_help {
  1874. my $help_arg = shift || 0;
  1875. return show_help_types() if $help_arg =~ /^types?/;
  1876. App::Ack::print( <<"END_OF_HELP" );
  1877. Usage: ack [OPTION]... PATTERN [FILES OR DIRECTORIES]
  1878. Search for PATTERN in each source file in the tree from the current
  1879. directory on down. If any files or directories are specified, then
  1880. only those files and directories are checked. ack may also search
  1881. STDIN, but only if no file or directory arguments are specified,
  1882. or if one of them is "-".
  1883. Default switches may be specified in ACK_OPTIONS environment variable or
  1884. an .ackrc file. If you want no dependency on the environment, turn it
  1885. off with --noenv.
  1886. Example: ack -i select
  1887. Searching:
  1888. -i, --ignore-case Ignore case distinctions in PATTERN
  1889. --[no]smart-case Ignore case distinctions in PATTERN,
  1890. only if PATTERN contains no upper case.
  1891. Ignored if -i is specified
  1892. -v, --invert-match Invert match: select non-matching lines
  1893. -w, --word-regexp Force PATTERN to match only whole words
  1894. -Q, --literal Quote all metacharacters; PATTERN is literal
  1895. Search output:
  1896. --lines=NUM Only print line(s) NUM of each file
  1897. -l, --files-with-matches Only print filenames containing matches
  1898. -L, --files-without-matches Only print filenames with no matches
  1899. --output=expr Output the evaluation of expr for each line
  1900. (turns off text highlighting)
  1901. -o Show only the part of a line matching PATTERN
  1902. Same as --output='\$&'
  1903. --passthru Print all lines, whether matching or not
  1904. --match PATTERN Specify PATTERN explicitly.
  1905. -m, --max-count=NUM Stop searching in each file after NUM matches
  1906. -1 Stop searching after one match of any kind
  1907. -H, --with-filename Print the filename for each match (default:
  1908. on unless explicitly searching a single file)
  1909. -h, --no-filename Suppress the prefixing filename on output
  1910. -c, --count Show number of lines matching per file
  1911. --[no]column Show the column number of the first match
  1912. -A NUM, --after-context=NUM Print NUM lines of trailing context after
  1913. matching lines.
  1914. -B NUM, --before-context=NUM Print NUM lines of leading context before
  1915. matching lines.
  1916. -C [NUM], --context[=NUM] Print NUM lines (default 2) of output context.
  1917. --print0 Print null byte as separator between filenames,
  1918. only works with -f, -g, -l, -L or -c.
  1919. -s Suppress error messages about nonexistent or
  1920. unreadable files.
  1921. File presentation:
  1922. --pager=COMMAND Pipes all ack output through COMMAND. For
  1923. example, --pager="less -R". Ignored if output
  1924. is redirected.
  1925. --nopager Do not send output through a pager. Cancels
  1926. any setting in ~/.ackrc, ACK_PAGER or
  1927. ACK_PAGER_COLOR.
  1928. --[no]heading Print a filename heading above each file's
  1929. results. (default: on when used interactively)
  1930. --[no]break Print a break between results from different
  1931. files. (default: on when used interactively)
  1932. --group Same as --heading --break
  1933. --nogroup Same as --noheading --nobreak
  1934. --[no]color Highlight the matching text (default: on unless
  1935. output is redirected, or on Windows)
  1936. --[no]colour Same as --[no]color
  1937. --color-filename=COLOR
  1938. --color-match=COLOR
  1939. --color-lineno=COLOR Set the color for filenames, matches, and line
  1940. numbers.
  1941. --flush Flush output immediately, even when ack is used
  1942. non-interactively (when output goes to a pipe or
  1943. file).
  1944. File finding:
  1945. -f Only print the files selected, without
  1946. searching. The PATTERN must not be specified.
  1947. -g Same as -f, but only select files matching
  1948. PATTERN.
  1949. --sort-files Sort the found files lexically.
  1950. --show-types Show which types each file has.
  1951. --files-from=FILE Read the list of files to search from FILE.
  1952. -x Read the list of files to search from STDIN.
  1953. File inclusion/exclusion:
  1954. --[no]ignore-dir=name Add/remove directory from list of ignored dirs
  1955. --[no]ignore-directory=name Synonym for ignore-dir
  1956. --ignore-file=filter Add filter for ignoring files
  1957. -r, -R, --recurse Recurse into subdirectories (default: on)
  1958. -n, --no-recurse No descending into subdirectories
  1959. --[no]follow Follow symlinks. Default is off.
  1960. -k, --known-types Include only files of types that ack recognizes.
  1961. --type=X Include only X files, where X is a recognized
  1962. filetype.
  1963. --type=noX Exclude X files.
  1964. See "ack --help-types" for supported filetypes.
  1965. File type specification:
  1966. --type-set TYPE:FILTER:FILTERARGS
  1967. Files with the given FILTERARGS applied to the
  1968. given FILTER are recognized as being of type
  1969. TYPE. This replaces an existing definition for
  1970. type TYPE.
  1971. --type-add TYPE:FILTER:FILTERARGS
  1972. Files with the given FILTERARGS applied to the
  1973. given FILTER are recognized as being type TYPE.
  1974. --type-del TYPE Removes all filters associated with TYPE.
  1975. Miscellaneous:
  1976. --[no]env Ignore environment variables and global ackrc
  1977. files. --env is legal but redundant.
  1978. --ackrc=filename Specify an ackrc file to use
  1979. --ignore-ack-defaults Ignore default definitions included with ack.
  1980. --create-ackrc Outputs a default ackrc for your customization
  1981. to standard output.
  1982. --help, -? This help
  1983. --help-types Display all known types
  1984. --dump Dump information on which options are loaded
  1985. from which RC files
  1986. --[no]filter Force ack to treat standard input as a pipe
  1987. (--filter) or tty (--nofilter)
  1988. --man Man page
  1989. --version Display version & copyright
  1990. --thpppt Bill the Cat
  1991. --bar The warning admiral
  1992. --cathy Chocolate! Chocolate! Chocolate!
  1993. Exit status is 0 if match, 1 if no match.
  1994. ack's home page is at http://beyondgrep.com/
  1995. The full ack manual is available by running "ack --man".
  1996. This is version $VERSION of ack. Run "ack --version" for full version info.
  1997. END_OF_HELP
  1998. return;
  1999. }
  2000. sub show_help_types {
  2001. App::Ack::print( <<'END_OF_HELP' );
  2002. Usage: ack [OPTION]... PATTERN [FILES OR DIRECTORIES]
  2003. The following is the list of filetypes supported by ack. You can
  2004. specify a file type with the --type=TYPE format, or the --TYPE
  2005. format. For example, both --type=perl and --perl work.
  2006. Note that some extensions may appear in multiple types. For example,
  2007. .pod files are both Perl and Parrot.
  2008. END_OF_HELP
  2009. my @types = filetypes_supported();
  2010. my $maxlen = 0;
  2011. for ( @types ) {
  2012. $maxlen = length if $maxlen < length;
  2013. }
  2014. for my $type ( sort @types ) {
  2015. next if $type =~ /^-/; # Stuff to not show
  2016. my $ext_list = $mappings{$type};
  2017. if ( ref $ext_list ) {
  2018. $ext_list = join( '; ', map { $_->to_string } @{$ext_list} );
  2019. }
  2020. App::Ack::print( sprintf( " --[no]%-*.*s %s\n", $maxlen, $maxlen, $type, $ext_list ) );
  2021. }
  2022. return;
  2023. }
  2024. sub show_man {
  2025. require Pod::Usage;
  2026. Pod::Usage::pod2usage({
  2027. -input => $App::Ack::orig_program_name,
  2028. -verbose => 2,
  2029. -exitval => 0,
  2030. });
  2031. return;
  2032. }
  2033. sub get_version_statement {
  2034. require Config;
  2035. my $copyright = get_copyright();
  2036. my $this_perl = $Config::Config{perlpath};
  2037. if ($^O ne 'VMS') {
  2038. my $ext = $Config::Config{_exe};
  2039. $this_perl .= $ext unless $this_perl =~ m/$ext$/i;
  2040. }
  2041. my $ver = sprintf( '%vd', $^V );
  2042. return <<"END_OF_VERSION";
  2043. ack ${VERSION}
  2044. Running under Perl $ver at $this_perl
  2045. $copyright
  2046. This program is free software. You may modify or distribute it
  2047. under the terms of the Artistic License v2.0.
  2048. END_OF_VERSION
  2049. }
  2050. sub print_version_statement {
  2051. App::Ack::print( get_version_statement() );
  2052. return;
  2053. }
  2054. sub get_copyright {
  2055. return $COPYRIGHT;
  2056. }
  2057. # print*() subs added in order to make it easy for a third party
  2058. # module (such as App::Wack) to redefine the display methods
  2059. # and show the results in a different way.
  2060. sub print { print {$fh} @_; return; }
  2061. sub print_first_filename { App::Ack::print( $_[0], "\n" ); return; }
  2062. sub print_blank_line { App::Ack::print( "\n" ); return; }
  2063. sub print_separator { App::Ack::print( "--\n" ); return; }
  2064. sub print_filename { App::Ack::print( $_[0], $_[1] ); return; }
  2065. sub print_line_no { App::Ack::print( $_[0], $_[1] ); return; }
  2066. sub print_column_no { App::Ack::print( $_[0], $_[1] ); return; }
  2067. sub print_count {
  2068. my $filename = shift;
  2069. my $nmatches = shift;
  2070. my $ors = shift;
  2071. my $count = shift;
  2072. my $show_filename = shift;
  2073. if ($show_filename) {
  2074. App::Ack::print( $filename );
  2075. App::Ack::print( ':', $nmatches ) if $count;
  2076. }
  2077. else {
  2078. App::Ack::print( $nmatches ) if $count;
  2079. }
  2080. App::Ack::print( $ors );
  2081. return;
  2082. }
  2083. sub print_count0 {
  2084. my $filename = shift;
  2085. my $ors = shift;
  2086. my $show_filename = shift;
  2087. if ($show_filename) {
  2088. App::Ack::print( $filename, ':0', $ors );
  2089. }
  2090. else {
  2091. App::Ack::print( '0', $ors );
  2092. }
  2093. return;
  2094. }
  2095. sub set_up_pager {
  2096. my $command = shift;
  2097. return if App::Ack::output_to_pipe();
  2098. my $pager;
  2099. if ( not open( $pager, '|-', $command ) ) {
  2100. App::Ack::die( qq{Unable to pipe to pager "$command": $!} );
  2101. }
  2102. $fh = $pager;
  2103. return;
  2104. }
  2105. sub output_to_pipe {
  2106. return $output_to_pipe;
  2107. }
  2108. sub exit_from_ack {
  2109. my $nmatches = shift;
  2110. my $rc = $nmatches ? 0 : 1;
  2111. exit $rc;
  2112. }
  2113. 1; # End of App::Ack
  2114. package App::Ack::Resource;
  2115. use warnings;
  2116. use strict;
  2117. use overload
  2118. '""' => 'name';
  2119. sub FAIL {
  2120. require Carp;
  2121. Carp::confess( 'Must be overloaded' );
  2122. }
  2123. sub new {
  2124. return FAIL();
  2125. }
  2126. sub name {
  2127. return FAIL();
  2128. }
  2129. sub is_binary {
  2130. return FAIL();
  2131. }
  2132. sub open {
  2133. return FAIL();
  2134. }
  2135. sub needs_line_scan {
  2136. return FAIL();
  2137. }
  2138. sub reset {
  2139. return FAIL();
  2140. }
  2141. sub close {
  2142. return FAIL();
  2143. }
  2144. sub clone {
  2145. return FAIL();
  2146. }
  2147. sub firstliney {
  2148. return FAIL();
  2149. }
  2150. 1;
  2151. package App::Ack::Resources;
  2152. use warnings;
  2153. use strict;
  2154. sub _generate_error_handler {
  2155. my $opt = shift;
  2156. if ( $opt->{dont_report_bad_filenames} ) {
  2157. return sub {
  2158. my $msg = shift;
  2159. # XXX restricting to specific error messages for now; I would
  2160. # prefer a different way of doing this
  2161. if ( $msg =~ /Permission denied/ ) {
  2162. return;
  2163. }
  2164. App::Ack::warn( $msg );
  2165. };
  2166. }
  2167. else {
  2168. return sub {
  2169. my $msg = shift;
  2170. App::Ack::warn( $msg );
  2171. };
  2172. }
  2173. }
  2174. sub from_argv {
  2175. my $class = shift;
  2176. my $opt = shift;
  2177. my $start = shift;
  2178. my $self = bless {}, $class;
  2179. my $file_filter = undef;
  2180. my $descend_filter = $opt->{descend_filter};
  2181. if( $opt->{n} ) {
  2182. $descend_filter = sub {
  2183. return 0;
  2184. };
  2185. }
  2186. $self->{iter} =
  2187. File::Next::files( {
  2188. file_filter => $opt->{file_filter},
  2189. descend_filter => $descend_filter,
  2190. error_handler => _generate_error_handler($opt),
  2191. warning_handler => sub {},
  2192. sort_files => $opt->{sort_files},
  2193. follow_symlinks => $opt->{follow},
  2194. }, @{$start} );
  2195. return $self;
  2196. }
  2197. sub from_file {
  2198. my $class = shift;
  2199. my $opt = shift;
  2200. my $file = shift;
  2201. my $iter =
  2202. File::Next::from_file( {
  2203. error_handler => _generate_error_handler($opt),
  2204. warning_handler => _generate_error_handler($opt),
  2205. sort_files => $opt->{sort_files},
  2206. }, $file ) or return undef;
  2207. return bless {
  2208. iter => $iter,
  2209. }, $class;
  2210. }
  2211. # This is for reading input lines from STDIN, not the list of files from STDIN
  2212. sub from_stdin {
  2213. my $class = shift;
  2214. my $opt = shift;
  2215. my $self = bless {}, $class;
  2216. my $has_been_called = 0;
  2217. $self->{iter} = sub {
  2218. if ( !$has_been_called ) {
  2219. $has_been_called = 1;
  2220. return '-';
  2221. }
  2222. return;
  2223. };
  2224. return $self;
  2225. }
  2226. sub next {
  2227. my $self = shift;
  2228. my $file = $self->{iter}->() or return;
  2229. return App::Ack::Resource::Basic->new( $file );
  2230. }
  2231. 1;
  2232. package App::Ack::Resource::Basic;
  2233. use warnings;
  2234. use strict;
  2235. use Fcntl ();
  2236. BEGIN {
  2237. our @ISA = 'App::Ack::Resource';
  2238. }
  2239. sub new {
  2240. my $class = shift;
  2241. my $filename = shift;
  2242. my $self = bless {
  2243. filename => $filename,
  2244. fh => undef,
  2245. opened => 0,
  2246. }, $class;
  2247. if ( $self->{filename} eq '-' ) {
  2248. $self->{fh} = *STDIN;
  2249. $self->{opened} = 1;
  2250. }
  2251. return $self;
  2252. }
  2253. sub name {
  2254. return $_[0]->{filename};
  2255. }
  2256. sub needs_line_scan {
  2257. my $self = shift;
  2258. my $opt = shift;
  2259. return 1 if $opt->{v};
  2260. my $size = -s $self->{fh};
  2261. if ( $size == 0 ) {
  2262. return 0;
  2263. }
  2264. elsif ( $size > 100_000 ) {
  2265. return 1;
  2266. }
  2267. my $buffer;
  2268. my $rc = sysread( $self->{fh}, $buffer, $size );
  2269. if ( !defined($rc) && $App::Ack::report_bad_filenames ) {
  2270. App::Ack::warn( "$self->{filename}: $!" );
  2271. return 1;
  2272. }
  2273. return 0 unless $rc && ( $rc == $size );
  2274. my $regex = $opt->{regex};
  2275. return $buffer =~ /$regex/m;
  2276. }
  2277. sub reset {
  2278. my $self = shift;
  2279. # return if we haven't opened the file yet
  2280. if ( !defined($self->{fh}) ) {
  2281. return;
  2282. }
  2283. if( !seek( $self->{fh}, 0, 0 ) && $App::Ack::report_bad_filenames ) {
  2284. App::Ack::warn( "$self->{filename}: $!" );
  2285. }
  2286. return;
  2287. }
  2288. sub close {
  2289. my $self = shift;
  2290. # return if we haven't opened the file yet
  2291. if ( !defined($self->{fh}) ) {
  2292. return;
  2293. }
  2294. if ( !close($self->{fh}) && $App::Ack::report_bad_filenames ) {
  2295. App::Ack::warn( $self->name() . ": $!" );
  2296. }
  2297. $self->{opened} = 0;
  2298. return;
  2299. }
  2300. sub clone {
  2301. my ( $self ) = @_;
  2302. return __PACKAGE__->new($self->name);
  2303. }
  2304. sub firstliney {
  2305. my ( $self ) = @_;
  2306. my $fh = $self->open();
  2307. if ( !exists $self->{firstliney} ) {
  2308. my $buffer = '';
  2309. my $rc = sysread( $fh, $buffer, 250 );
  2310. unless($rc) { # XXX handle this better?
  2311. $buffer = '';
  2312. }
  2313. $buffer =~ s/[\r\n].*//s;
  2314. $self->{firstliney} = $buffer;
  2315. $self->reset;
  2316. }
  2317. $self->close;
  2318. return $self->{firstliney};
  2319. }
  2320. sub open {
  2321. my ( $self ) = @_;
  2322. return $self->{fh} if $self->{opened};
  2323. if ( ! open $self->{fh}, '<', $self->{filename} ) {
  2324. return;
  2325. }
  2326. $self->{opened} = 1;
  2327. return $self->{fh};
  2328. }
  2329. 1;
  2330. package App::Ack::ConfigDefault;
  2331. use warnings;
  2332. use strict;
  2333. sub options {
  2334. return split( /\n/, _options_block() );
  2335. }
  2336. sub options_clean {
  2337. return grep { /./ && !/^#/ } options();
  2338. }
  2339. sub _options_block {
  2340. my $lines = <<'HERE';
  2341. # This is the default ackrc for ack version ==VERSION==.
  2342. # There are four different ways to match
  2343. #
  2344. # is: Match the filename exactly
  2345. #
  2346. # ext: Match the extension of the filename exactly
  2347. #
  2348. # match: Match the filename against a Perl regular expression
  2349. #
  2350. # firstlinematch: Match the first 250 characters of the first line
  2351. # of text against a Perl regular expression. This is only for
  2352. # the --type-add option.
  2353. ### Directories to ignore
  2354. # Bazaar
  2355. # http://bazaar.canonical.com/
  2356. --ignore-directory=is:.bzr
  2357. # Codeville
  2358. # http://freecode.com/projects/codeville
  2359. --ignore-directory=is:.cdv
  2360. # Interface Builder (Xcode)
  2361. # http://en.wikipedia.org/wiki/Interface_Builder
  2362. --ignore-directory=is:~.dep
  2363. --ignore-directory=is:~.dot
  2364. --ignore-directory=is:~.nib
  2365. --ignore-directory=is:~.plst
  2366. # Git
  2367. # http://git-scm.com/
  2368. --ignore-directory=is:.git
  2369. # Mercurial
  2370. # http://mercurial.selenic.com/
  2371. --ignore-directory=is:.hg
  2372. # quilt
  2373. # http://directory.fsf.org/wiki/Quilt
  2374. --ignore-directory=is:.pc
  2375. # Subversion
  2376. # http://subversion.tigris.org/
  2377. --ignore-directory=is:.svn
  2378. # Monotone
  2379. # http://www.monotone.ca/
  2380. --ignore-directory=is:_MTN
  2381. # CVS
  2382. # http://savannah.nongnu.org/projects/cvs
  2383. --ignore-directory=is:CVS
  2384. # RCS
  2385. # http://www.gnu.org/software/rcs/
  2386. --ignore-directory=is:RCS
  2387. # SCCS
  2388. # http://en.wikipedia.org/wiki/Source_Code_Control_System
  2389. --ignore-directory=is:SCCS
  2390. # darcs
  2391. # http://darcs.net/
  2392. --ignore-directory=is:_darcs
  2393. # Vault/Fortress
  2394. --ignore-directory=is:_sgbak
  2395. # autoconf
  2396. # http://www.gnu.org/software/autoconf/
  2397. --ignore-directory=is:autom4te.cache
  2398. # Perl module building
  2399. --ignore-directory=is:blib
  2400. --ignore-directory=is:_build
  2401. # Perl Devel::Cover module's output directory
  2402. # https://metacpan.org/release/Devel-Cover
  2403. --ignore-directory=is:cover_db
  2404. # Node modules created by npm
  2405. --ignore-directory=is:node_modules
  2406. # CMake cache
  2407. # http://www.cmake.org/
  2408. --ignore-directory=is:CMakeFiles
  2409. # Eclipse workspace folder
  2410. # http://eclipse.org/
  2411. --ignore-directory=is:.metadata
  2412. # Cabal (Haskell) sandboxes
  2413. # http://www.haskell.org/cabal/users-guide/installing-packages.html
  2414. --ignore-directory=is:.cabal-sandbox
  2415. ### Files to ignore
  2416. # Backup files
  2417. --ignore-file=ext:bak
  2418. --ignore-file=match:/~$/
  2419. # Emacs swap files
  2420. --ignore-file=match:/^#.+#$/
  2421. # vi/vim swap files http://vim.org/
  2422. --ignore-file=match:/[._].*\.swp$/
  2423. # core dumps
  2424. --ignore-file=match:/core\.\d+$/
  2425. # minified Javascript
  2426. --ignore-file=match:/[.-]min[.]js$/
  2427. --ignore-file=match:/[.]js[.]min$/
  2428. # minified CSS
  2429. --ignore-file=match:/[.]min[.]css$/
  2430. --ignore-file=match:/[.]css[.]min$/
  2431. # JS and CSS source maps
  2432. --ignore-file=match:/[.]js[.]map$/
  2433. --ignore-file=match:/[.]css[.]map$/
  2434. # PDFs, because they pass Perl's -T detection
  2435. --ignore-file=ext:pdf
  2436. # Common graphics, just as an optimization
  2437. --ignore-file=ext:gif,jpg,jpeg,png
  2438. ### Filetypes defined
  2439. # Perl
  2440. # http://perl.org/
  2441. --type-add=perl:ext:pl,pm,pod,t,psgi
  2442. --type-add=perl:firstlinematch:/^#!.*\bperl/
  2443. # Perl tests
  2444. --type-add=perltest:ext:t
  2445. # Makefiles
  2446. # http://www.gnu.org/s/make/
  2447. --type-add=make:ext:mk
  2448. --type-add=make:ext:mak
  2449. --type-add=make:is:makefile
  2450. --type-add=make:is:Makefile
  2451. --type-add=make:is:Makefile.Debug
  2452. --type-add=make:is:Makefile.Release
  2453. # Rakefiles
  2454. # http://rake.rubyforge.org/
  2455. --type-add=rake:is:Rakefile
  2456. # CMake
  2457. # http://www.cmake.org/
  2458. --type-add=cmake:is:CMakeLists.txt
  2459. --type-add=cmake:ext:cmake
  2460. # Actionscript
  2461. --type-add=actionscript:ext:as,mxml
  2462. # Ada
  2463. # http://www.adaic.org/
  2464. --type-add=ada:ext:ada,adb,ads
  2465. # ASP
  2466. # http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2467. --type-add=asp:ext:asp
  2468. # ASP.Net
  2469. # http://www.asp.net/
  2470. --type-add=aspx:ext:master,ascx,asmx,aspx,svc
  2471. # Assembly
  2472. --type-add=asm:ext:asm,s
  2473. # Batch
  2474. --type-add=batch:ext:bat,cmd
  2475. # ColdFusion
  2476. # http://en.wikipedia.org/wiki/ColdFusion
  2477. --type-add=cfmx:ext:cfc,cfm,cfml
  2478. # Clojure
  2479. # http://clojure.org/
  2480. --type-add=clojure:ext:clj
  2481. # C
  2482. # .xs are Perl C files
  2483. --type-add=cc:ext:c,h,xs
  2484. # C header files
  2485. --type-add=hh:ext:h
  2486. # CoffeeScript
  2487. # http://coffeescript.org/
  2488. --type-add=coffeescript:ext:coffee
  2489. # C++
  2490. --type-add=cpp:ext:cpp,cc,cxx,m,hpp,hh,h,hxx
  2491. # C#
  2492. --type-add=csharp:ext:cs
  2493. # CSS
  2494. # http://www.w3.org/Style/CSS/
  2495. --type-add=css:ext:css
  2496. # Dart
  2497. # http://www.dartlang.org/
  2498. --type-add=dart:ext:dart
  2499. # Delphi
  2500. # http://en.wikipedia.org/wiki/Embarcadero_Delphi
  2501. --type-add=delphi:ext:pas,int,dfm,nfm,dof,dpk,dproj,groupproj,bdsgroup,bdsproj
  2502. # Elixir
  2503. # http://elixir-lang.org/
  2504. --type-add=elixir:ext:ex,exs
  2505. # Emacs Lisp
  2506. # http://www.gnu.org/software/emacs
  2507. --type-add=elisp:ext:el
  2508. # Erlang
  2509. # http://www.erlang.org/
  2510. --type-add=erlang:ext:erl,hrl
  2511. # Fortran
  2512. # http://en.wikipedia.org/wiki/Fortran
  2513. --type-add=fortran:ext:f,f77,f90,f95,f03,for,ftn,fpp
  2514. # Go
  2515. # http://golang.org/
  2516. --type-add=go:ext:go
  2517. # Groovy
  2518. # http://groovy.codehaus.org/
  2519. --type-add=groovy:ext:groovy,gtmpl,gpp,grunit,gradle
  2520. # Haskell
  2521. # http://www.haskell.org/
  2522. --type-add=haskell:ext:hs,lhs
  2523. # HTML
  2524. --type-add=html:ext:htm,html
  2525. # Jade
  2526. # http://jade-lang.com/
  2527. --type-add=jade:ext:jade
  2528. # Java
  2529. # http://www.oracle.com/technetwork/java/index.html
  2530. --type-add=java:ext:java,properties
  2531. # JavaScript
  2532. --type-add=js:ext:js
  2533. # JSP
  2534. # http://www.oracle.com/technetwork/java/javaee/jsp/index.html
  2535. --type-add=jsp:ext:jsp,jspx,jhtm,jhtml
  2536. # JSON
  2537. # http://www.json.org/
  2538. --type-add=json:ext:json
  2539. # Less
  2540. # http://www.lesscss.org/
  2541. --type-add=less:ext:less
  2542. # Common Lisp
  2543. # http://common-lisp.net/
  2544. --type-add=lisp:ext:lisp,lsp
  2545. # Lua
  2546. # http://www.lua.org/
  2547. --type-add=lua:ext:lua
  2548. --type-add=lua:firstlinematch:/^#!.*\blua(jit)?/
  2549. # Objective-C
  2550. --type-add=objc:ext:m,h
  2551. # Objective-C++
  2552. --type-add=objcpp:ext:mm,h
  2553. # OCaml
  2554. # http://caml.inria.fr/
  2555. --type-add=ocaml:ext:ml,mli
  2556. # Matlab
  2557. # http://en.wikipedia.org/wiki/MATLAB
  2558. --type-add=matlab:ext:m
  2559. # Parrot
  2560. # http://www.parrot.org/
  2561. --type-add=parrot:ext:pir,pasm,pmc,ops,pod,pg,tg
  2562. # PHP
  2563. # http://www.php.net/
  2564. --type-add=php:ext:php,phpt,php3,php4,php5,phtml
  2565. --type-add=php:firstlinematch:/^#!.*\bphp/
  2566. # Plone
  2567. # http://plone.org/
  2568. --type-add=plone:ext:pt,cpt,metadata,cpy,py
  2569. # Python
  2570. # http://www.python.org/
  2571. --type-add=python:ext:py
  2572. --type-add=python:firstlinematch:/^#!.*\bpython/
  2573. # R
  2574. # http://www.r-project.org/
  2575. --type-add=rr:ext:R
  2576. # reStructured Text
  2577. # http://docutils.sourceforge.net/rst.html
  2578. --type-add=rst:ext:rst
  2579. # Ruby
  2580. # http://www.ruby-lang.org/
  2581. --type-add=ruby:ext:rb,rhtml,rjs,rxml,erb,rake,spec
  2582. --type-add=ruby:is:Rakefile
  2583. --type-add=ruby:firstlinematch:/^#!.*\bruby/
  2584. # Rust
  2585. # http://www.rust-lang.org/
  2586. --type-add=rust:ext:rs
  2587. # Sass
  2588. # http://sass-lang.com
  2589. --type-add=sass:ext:sass,scss
  2590. # Scala
  2591. # http://www.scala-lang.org/
  2592. --type-add=scala:ext:scala
  2593. # Scheme
  2594. # http://groups.csail.mit.edu/mac/projects/scheme/
  2595. --type-add=scheme:ext:scm,ss
  2596. # Shell
  2597. --type-add=shell:ext:sh,bash,csh,tcsh,ksh,zsh,fish
  2598. --type-add=shell:firstlinematch:/^#!.*\b(?:ba|t?c|k|z|fi)?sh\b/
  2599. # Smalltalk
  2600. # http://www.smalltalk.org/
  2601. --type-add=smalltalk:ext:st
  2602. # Smarty
  2603. # http://www.smarty.net/
  2604. --type-add=smarty:ext:tpl
  2605. # SQL
  2606. # http://www.iso.org/iso/catalogue_detail.htm?csnumber=45498
  2607. --type-add=sql:ext:sql,ctl
  2608. # Stylus
  2609. # http://learnboost.github.io/stylus/
  2610. --type-add=stylus:ext:styl
  2611. # Tcl
  2612. # http://www.tcl.tk/
  2613. --type-add=tcl:ext:tcl,itcl,itk
  2614. # LaTeX
  2615. # http://www.latex-project.org/
  2616. --type-add=tex:ext:tex,cls,sty
  2617. # Template Toolkit (Perl)
  2618. # http://template-toolkit.org/
  2619. --type-add=tt:ext:tt,tt2,ttml
  2620. # Visual Basic
  2621. --type-add=vb:ext:bas,cls,frm,ctl,vb,resx
  2622. # Verilog
  2623. --type-add=verilog:ext:v,vh,sv
  2624. # VHDL
  2625. # http://www.eda.org/twiki/bin/view.cgi/P1076/WebHome
  2626. --type-add=vhdl:ext:vhd,vhdl
  2627. # Vim
  2628. # http://www.vim.org/
  2629. --type-add=vim:ext:vim
  2630. # XML
  2631. # http://www.w3.org/TR/REC-xml/
  2632. --type-add=xml:ext:xml,dtd,xsl,xslt,ent
  2633. --type-add=xml:firstlinematch:/<[?]xml/
  2634. # YAML
  2635. # http://yaml.org/
  2636. --type-add=yaml:ext:yaml,yml
  2637. HERE
  2638. $lines =~ s/==VERSION==/$App::Ack::VERSION/sm;
  2639. return $lines;
  2640. }
  2641. 1;
  2642. package App::Ack::ConfigFinder;
  2643. use strict;
  2644. use warnings;
  2645. use Cwd 3.00 ();
  2646. use File::Spec 3.00;
  2647. use if ($^O eq 'MSWin32'), 'Win32';
  2648. sub new {
  2649. my ( $class ) = @_;
  2650. return bless {}, $class;
  2651. }
  2652. sub _remove_redundancies {
  2653. my @configs = @_;
  2654. my %seen;
  2655. foreach my $config (@configs) {
  2656. my $key = $config->{path};
  2657. if ( not $App::Ack::is_windows ) {
  2658. # On Unix, uniquify on inode.
  2659. my ($dev, $inode) = (stat $key)[0, 1];
  2660. $key = "$dev:$inode" if defined $dev;
  2661. }
  2662. undef $config if $seen{$key}++;
  2663. }
  2664. return grep { defined } @configs;
  2665. }
  2666. sub _check_for_ackrc {
  2667. return unless defined $_[0];
  2668. my @files = grep { -f }
  2669. map { File::Spec->catfile(@_, $_) }
  2670. qw(.ackrc _ackrc);
  2671. die File::Spec->catdir(@_) . " contains both .ackrc and _ackrc.\n" .
  2672. "Please remove one of those files.\n"
  2673. if @files > 1;
  2674. return wantarray ? @files : $files[0];
  2675. } # end _check_for_ackrc
  2676. sub find_config_files {
  2677. my @config_files;
  2678. if ( $App::Ack::is_windows ) {
  2679. push @config_files, map { +{ path => File::Spec->catfile($_, 'ackrc') } } (
  2680. Win32::GetFolderPath(Win32::CSIDL_COMMON_APPDATA()),
  2681. Win32::GetFolderPath(Win32::CSIDL_APPDATA()),
  2682. );
  2683. }
  2684. else {
  2685. push @config_files, { path => '/etc/ackrc' };
  2686. }
  2687. if ( $ENV{'ACKRC'} && -f $ENV{'ACKRC'} ) {
  2688. push @config_files, { path => $ENV{'ACKRC'} };
  2689. }
  2690. else {
  2691. push @config_files, map { +{ path => $_ } } _check_for_ackrc($ENV{'HOME'});
  2692. }
  2693. # XXX This should go through some untainted cwd-fetching function, and not get untainted inline like this.
  2694. my $cwd = Cwd::getcwd();
  2695. $cwd =~ /(.+)/;
  2696. $cwd = $1;
  2697. my @dirs = File::Spec->splitdir( $cwd );
  2698. while(@dirs) {
  2699. my $ackrc = _check_for_ackrc(@dirs);
  2700. if(defined $ackrc) {
  2701. push @config_files, { project => 1, path => $ackrc };
  2702. last;
  2703. }
  2704. pop @dirs;
  2705. }
  2706. # We only test for existence here, so if the file is deleted out from under us, this will fail later.
  2707. return _remove_redundancies( @config_files );
  2708. }
  2709. sub read_rcfile {
  2710. my $file = shift;
  2711. return unless defined $file && -e $file;
  2712. my @lines;
  2713. open( my $fh, '<', $file ) or App::Ack::die( "Unable to read $file: $!" );
  2714. while ( my $line = <$fh> ) {
  2715. chomp $line;
  2716. $line =~ s/^\s+//;
  2717. $line =~ s/\s+$//;
  2718. next if $line eq '';
  2719. next if $line =~ /^\s*#/;
  2720. push( @lines, $line );
  2721. }
  2722. close $fh or App::Ack::die( "Unable to close $file: $!" );
  2723. return @lines;
  2724. }
  2725. 1;
  2726. package App::Ack::ConfigLoader;
  2727. use strict;
  2728. use warnings;
  2729. use Carp 1.04 ();
  2730. use Getopt::Long 2.35 ();
  2731. use Text::ParseWords 3.1 ();
  2732. my @INVALID_COMBINATIONS;
  2733. BEGIN {
  2734. my @context = qw( -A -B -C --after-context --before-context --context );
  2735. my @pretty = qw( --heading --group --break );
  2736. my @filename = qw( -h -H --with-filename --no-filename );
  2737. @INVALID_COMBINATIONS = (
  2738. # XXX normalize
  2739. [qw(-l)] => [@context, @pretty, @filename, qw(-L -o --passthru --output --max-count --column -f -g --show-types)],
  2740. [qw(-L)] => [@context, @pretty, @filename, qw(-l -o --passthru --output --max-count --column -f -g --show-types -c --count)],
  2741. [qw(--line)] => [@context, @pretty, @filename, qw(-l --files-with-matches --files-without-matches -L -o --passthru --match -m --max-count -1 -c --count --column --print0 -f -g --show-types)],
  2742. [qw(-o)] => [@context, qw(--output -c --count --column --column -f --show-types)],
  2743. [qw(--passthru)] => [@context, qw(--output --column -m --max-count -1 -c --count -f -g)],
  2744. [qw(--output)] => [@context, qw(-c --count -f -g)],
  2745. [qw(--match)] => [qw(-f -g)],
  2746. [qw(-m --max-count)] => [qw(-1 -f -g -c --count)],
  2747. [qw(-h --no-filename)] => [qw(-H --with-filename -f -g --group --heading)],
  2748. [qw(-H --with-filename)] => [qw(-h --no-filename -f -g)],
  2749. [qw(-c --count)] => [@context, @pretty, qw(--column -f -g)],
  2750. [qw(--column)] => [qw(-f -g)],
  2751. [@context] => [qw(-f -g)],
  2752. [qw(-f)] => [qw(-g), @pretty],
  2753. [qw(-g)] => [qw(-f), @pretty],
  2754. );
  2755. }
  2756. sub process_filter_spec {
  2757. my ( $spec ) = @_;
  2758. if ( $spec =~ /^(\w+):(\w+):(.*)/ ) {
  2759. my ( $type_name, $ext_type, $arguments ) = ( $1, $2, $3 );
  2760. return ( $type_name,
  2761. App::Ack::Filter->create_filter($ext_type, split(/,/, $arguments)) );
  2762. }
  2763. elsif ( $spec =~ /^(\w+)=(.*)/ ) { # Check to see if we have ack1-style argument specification.
  2764. my ( $type_name, $extensions ) = ( $1, $2 );
  2765. my @extensions = split(/,/, $extensions);
  2766. foreach my $extension ( @extensions ) {
  2767. $extension =~ s/^[.]//;
  2768. }
  2769. return ( $type_name, App::Ack::Filter->create_filter('ext', @extensions) );
  2770. }
  2771. else {
  2772. Carp::croak "invalid filter specification '$spec'";
  2773. }
  2774. }
  2775. sub uninvert_filter {
  2776. my ( $opt, @filters ) = @_;
  2777. return unless defined $opt->{filters} && @filters;
  2778. # Loop through all the registered filters. If we hit one that
  2779. # matches this extension and it's inverted, we need to delete it from
  2780. # the options.
  2781. for ( my $i = 0; $i < @{ $opt->{filters} }; $i++ ) {
  2782. my $opt_filter = @{ $opt->{filters} }[$i];
  2783. # XXX Do a real list comparison? This just checks string equivalence.
  2784. if ( $opt_filter->is_inverted() && "$opt_filter->{filter}" eq "@filters" ) {
  2785. splice @{ $opt->{filters} }, $i, 1;
  2786. $i--;
  2787. }
  2788. }
  2789. }
  2790. sub process_filetypes {
  2791. my ( $opt, $arg_sources ) = @_;
  2792. Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version'); # start with default options, minus some annoying ones
  2793. Getopt::Long::Configure(
  2794. 'no_ignore_case',
  2795. 'no_auto_abbrev',
  2796. 'pass_through',
  2797. );
  2798. my %additional_specs;
  2799. my $add_spec = sub {
  2800. my ( undef, $spec ) = @_;
  2801. my ( $name, $filter ) = process_filter_spec($spec);
  2802. push @{ $App::Ack::mappings{$name} }, $filter;
  2803. $additional_specs{$name . '!'} = sub {
  2804. my ( undef, $value ) = @_;
  2805. my @filters = @{ $App::Ack::mappings{$name} };
  2806. if ( not $value ) {
  2807. @filters = map { $_->invert() } @filters;
  2808. }
  2809. else {
  2810. uninvert_filter( $opt, @filters );
  2811. }
  2812. push @{ $opt->{'filters'} }, @filters;
  2813. };
  2814. };
  2815. my $set_spec = sub {
  2816. my ( undef, $spec ) = @_;
  2817. my ( $name, $filter ) = process_filter_spec($spec);
  2818. $App::Ack::mappings{$name} = [ $filter ];
  2819. $additional_specs{$name . '!'} = sub {
  2820. my ( undef, $value ) = @_;
  2821. my @filters = @{ $App::Ack::mappings{$name} };
  2822. if ( not $value ) {
  2823. @filters = map { $_->invert() } @filters;
  2824. }
  2825. push @{ $opt->{'filters'} }, @filters;
  2826. };
  2827. };
  2828. my $delete_spec = sub {
  2829. my ( undef, $name ) = @_;
  2830. delete $App::Ack::mappings{$name};
  2831. delete $additional_specs{$name . '!'};
  2832. };
  2833. my %type_arg_specs = (
  2834. 'type-add=s' => $add_spec,
  2835. 'type-set=s' => $set_spec,
  2836. 'type-del=s' => $delete_spec,
  2837. );
  2838. foreach my $source (@{$arg_sources}) {
  2839. my ( $source_name, $args ) = @{$source}{qw/name contents/};
  2840. if ( ref($args) ) {
  2841. # $args are modified in place, so no need to munge $arg_sources
  2842. local @ARGV = @{$args};
  2843. Getopt::Long::GetOptions(%type_arg_specs);
  2844. @{$args} = @ARGV;
  2845. }
  2846. else {
  2847. ( undef, $source->{contents} ) =
  2848. Getopt::Long::GetOptionsFromString($args, %type_arg_specs);
  2849. }
  2850. }
  2851. $additional_specs{'k|known-types'} = sub {
  2852. my ( undef, $value ) = @_;
  2853. my @filters = map { @{$_} } values(%App::Ack::mappings);
  2854. push @{ $opt->{'filters'} }, @filters;
  2855. };
  2856. return \%additional_specs;
  2857. }
  2858. sub removed_option {
  2859. my ( $option, $explanation ) = @_;
  2860. $explanation ||= '';
  2861. return sub {
  2862. warn "Option '$option' is not valid in ack 2\n$explanation";
  2863. exit 1;
  2864. };
  2865. }
  2866. sub get_arg_spec {
  2867. my ( $opt, $extra_specs ) = @_;
  2868. my $dash_a_explanation = <<'EOT';
  2869. This is because we now have -k/--known-types which makes it only select files
  2870. of known types, rather than any text file (which is the behavior of ack 1.x).
  2871. You may have options in a .ackrc, or in the ACKRC_OPTIONS environment variable.
  2872. Try using the --dump flag.
  2873. EOT
  2874. return {
  2875. 1 => sub { $opt->{1} = $opt->{m} = 1 },
  2876. 'A|after-context=i' => \$opt->{after_context},
  2877. 'B|before-context=i'
  2878. => \$opt->{before_context},
  2879. 'C|context:i' => sub { shift; my $val = shift; $opt->{before_context} = $opt->{after_context} = ($val || 2) },
  2880. 'a' => removed_option('-a', $dash_a_explanation),
  2881. 'all' => removed_option('--all', $dash_a_explanation),
  2882. 'break!' => \$opt->{break},
  2883. c => \$opt->{count},
  2884. 'color|colour!' => \$opt->{color},
  2885. 'color-match=s' => \$ENV{ACK_COLOR_MATCH},
  2886. 'color-filename=s' => \$ENV{ACK_COLOR_FILENAME},
  2887. 'color-lineno=s' => \$ENV{ACK_COLOR_LINENO},
  2888. 'column!' => \$opt->{column},
  2889. count => \$opt->{count},
  2890. 'create-ackrc' => sub { print "$_\n" for ( '--ignore-ack-defaults', App::Ack::ConfigDefault::options() ); exit; },
  2891. 'env!' => sub {
  2892. my ( undef, $value ) = @_;
  2893. if ( !$value ) {
  2894. $opt->{noenv_seen} = 1;
  2895. }
  2896. },
  2897. f => \$opt->{f},
  2898. 'files-from=s' => \$opt->{files_from},
  2899. 'filter!' => \$App::Ack::is_filter_mode,
  2900. flush => \$opt->{flush},
  2901. 'follow!' => \$opt->{follow},
  2902. g => \$opt->{g},
  2903. G => removed_option('-G'),
  2904. 'group!' => sub { shift; $opt->{heading} = $opt->{break} = shift },
  2905. 'heading!' => \$opt->{heading},
  2906. 'h|no-filename' => \$opt->{h},
  2907. 'H|with-filename' => \$opt->{H},
  2908. 'i|ignore-case' => \$opt->{i},
  2909. 'ignore-directory|ignore-dir=s' => sub {
  2910. my ( undef, $dir ) = @_;
  2911. $dir = App::Ack::remove_dir_sep( $dir );
  2912. if ( $dir !~ /^(?:is|match):/ ) {
  2913. $dir = 'is:' . $dir;
  2914. }
  2915. push @{ $opt->{idirs} }, $dir;
  2916. },
  2917. 'ignore-file=s' => sub {
  2918. my ( undef, $file ) = @_;
  2919. push @{ $opt->{ifiles} }, $file;
  2920. },
  2921. 'lines=s' => sub { shift; my $val = shift; push @{$opt->{lines}}, $val },
  2922. 'l|files-with-matches'
  2923. => \$opt->{l},
  2924. 'L|files-without-matches'
  2925. => \$opt->{L},
  2926. 'm|max-count=i' => \$opt->{m},
  2927. 'match=s' => \$opt->{regex},
  2928. 'n|no-recurse' => \$opt->{n},
  2929. o => sub { $opt->{output} = '$&' },
  2930. 'output=s' => \$opt->{output},
  2931. 'pager:s' => sub {
  2932. my ( undef, $value ) = @_;
  2933. $opt->{pager} = $value || $ENV{PAGER};
  2934. },
  2935. 'noignore-directory|noignore-dir=s'
  2936. => sub {
  2937. my ( undef, $dir ) = @_;
  2938. # XXX can you do --noignore-dir=match,...?
  2939. $dir = App::Ack::remove_dir_sep( $dir );
  2940. if ( $dir !~ /^(?:is|match):/ ) {
  2941. $dir = 'is:' . $dir;
  2942. }
  2943. if ( $dir !~ /^(?:is|match):/ ) {
  2944. Carp::croak("invalid noignore-directory argument: '$dir'");
  2945. }
  2946. @{ $opt->{idirs} } = grep {
  2947. $_ ne $dir
  2948. } @{ $opt->{idirs} };
  2949. push @{ $opt->{no_ignore_dirs} }, $dir;
  2950. },
  2951. 'nopager' => sub { $opt->{pager} = undef },
  2952. 'passthru' => \$opt->{passthru},
  2953. 'print0' => \$opt->{print0},
  2954. 'Q|literal' => \$opt->{Q},
  2955. 'r|R|recurse' => sub { $opt->{n} = 0 },
  2956. 's' => \$opt->{dont_report_bad_filenames},
  2957. 'show-types' => \$opt->{show_types},
  2958. 'smart-case!' => \$opt->{smart_case},
  2959. 'sort-files' => \$opt->{sort_files},
  2960. 'type=s' => sub {
  2961. my ( $getopt, $value ) = @_;
  2962. my $cb_value = 1;
  2963. if ( $value =~ s/^no// ) {
  2964. $cb_value = 0;
  2965. }
  2966. my $callback = $extra_specs->{ $value . '!' };
  2967. if ( $callback ) {
  2968. $callback->( $getopt, $cb_value );
  2969. }
  2970. else {
  2971. Carp::croak( "Unknown type '$value'" );
  2972. }
  2973. },
  2974. 'u' => removed_option('-u'),
  2975. 'unrestricted' => removed_option('--unrestricted'),
  2976. 'v|invert-match' => \$opt->{v},
  2977. 'w|word-regexp' => \$opt->{w},
  2978. 'x' => sub { $opt->{files_from} = '-' },
  2979. 'version' => sub { App::Ack::print_version_statement(); exit; },
  2980. 'help|?:s' => sub { shift; App::Ack::show_help(@_); exit; },
  2981. 'help-types' => sub { App::Ack::show_help_types(); exit; },
  2982. 'man' => sub { App::Ack::show_man(); exit; },
  2983. $extra_specs ? %{$extra_specs} : (),
  2984. }; # arg_specs
  2985. }
  2986. sub process_other {
  2987. my ( $opt, $extra_specs, $arg_sources ) = @_;
  2988. # Start with default options, minus some annoying ones.
  2989. Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
  2990. Getopt::Long::Configure(
  2991. 'bundling',
  2992. 'no_ignore_case',
  2993. );
  2994. my $argv_source;
  2995. my $is_help_types_active;
  2996. foreach my $source (@{$arg_sources}) {
  2997. my ( $source_name, $args ) = @{$source}{qw/name contents/};
  2998. if ( $source_name eq 'ARGV' ) {
  2999. $argv_source = $args;
  3000. last;
  3001. }
  3002. }
  3003. if ( $argv_source ) { # This *should* always be true, but you never know...
  3004. my @copy = @{$argv_source};
  3005. local @ARGV = @copy;
  3006. Getopt::Long::Configure('pass_through');
  3007. Getopt::Long::GetOptions(
  3008. 'help-types' => \$is_help_types_active,
  3009. );
  3010. Getopt::Long::Configure('no_pass_through');
  3011. }
  3012. my $arg_specs = get_arg_spec($opt, $extra_specs);
  3013. foreach my $source (@{$arg_sources}) {
  3014. my ( $source_name, $args ) = @{$source}{qw/name contents/};
  3015. my $args_for_source = $arg_specs;
  3016. if ( $source->{project} ) {
  3017. my $illegal = sub {
  3018. die "Options --output, --pager and --match are forbidden in project .ackrc files.\n";
  3019. };
  3020. $args_for_source = { %$args_for_source,
  3021. 'output=s' => $illegal,
  3022. 'pager:s' => $illegal,
  3023. 'match=s' => $illegal,
  3024. };
  3025. }
  3026. my $ret;
  3027. if ( ref($args) ) {
  3028. local @ARGV = @{$args};
  3029. $ret = Getopt::Long::GetOptions( %{$args_for_source} );
  3030. @{$args} = @ARGV;
  3031. }
  3032. else {
  3033. ( $ret, $source->{contents} ) =
  3034. Getopt::Long::GetOptionsFromString( $args, %{$args_for_source} );
  3035. }
  3036. if ( !$ret ) {
  3037. if ( !$is_help_types_active ) {
  3038. my $where = $source_name eq 'ARGV' ? 'on command line' : "in $source_name";
  3039. App::Ack::die( "Invalid option $where" );
  3040. }
  3041. }
  3042. if ( $opt->{noenv_seen} ) {
  3043. App::Ack::die( "--noenv found in $source_name" );
  3044. }
  3045. }
  3046. # XXX We need to check on a -- in the middle of a non-ARGV source
  3047. return;
  3048. }
  3049. sub should_dump_options {
  3050. my ( $sources ) = @_;
  3051. foreach my $source (@{$sources}) {
  3052. my ( $name, $options ) = @{$source}{qw/name contents/};
  3053. if($name eq 'ARGV') {
  3054. my $dump;
  3055. local @ARGV = @{$options};
  3056. Getopt::Long::Configure('default', 'pass_through', 'no_auto_help', 'no_auto_version');
  3057. Getopt::Long::GetOptions(
  3058. 'dump' => \$dump,
  3059. );
  3060. @{$options} = @ARGV;
  3061. return $dump;
  3062. }
  3063. }
  3064. return;
  3065. }
  3066. sub explode_sources {
  3067. my ( $sources ) = @_;
  3068. my @new_sources;
  3069. Getopt::Long::Configure('default', 'pass_through', 'no_auto_help', 'no_auto_version');
  3070. my %opt;
  3071. my $arg_spec = get_arg_spec(\%opt);
  3072. my $add_type = sub {
  3073. my ( undef, $arg ) = @_;
  3074. # XXX refactor?
  3075. if ( $arg =~ /(\w+)=/) {
  3076. $arg_spec->{$1} = sub {};
  3077. }
  3078. else {
  3079. ( $arg ) = split /:/, $arg;
  3080. $arg_spec->{$arg} = sub {};
  3081. }
  3082. };
  3083. my $del_type = sub {
  3084. my ( undef, $arg ) = @_;
  3085. delete $arg_spec->{$arg};
  3086. };
  3087. foreach my $source (@{$sources}) {
  3088. my ( $name, $options ) = @{$source}{qw/name contents/};
  3089. if ( ref($options) ne 'ARRAY' ) {
  3090. $source->{contents} = $options =
  3091. [ Text::ParseWords::shellwords($options) ];
  3092. }
  3093. for my $j ( 0 .. @{$options}-1 ) {
  3094. next unless $options->[$j] =~ /^-/;
  3095. my @chunk = ( $options->[$j] );
  3096. push @chunk, $options->[$j] while ++$j < @{$options} && $options->[$j] !~ /^-/;
  3097. $j--;
  3098. my @copy = @chunk;
  3099. local @ARGV = @chunk;
  3100. Getopt::Long::GetOptions(
  3101. 'type-add=s' => $add_type,
  3102. 'type-set=s' => $add_type,
  3103. 'type-del=s' => $del_type,
  3104. );
  3105. Getopt::Long::GetOptions( %{$arg_spec} );
  3106. push @new_sources, {
  3107. name => $name,
  3108. contents => \@copy,
  3109. };
  3110. }
  3111. }
  3112. return \@new_sources;
  3113. }
  3114. sub compare_opts {
  3115. my ( $a, $b ) = @_;
  3116. my $first_a = $a->[0];
  3117. my $first_b = $b->[0];
  3118. $first_a =~ s/^--?//;
  3119. $first_b =~ s/^--?//;
  3120. return $first_a cmp $first_b;
  3121. }
  3122. sub dump_options {
  3123. my ( $sources ) = @_;
  3124. $sources = explode_sources($sources);
  3125. my %opts_by_source;
  3126. my @source_names;
  3127. foreach my $source (@{$sources}) {
  3128. my ( $name, $contents ) = @{$source}{qw/name contents/};
  3129. if ( not $opts_by_source{$name} ) {
  3130. $opts_by_source{$name} = [];
  3131. push @source_names, $name;
  3132. }
  3133. push @{$opts_by_source{$name}}, $contents;
  3134. }
  3135. foreach my $name (@source_names) {
  3136. my $contents = $opts_by_source{$name};
  3137. print $name, "\n";
  3138. print '=' x length($name), "\n";
  3139. print ' ', join(' ', @{$_}), "\n" foreach sort { compare_opts($a, $b) } @{$contents};
  3140. }
  3141. return;
  3142. }
  3143. sub remove_default_options_if_needed {
  3144. my ( $sources ) = @_;
  3145. my $default_index;
  3146. foreach my $index ( 0 .. $#{$sources} ) {
  3147. if ( $sources->[$index]{'name'} eq 'Defaults' ) {
  3148. $default_index = $index;
  3149. last;
  3150. }
  3151. }
  3152. return $sources unless defined $default_index;
  3153. my $should_remove = 0;
  3154. # Start with default options, minus some annoying ones.
  3155. Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
  3156. Getopt::Long::Configure(
  3157. 'no_ignore_case',
  3158. 'no_auto_abbrev',
  3159. 'pass_through',
  3160. );
  3161. foreach my $index ( $default_index + 1 .. $#{$sources} ) {
  3162. my ( $name, $args ) = @{$sources->[$index]}{qw/name contents/};
  3163. if (ref($args)) {
  3164. local @ARGV = @{$args};
  3165. Getopt::Long::GetOptions(
  3166. 'ignore-ack-defaults' => \$should_remove,
  3167. );
  3168. @{$args} = @ARGV;
  3169. }
  3170. else {
  3171. ( undef, $sources->[$index]{contents} ) = Getopt::Long::GetOptionsFromString($args,
  3172. 'ignore-ack-defaults' => \$should_remove,
  3173. );
  3174. }
  3175. }
  3176. Getopt::Long::Configure('default');
  3177. Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
  3178. return $sources unless $should_remove;
  3179. my @copy = @{$sources};
  3180. splice @copy, $default_index, 1;
  3181. return \@copy;
  3182. }
  3183. sub check_for_mutually_exclusive_options {
  3184. my ( $arg_sources ) = @_;
  3185. my %mutually_exclusive_with;
  3186. my @copy = @{$arg_sources};
  3187. for(my $i = 0; $i < @INVALID_COMBINATIONS; $i += 2) {
  3188. my ( $lhs, $rhs ) = @INVALID_COMBINATIONS[ $i, $i + 1 ];
  3189. foreach my $l_opt ( @{$lhs} ) {
  3190. foreach my $r_opt ( @{$rhs} ) {
  3191. push @{ $mutually_exclusive_with{ $l_opt } }, $r_opt;
  3192. push @{ $mutually_exclusive_with{ $r_opt } }, $l_opt;
  3193. }
  3194. }
  3195. }
  3196. while( @copy ) {
  3197. my %set_opts;
  3198. my $source = shift @copy;
  3199. my ( $source_name, $args ) = @{$source}{qw/name contents/};
  3200. $args = ref($args) ? [ @{$args} ] : [ Text::ParseWords::shellwords($args) ];
  3201. foreach my $opt ( @{$args} ) {
  3202. next unless $opt =~ /^[-+]/;
  3203. last if $opt eq '--';
  3204. if( $opt =~ /^(.*)=/ ) {
  3205. $opt = $1;
  3206. }
  3207. elsif ( $opt =~ /^(-[^-]).+/ ) {
  3208. $opt = $1;
  3209. }
  3210. $set_opts{ $opt } = 1;
  3211. my $mutex_opts = $mutually_exclusive_with{ $opt };
  3212. next unless $mutex_opts;
  3213. foreach my $mutex_opt ( @{$mutex_opts} ) {
  3214. if($set_opts{ $mutex_opt }) {
  3215. die "Options '$mutex_opt' and '$opt' are mutually exclusive\n";
  3216. }
  3217. }
  3218. }
  3219. }
  3220. }
  3221. sub process_args {
  3222. my $arg_sources = \@_;
  3223. my %opt = (
  3224. pager => $ENV{ACK_PAGER_COLOR} || $ENV{ACK_PAGER},
  3225. );
  3226. check_for_mutually_exclusive_options($arg_sources);
  3227. $arg_sources = remove_default_options_if_needed($arg_sources);
  3228. if ( should_dump_options($arg_sources) ) {
  3229. dump_options($arg_sources);
  3230. exit(0);
  3231. }
  3232. my $type_specs = process_filetypes(\%opt, $arg_sources);
  3233. process_other(\%opt, $type_specs, $arg_sources);
  3234. while ( @{$arg_sources} ) {
  3235. my $source = shift @{$arg_sources};
  3236. my ( $source_name, $args ) = @{$source}{qw/name contents/};
  3237. # All of our sources should be transformed into an array ref
  3238. if ( ref($args) ) {
  3239. if ( $source_name eq 'ARGV' ) {
  3240. @ARGV = @{$args};
  3241. }
  3242. elsif (@{$args}) {
  3243. Carp::croak "source '$source_name' has extra arguments!";
  3244. }
  3245. }
  3246. else {
  3247. Carp::croak 'The impossible has occurred!';
  3248. }
  3249. }
  3250. my $filters = ($opt{filters} ||= []);
  3251. # Throw the default filter in if no others are selected.
  3252. if ( not grep { !$_->is_inverted() } @{$filters} ) {
  3253. push @{$filters}, App::Ack::Filter::Default->new();
  3254. }
  3255. return \%opt;
  3256. }
  3257. sub retrieve_arg_sources {
  3258. my @arg_sources;
  3259. my $noenv;
  3260. my $ackrc;
  3261. Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
  3262. Getopt::Long::Configure('pass_through');
  3263. Getopt::Long::Configure('no_auto_abbrev');
  3264. Getopt::Long::GetOptions(
  3265. 'noenv' => \$noenv,
  3266. 'ackrc=s' => \$ackrc,
  3267. );
  3268. Getopt::Long::Configure('default', 'no_auto_help', 'no_auto_version');
  3269. my @files;
  3270. if ( !$noenv ) {
  3271. my $finder = App::Ack::ConfigFinder->new;
  3272. @files = $finder->find_config_files;
  3273. }
  3274. if ( $ackrc ) {
  3275. # We explicitly use open so we get a nice error message.
  3276. # XXX This is a potential race condition!.
  3277. if(open my $fh, '<', $ackrc) {
  3278. close $fh;
  3279. }
  3280. else {
  3281. die "Unable to load ackrc '$ackrc': $!"
  3282. }
  3283. push( @files, { path => $ackrc } );
  3284. }
  3285. push @arg_sources, {
  3286. name => 'Defaults',
  3287. contents => [ App::Ack::ConfigDefault::options_clean() ],
  3288. };
  3289. foreach my $file ( @files) {
  3290. my @lines = App::Ack::ConfigFinder::read_rcfile($file->{path});
  3291. if(@lines) {
  3292. push @arg_sources, {
  3293. name => $file->{path},
  3294. contents => \@lines,
  3295. project => $file->{project},
  3296. };
  3297. }
  3298. }
  3299. if ( $ENV{ACK_OPTIONS} && !$noenv ) {
  3300. push @arg_sources, {
  3301. name => 'ACK_OPTIONS',
  3302. contents => $ENV{ACK_OPTIONS},
  3303. };
  3304. }
  3305. push @arg_sources, {
  3306. name => 'ARGV',
  3307. contents => [ @ARGV ],
  3308. };
  3309. return @arg_sources;
  3310. }
  3311. 1; # End of App::Ack::ConfigLoader
  3312. package App::Ack::Filter;
  3313. use strict;
  3314. use warnings;
  3315. use overload
  3316. '""' => 'to_string';
  3317. use Carp 1.04 ();
  3318. my %filter_types;
  3319. sub create_filter {
  3320. my ( undef, $type, @args ) = @_;
  3321. if ( my $package = $filter_types{$type} ) {
  3322. return $package->new(@args);
  3323. }
  3324. Carp::croak "Unknown filter type '$type'";
  3325. }
  3326. sub register_filter {
  3327. my ( undef, $type, $package ) = @_;
  3328. $filter_types{$type} = $package;
  3329. return;
  3330. }
  3331. sub invert {
  3332. my ( $self ) = @_;
  3333. return App::Ack::Filter::Inverse->new( $self );
  3334. }
  3335. sub is_inverted {
  3336. return 0;
  3337. }
  3338. sub to_string {
  3339. my ( $self ) = @_;
  3340. return '(unimplemented to_string)';
  3341. }
  3342. sub inspect {
  3343. my ( $self ) = @_;
  3344. return ref($self);
  3345. }
  3346. 1;
  3347. package App::Ack::Filter::Extension;
  3348. use strict;
  3349. use warnings;
  3350. BEGIN {
  3351. our @ISA = 'App::Ack::Filter';
  3352. }
  3353. sub new {
  3354. my ( $class, @extensions ) = @_;
  3355. my $exts = join('|', map { "\Q$_\E"} @extensions);
  3356. my $re = qr/[.](?:$exts)$/i;
  3357. return bless {
  3358. extensions => \@extensions,
  3359. regex => $re,
  3360. groupname => 'ExtensionGroup',
  3361. }, $class;
  3362. }
  3363. sub create_group {
  3364. return App::Ack::Filter::ExtensionGroup->new();
  3365. }
  3366. sub filter {
  3367. my ( $self, $resource ) = @_;
  3368. my $re = $self->{'regex'};
  3369. return $resource->name =~ /$re/;
  3370. }
  3371. sub inspect {
  3372. my ( $self ) = @_;
  3373. my $re = $self->{'regex'};
  3374. return ref($self) . " - $re";
  3375. }
  3376. sub to_string {
  3377. my ( $self ) = @_;
  3378. my $exts = $self->{'extensions'};
  3379. return join(' ', map { ".$_" } @{$exts});
  3380. }
  3381. BEGIN {
  3382. App::Ack::Filter->register_filter(ext => __PACKAGE__);
  3383. }
  3384. 1;
  3385. package App::Ack::Filter::FirstLineMatch;
  3386. use strict;
  3387. use warnings;
  3388. BEGIN {
  3389. our @ISA = 'App::Ack::Filter';
  3390. }
  3391. sub new {
  3392. my ( $class, $re ) = @_;
  3393. $re =~ s{^/|/$}{}g; # XXX validate?
  3394. $re = qr{$re}i;
  3395. return bless {
  3396. regex => $re,
  3397. }, $class;
  3398. }
  3399. # This test reads the first 250 characters of a file, then just uses the
  3400. # first line found in that. This prevents reading something like an entire
  3401. # .min.js file (which might be only one "line" long) into memory.
  3402. sub filter {
  3403. my ( $self, $resource ) = @_;
  3404. my $re = $self->{'regex'};
  3405. my $line = $resource->firstliney;
  3406. return $line =~ /$re/;
  3407. }
  3408. sub inspect {
  3409. my ( $self ) = @_;
  3410. my $re = $self->{'regex'};
  3411. return ref($self) . " - $re";
  3412. }
  3413. sub to_string {
  3414. my ( $self ) = @_;
  3415. (my $re = $self->{regex}) =~ s{\([^:]*:(.*)\)$}{$1};
  3416. return "first line matches /$re/";
  3417. }
  3418. BEGIN {
  3419. App::Ack::Filter->register_filter(firstlinematch => __PACKAGE__);
  3420. }
  3421. 1;
  3422. package App::Ack::Filter::Is;
  3423. use strict;
  3424. use warnings;
  3425. BEGIN {
  3426. our @ISA = 'App::Ack::Filter';
  3427. }
  3428. use File::Spec 3.00 ();
  3429. sub new {
  3430. my ( $class, $filename ) = @_;
  3431. return bless {
  3432. filename => $filename,
  3433. groupname => 'IsGroup',
  3434. }, $class;
  3435. }
  3436. sub create_group {
  3437. return App::Ack::Filter::IsGroup->new();
  3438. }
  3439. sub filter {
  3440. my ( $self, $resource ) = @_;
  3441. my $filename = $self->{'filename'};
  3442. my $base = (File::Spec->splitpath($resource->name))[2];
  3443. return $base eq $filename;
  3444. }
  3445. sub inspect {
  3446. my ( $self ) = @_;
  3447. my $filename = $self->{'filename'};
  3448. return ref($self) . " - $filename";
  3449. }
  3450. sub to_string {
  3451. my ( $self ) = @_;
  3452. my $filename = $self->{'filename'};
  3453. return $filename;
  3454. }
  3455. BEGIN {
  3456. App::Ack::Filter->register_filter(is => __PACKAGE__);
  3457. }
  3458. 1;
  3459. package App::Ack::Filter::Match;
  3460. use strict;
  3461. use warnings;
  3462. BEGIN {
  3463. our @ISA = 'App::Ack::Filter';
  3464. }
  3465. use File::Spec 3.00;
  3466. sub new {
  3467. my ( $class, $re ) = @_;
  3468. $re =~ s{^/|/$}{}g; # XXX validate?
  3469. $re = qr/$re/i;
  3470. return bless {
  3471. regex => $re,
  3472. }, $class;
  3473. }
  3474. sub filter {
  3475. my ( $self, $resource ) = @_;
  3476. my $re = $self->{'regex'};
  3477. my $base = (File::Spec->splitpath($resource->name))[2];
  3478. return $base =~ /$re/;
  3479. }
  3480. sub inspect {
  3481. my ( $self ) = @_;
  3482. my $re = $self->{'regex'};
  3483. print ref($self) . " - $re";
  3484. return;
  3485. }
  3486. sub to_string {
  3487. my ( $self ) = @_;
  3488. my $re = $self->{'regex'};
  3489. return "filename matches $re";
  3490. }
  3491. BEGIN {
  3492. App::Ack::Filter->register_filter(match => __PACKAGE__);
  3493. }
  3494. 1;
  3495. package App::Ack::Filter::Default;
  3496. use strict;
  3497. use warnings;
  3498. BEGIN {
  3499. our @ISA = 'App::Ack::Filter';
  3500. }
  3501. sub new {
  3502. my ( $class ) = @_;
  3503. return bless {}, $class;
  3504. }
  3505. sub filter {
  3506. my ( $self, $resource ) = @_;
  3507. return -T $resource->name;
  3508. }
  3509. 1;
  3510. package App::Ack::Filter::Inverse;
  3511. use strict;
  3512. use warnings;
  3513. BEGIN {
  3514. our @ISA = 'App::Ack::Filter';
  3515. }
  3516. sub new {
  3517. my ( $class, $filter ) = @_;
  3518. return bless {
  3519. filter => $filter,
  3520. }, $class;
  3521. }
  3522. sub filter {
  3523. my ( $self, $resource ) = @_;
  3524. my $filter = $self->{'filter'};
  3525. return !$filter->filter( $resource );
  3526. }
  3527. sub invert {
  3528. my $self = shift;
  3529. return $self->{'filter'};
  3530. }
  3531. sub is_inverted {
  3532. return 1;
  3533. }
  3534. sub inspect {
  3535. my ( $self ) = @_;
  3536. my $filter = $self->{'filter'};
  3537. return "!$filter";
  3538. }
  3539. 1;
  3540. package App::Ack::Filter::Collection;
  3541. use strict;
  3542. use warnings;
  3543. BEGIN {
  3544. our @ISA = 'App::Ack::Filter';
  3545. }
  3546. sub new {
  3547. my ( $class ) = @_;
  3548. return bless {
  3549. groups => {},
  3550. ungrouped => [],
  3551. }, $class;
  3552. }
  3553. sub filter {
  3554. my ( $self, $resource ) = @_;
  3555. for my $group (values %{$self->{'groups'}}) {
  3556. if ($group->filter($resource)) {
  3557. return 1;
  3558. }
  3559. }
  3560. for my $filter (@{$self->{'ungrouped'}}) {
  3561. if ($filter->filter($resource)) {
  3562. return 1;
  3563. }
  3564. }
  3565. return 0;
  3566. }
  3567. sub add {
  3568. my ( $self, $filter ) = @_;
  3569. if (exists $filter->{'groupname'}) {
  3570. my $group = ($self->{groups}->{$filter->{groupname}} ||= $filter->create_group());
  3571. $group->add($filter);
  3572. }
  3573. else {
  3574. push @{$self->{'ungrouped'}}, $filter;
  3575. }
  3576. return;
  3577. }
  3578. sub inspect {
  3579. my ( $self ) = @_;
  3580. return ref($self) . " - $self";
  3581. }
  3582. sub to_string {
  3583. my ( $self ) = @_;
  3584. my $ungrouped = $self->{'ungrouped'};
  3585. return join(', ', map { "($_)" } @{$ungrouped});
  3586. }
  3587. 1;
  3588. package App::Ack::Filter::IsGroup;
  3589. use strict;
  3590. use warnings;
  3591. BEGIN {
  3592. our @ISA = 'App::Ack::Filter';
  3593. }
  3594. use File::Spec 3.00 ();
  3595. sub new {
  3596. my ( $class ) = @_;
  3597. return bless {
  3598. data => {},
  3599. }, $class;
  3600. }
  3601. sub add {
  3602. my ( $self, $filter ) = @_;
  3603. $self->{data}->{ $filter->{filename} } = 1;
  3604. return;
  3605. }
  3606. sub filter {
  3607. my ( $self, $resource ) = @_;
  3608. my $data = $self->{'data'};
  3609. my $base = (File::Spec->splitpath($resource->name))[2];
  3610. return exists $data->{$base};
  3611. }
  3612. sub inspect {
  3613. my ( $self ) = @_;
  3614. return ref($self) . " - $self";
  3615. }
  3616. sub to_string {
  3617. my ( $self ) = @_;
  3618. return join(' ', keys %{$self->{data}});
  3619. }
  3620. 1;
  3621. package App::Ack::Filter::ExtensionGroup;
  3622. use strict;
  3623. use warnings;
  3624. BEGIN {
  3625. our @ISA = 'App::Ack::Filter';
  3626. }
  3627. sub new {
  3628. my ( $class ) = @_;
  3629. return bless {
  3630. data => {},
  3631. }, $class;
  3632. }
  3633. sub add {
  3634. my ( $self, $filter ) = @_;
  3635. foreach my $ext (@{$filter->{extensions}}) {
  3636. $self->{data}->{lc $ext} = 1;
  3637. }
  3638. return;
  3639. }
  3640. sub filter {
  3641. my ( $self, $resource ) = @_;
  3642. if ($resource->name =~ /[.]([^.]*)$/) {
  3643. return exists $self->{'data'}->{lc $1};
  3644. }
  3645. return 0;
  3646. }
  3647. sub inspect {
  3648. my ( $self ) = @_;
  3649. return ref($self) . " - $self";
  3650. }
  3651. sub to_string {
  3652. my ( $self ) = @_;
  3653. return join(' ', map { ".$_" } sort keys %{$self->{data}});
  3654. }
  3655. 1;
  3656. package File::Next;
  3657. use strict;
  3658. use warnings;
  3659. our $VERSION = '1.12';
  3660. use File::Spec ();
  3661. our $name; # name of the current file
  3662. our $dir; # dir of the current file
  3663. our %files_defaults;
  3664. our %skip_dirs;
  3665. BEGIN {
  3666. %files_defaults = (
  3667. file_filter => undef,
  3668. descend_filter => undef,
  3669. error_handler => sub { CORE::die @_ },
  3670. warning_handler => sub { CORE::warn @_ },
  3671. sort_files => undef,
  3672. follow_symlinks => 1,
  3673. nul_separated => 0,
  3674. );
  3675. %skip_dirs = map {($_,1)} (File::Spec->curdir, File::Spec->updir);
  3676. }
  3677. sub files {
  3678. die _bad_invocation() if @_ && defined($_[0]) && ($_[0] eq __PACKAGE__);
  3679. my ($parms,@queue) = _setup( \%files_defaults, @_ );
  3680. my $filter = $parms->{file_filter};
  3681. return sub {
  3682. while (@queue) {
  3683. my ($dirname,$file,$fullpath) = splice( @queue, 0, 3 );
  3684. if ( -f $fullpath || -p $fullpath || $fullpath =~ m{^/dev/fd} ) {
  3685. if ( $filter ) {
  3686. local $_ = $file;
  3687. local $File::Next::dir = $dirname;
  3688. local $File::Next::name = $fullpath;
  3689. next if not $filter->();
  3690. }
  3691. return wantarray ? ($dirname,$file,$fullpath) : $fullpath;
  3692. }
  3693. elsif ( -d _ ) {
  3694. unshift( @queue, _candidate_files( $parms, $fullpath ) );
  3695. }
  3696. } # while
  3697. return;
  3698. }; # iterator
  3699. }
  3700. sub from_file {
  3701. die _bad_invocation() if @_ && defined($_[0]) && ($_[0] eq __PACKAGE__);
  3702. my ($parms,@queue) = _setup( \%files_defaults, @_ );
  3703. my $err = $parms->{error_handler};
  3704. my $warn = $parms->{error_handler};
  3705. my $filename = $queue[1];
  3706. if ( !defined($filename) ) {
  3707. $err->( 'Must pass a filename to from_file()' );
  3708. return undef;
  3709. }
  3710. my $fh;
  3711. if ( $filename eq '-' ) {
  3712. $fh = \*STDIN;
  3713. }
  3714. else {
  3715. if ( !open( $fh, '<', $filename ) ) {
  3716. $err->( "Unable to open $filename: $!" );
  3717. return undef;
  3718. }
  3719. }
  3720. my $filter = $parms->{file_filter};
  3721. return sub {
  3722. local $/ = $parms->{nul_separated} ? "\x00" : $/;
  3723. while ( my $fullpath = <$fh> ) {
  3724. chomp $fullpath;
  3725. next unless $fullpath =~ /./;
  3726. if ( not ( -f $fullpath || -p _ ) ) {
  3727. $warn->( "$fullpath: No such file" );
  3728. next;
  3729. }
  3730. my ($volume,$dirname,$file) = File::Spec->splitpath( $fullpath );
  3731. if ( $filter ) {
  3732. local $_ = $file;
  3733. local $File::Next::dir = $dirname;
  3734. local $File::Next::name = $fullpath;
  3735. next if not $filter->();
  3736. }
  3737. return wantarray ? ($dirname,$file,$fullpath) : $fullpath;
  3738. } # while
  3739. close $fh;
  3740. return;
  3741. }; # iterator
  3742. }
  3743. sub _bad_invocation {
  3744. my $good = (caller(1))[3];
  3745. my $bad = $good;
  3746. $bad =~ s/(.+)::/$1->/;
  3747. return "$good must not be invoked as $bad";
  3748. }
  3749. sub sort_standard($$) { return $_[0]->[1] cmp $_[1]->[1] }
  3750. sub sort_reverse($$) { return $_[1]->[1] cmp $_[0]->[1] }
  3751. sub reslash {
  3752. my $path = shift;
  3753. my @parts = split( /\//, $path );
  3754. return $path if @parts < 2;
  3755. return File::Spec->catfile( @parts );
  3756. }
  3757. sub _setup {
  3758. my $defaults = shift;
  3759. my $passed_parms = ref $_[0] eq 'HASH' ? {%{+shift}} : {}; # copy parm hash
  3760. my %passed_parms = %{$passed_parms};
  3761. my $parms = {};
  3762. for my $key ( keys %{$defaults} ) {
  3763. $parms->{$key} =
  3764. exists $passed_parms{$key}
  3765. ? delete $passed_parms{$key}
  3766. : $defaults->{$key};
  3767. }
  3768. # Any leftover keys are bogus
  3769. for my $badkey ( keys %passed_parms ) {
  3770. my $sub = (caller(1))[3];
  3771. $parms->{error_handler}->( "Invalid option passed to $sub(): $badkey" );
  3772. }
  3773. # If it's not a code ref, assume standard sort
  3774. if ( $parms->{sort_files} && ( ref($parms->{sort_files}) ne 'CODE' ) ) {
  3775. $parms->{sort_files} = \&sort_standard;
  3776. }
  3777. my @queue;
  3778. for ( @_ ) {
  3779. my $start = reslash( $_ );
  3780. if (-d $start) {
  3781. push @queue, ($start,undef,$start);
  3782. }
  3783. else {
  3784. push @queue, (undef,$start,$start);
  3785. }
  3786. }
  3787. return ($parms,@queue);
  3788. }
  3789. sub _candidate_files {
  3790. my $parms = shift;
  3791. my $dirname = shift;
  3792. my $dh;
  3793. if ( !opendir $dh, $dirname ) {
  3794. $parms->{error_handler}->( "$dirname: $!" );
  3795. return;
  3796. }
  3797. my @newfiles;
  3798. my $descend_filter = $parms->{descend_filter};
  3799. my $follow_symlinks = $parms->{follow_symlinks};
  3800. my $sort_sub = $parms->{sort_files};
  3801. for my $file ( grep { !exists $skip_dirs{$_} } readdir $dh ) {
  3802. my $has_stat;
  3803. # Only do directory checking if we have a descend_filter
  3804. my $fullpath = File::Spec->catdir( $dirname, $file );
  3805. if ( !$follow_symlinks ) {
  3806. next if -l $fullpath;
  3807. $has_stat = 1;
  3808. }
  3809. if ( $descend_filter ) {
  3810. if ( $has_stat ? (-d _) : (-d $fullpath) ) {
  3811. local $File::Next::dir = $fullpath;
  3812. local $_ = $file;
  3813. next if not $descend_filter->();
  3814. }
  3815. }
  3816. if ( $sort_sub ) {
  3817. push( @newfiles, [ $dirname, $file, $fullpath ] );
  3818. }
  3819. else {
  3820. push( @newfiles, $dirname, $file, $fullpath );
  3821. }
  3822. }
  3823. closedir $dh;
  3824. if ( $sort_sub ) {
  3825. return map { @{$_} } sort $sort_sub @newfiles;
  3826. }
  3827. return @newfiles;
  3828. }
  3829. 1; # End of File::Next