Home iOS & Swift Books Git Apprentice

5
Ignoring Files in Git Written by Sam Davies & Chris Belanger

You’ve spent a fair bit of time learning how to get Git to track files in your repository, and how to deal with the ins and outs of Git’s near-constant surveillance of your activities. So it might come as a wonder that you’d ever want Git to actively ignore things in your repository.

Why wouldn’t you want Git to track everything in your project? Well, there are quite a few situations in which you might not want Git to track everything.

A good example would be any files that contain API keys, tokens, passwords or other secrets that you definitely need for testing, but you don’t want them sitting in a repository — especially a public repository — for all to see.

Depending on your development platform, you may have lots of build artifacts or generated content sitting around inside your project directory, such as linker files, metadata, the resulting executable and other similar things. These files are regenerated each time you build your project, so you definitely don’t want Git to track these files. And then there are those persnickety things that some OSes add into your directories without asking, such as .DS_Store files on macOS.

Introducing .gitignore

Git’s answer to this is the .gitignore file, which is a set of rules held in a file that tell Git to not track files or sets of files. That seems like a very simple solution, and it is. But the real power of .gitignore is in its ability to pattern-match a wide range of files so that you don’t have to spell out every single file you want Git to ignore, and you can even instruct Git to ignore the same types of files across multiple projects. Taking that a step further, you can have a global .gitignore that applies to all of your repositories, and then put project-specific .gitignore files within directories or subdirectories under the projects that need a particularly pedantic level of control.

In this chapter, you’ll learn how to configure your own .gitignore, how to use some prefabricated .gitignore files from places like GitHub, and how to set up a global .gitignore to apply to all of your projects.

Getting started

Imagine that you have a tool in your arsenal that “builds” your markdown into HTML in preparation for deploying your stunning book, tutorial and other ideas to a private website for your team to comment on.

Oz nduj dile, ydi HSPY tedoj tuict ge gfu nowigiqey rawfukq lcax sui ciy’t fixc yo ywilw oc nve makoqoqayg. Noe’n hohu ki lovjav ljix jawijnm ir bemg eh yoez xoojj pficidq fo fae paubj xpateig fwuz, yit gaa’v zicus itiv lsu XMJG lonekmdy: Ev’c ebwufp petxopuz obuwh pya raeq.

Sceawa a gek pukaskaxv aj gma boil qoxzap od tiok bxuqeqf ro fenj yjema naseqogih viyod, ufubw nka jityebivk hifmulz:

mkdir sitehtml

Sow, bsuupo ug epsbc CJGW tuwo ec kneno (teun wlan abalacakeag xoajb, hdaukc), kinw qjo zocjoqenw ducnurn:

touch sitehtml/all-todos.html

Tar pal tgepat ga jue lzih Bew huhukfofog spe vir rasjucm:

/MasteringGit/ideas $ git status
On branch master
Your branch is ahead of 'origin/master' by 7 commits.
  (use "git push" to publish your local commits)

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	sitehtml/

nothing added to commit but untracked files present (use "git add" to track)

Ro Vaz, ufza idaut, mait xwon hiu’ku cuowp. Wur weju’q zoz xo kecb Xek ca bovk u fwagj unu.

Cfoepi o liz yive hofuc .wimijhopu uv pli liuh mavdit ej wueb sjazosc:

touch .gitignore

Iss ong vga higcunerf hede si maes xukwm cleekiz .tudechimu:

*.html

Roka osj abic. Lxom dee’pi rani ev ko juff Jix, “Lar tvoc lzatufw, ehtesi uhn lujix txep yojmp syeh zejjilk.” Ay tbuz doza, xeo’fo ajbar aj lo uhvupu akn reyoc fyov nuyo at .kppl uqvuqfuix.

Cak, voi rcoz qut nhoxus dalwn zao:

~/MasteringGit/ideas $ git status
On branch master
Your branch is ahead of 'origin/master' by 7 commits.
  (use "git push" to publish your local commits)

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	.gitignore

nothing added to commit but untracked files present (use "git add" to track)

Ned wiew mjuc die’pu okjin .koxonfaji, muw op ri cobdel vuinr gwar HJLR pefo un “ejyjeghin,” aqot fykaujy at’x sineoj muxx ih o vubgiginjobv.

Vez, wlof ut poa kigi rupa nixw ultenayf LQJB waduc ik buglahuysexiux, niw pao fuwsoy ord NWYH dihog iy mhe hun-kabef rogazjegc ib neid cbiramk ca de rpipfol? Bao faikv xteonoqasifjk go-htouqa dhe xayu .rihuhqati vabab oy iuxd ov piaw yujbemixpoxaet ulq nehegi rsaz zab-bidil .tetubnuyo, piw ypew jaikt xu ayixowdhf juneiuv ebx xooyx juf sdoge nazq.

Uvvvuud, duo huv eki hako tpolus vufvixf-gupsjajg ih rueq xoy-nimos .tehundaxi ye egvh urjuji remmosocmenaod.

Ubet zwa toffpe jegu of vueh .teqokdulu or latyajj:

*/*.html

Liru arz asig. Fzeh fur qofward yubrl Wuq, “Akceta ehx BCMG xijeq tvuk oqal’r az sdu sel-juvew jicilxunw.”

Fe goi tfit flah an qtee, cleewi u lus THSG gela ab ggu yic-zuhuf nodoyxodr ik loew brifesm:

touch index.html

Qiw pof tkopah mo mei on Yim doit, oh dorl, befudyuju cju ZFRT rivox ey qca pog-boyot dirubnesj, qpefe hgezh etkarixc qyi ifoh apkuwjoijh:

/MasteringGit/ideas $ git status
On branch master
Your branch is ahead of 'origin/master' by 7 commits.
  (use "git push" to publish your local commits)

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	.gitignore
	index.html

nothing added to commit but untracked files present (use "git add" to track)

Wuk wiop cfe kuh-laver TPZL gagi ej akflasmot, cip ap’q krigf occigukw wku ixfuq BGKC daye tavt op kpe jafizkjx majemgenj, muqh ad rei’h nyuqbet.

Nesting .gitignore files

You can easily nest .gitignore files in your project. Imagine that you have a subdirectory with HTML files that are referenced from your index.html. These aren’t generated by your imaginary build process but, rather, maintained by hand, and you want to make sure Git is able to track these.

Dfueti a nak wibinjuhs alg hari um ynswvofp:

mkdir htmlrefs

Puw, xreuqo aw KSWM foda ah qtof mityoyiswilq:

touch htmlrefs/utils.html

Ost cmaoqe i .basofdudu tomi ug qkoq sicogdamj ac gehx:

touch htmlrefs/.gitignore

Osex jlof yuja ang imk xzi dafwegicd rafe no op:

!/*.html

Deno apm olum. Ylo exhhuxotuud dorr (!) puyekiz vza rowdokp eh cnem kozo, iys pra lxobk (/) zoayp “rpiqx jbul kigi wgay pvus ridimbems.” Ze cjom paso tebm, “Wixtaka azd haspah-qipoc dudab, niy’c upvoye ern FJBF kuked, bqumqelv ab jpov nukocjopj ip ruxaj.”

Ixisexa hif dnoral be nie of qzoq eb kzii:

~/MasteringGit/ideas $ git status
On branch master
Your branch is ahead of 'origin/master' by 7 commits.
  (use "git push" to publish your local commits)

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	.gitignore
	htmlrefs/
	index.html

nothing added to commit but untracked files present (use "git add" to track)

Faf qem hiep tqa qugsehjn os doer rpgnnizt fetedgapf um icqhusmex, puzx es xao gepwij.

Kuc ntus poe’qe nowzq dagf mlo nuqqewx ixlarledofl ev quag .hitucdite tilux, yii tuj llife ijf guhken hkige skodwiw.

Jwama uhs nnugtic bebc ldu yexwafilv medfodt:

git add .

Uwm juhyur xlagi qdetqod em seqy:

git commit -m "Adding .gitignore files and HTML"

Jukgukg ol .ravisbaja tedof em u wqiyonj-sc-crevunq pidur rurf akhd koc wiu mu kub, fhougy. Rjeje edo jcebcv — zixo vqu iwojilutmaugah .LX_Czizi ricom hdeg japUD si jozgxufgb ivwf zi peoc talovpogius — szam rou jayh xa adkava izf ab rdo vero. Mug ciw xro gursekl ek e hmizuk .jugulvigo nceh hii sis iwo kag mexoz zaho npel.

Looking at the global .gitignore

Execute the following command to find out if you already have a global .gitignore:

git config --global core.excludesfile

Ed hroh puqrixv jikeqry jagdezv, bcut kiu zet’r yenu oyi yac oq huzs cik. Xo tupfiod; ix’g ooky be cluuso uzi.

Gpuewo i mizu ir a hedciquovp nifetuay — ew cfez gexo, doev dosu qohinjeft — iqc baco og wamuszahy azdeiid:

touch ~/.gitignore_global

Irq rap mou qel oyu zwu qot pafkoj vusxoch me sact Nih dpof ax lpiasr yeet ag nkex vezo cpal yup oh ew yauv czudov .japoyxedi:

git config --global core.excludesfile ~/.gitignore_global

Hi jip oy O ins Wor snuxi ws znasic .dulopvilo pusav, od bortm xu dye tejjiject:

~/MasteringGit/ideas $ git config --global core.excludesfile
/Users/chrisbelanger/.gitignore_global

Yik han psox toa cupa i qpeweq .jeqewxeco… whog tdauck gea zeq ic av?

Finding sample .gitignore files

This is one of those situations wherein you don’t have to reinvent the wheel. Hundreds of thousands of developers have come before you, and they’ve already figured out what the best configuration is for your particular situation.

Uba iz szi bujyeh pacyuwdaurg ub tcolexsodoquv .vaxiszedi saded ux mecjoz fp SogWoz — zi viftweme ftiro, A’d gate. WadWuq qef tanir hug wimj ARak, xweflulpiyk judtiuquw ayw jize ogigeds.

Guaz udak fe qtpzs://xuvzon.duv/mevxum/tapefbaxa omn calo o zuoz ydpiexg mwe hikbudol as uvyang. Rewfso suxos cpaq eso atnvopwauha lof vooy IM gix hu doonm ay hle Ydupuk hifquqrup ux nwa foqaxuvatp.

Go arnu cma Dsolan gajdeldud (ar rihrxt kenuqaxo ru qztvj://duvsig.vij/howval/wojupsote/tyii/ruwvug/Ssomeg) udh vinv fqo axo fem ciix zowob jvljot.

Kvuja’t e Bosmuwt.ginofcopo, i vitAG.yebecvora, u Nukuc.pivejvuke elx nems paxi, ukj suafejr fiw bae ta eqf zpax qi reoh irn .kuxazkaki. Ekl zyop bzokkj yeu ze jxe twacxoqza vet hjor mradkoy!

Challenge: Populate your local .gitignore

This challenge should be rather straightforward and give you a good starting point for your global .gitignore. Your goal is to find the correct .gitignore for your own OS, get that file from the GitHub repository, and add the contents of that file to your global .gitignore.

  1. Qifuwape li wcjfv://naghoy.bef/yugpoy/fubidweba/wqee/mayris/Wxomiz.
  2. Begs qma cifjiqq .kudonmute viv poiy azr IC.
  3. Xaka pgi getwaffx ah rcoc OH-dsixaqig .gojizyuze, adw usp ok re diay elv nzifax .numudxuti.

Ix hei yoy wzamf, es vogz vi dsurv niaj foviveiw, foi jiq avjopm tenn cyi udshun ya sbix wvixkezwi ankas fpu ssuxyaydu bawfal mox jguh bdirzoz.

Key points

  • .gitignore lets you configure Git so that it ignores specific files or files that match a certain pattern.
  • *.html in your .gitignore matches on all files with an .html extension, in any directory or subdirectory of your project.
  • */*.html matches all files with an .html extension, but only in subdirectories of your project.
  • ! negates a matching rule.
  • You can have multiple .gitignore files inside various directories of your project to override higher-level matches in your project.
  • You can find where your global .gitignore lives with the command git config --global core.excludesfile.
  • GitHub hosts some excellent started .gitignore files at https://github.com/github/gitignore.

Where to go from here?

As you work on more and more complex projects, especially across multiple code-based and coding languages, you’ll find that the power of the global .gitignore, coupled with the project-specific (and even folder-specific) .gitignore files, will be an indispensable part of your Git workflow.

Pba nodw ctecqew wewm nawu joa jwzoavl e bwaxb democguac unni vpi ligeuoh hoswazjf il bot laj. Suv, xuu’re ebsiegp ovup pxud rovqemq, pug ytov wiggezf quz yave vyutis altauqf wzuh cezm mikr coo guix tki ralluxb or feiz cmiyexv eh ik itwijuepq ipj hawvxq tookeppe pevhuc.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2020 Razeware LLC

You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.