Home iOS & Swift Books Git Apprentice

4
The Staging Area Written by Sam Davies & Chris Belanger

In previous chapters, you’ve gained some knowledge of the staging area of Git: You’ve learned how to stage modifications to your files, stage the addition of new files to the repository, view diffs between your working tree and the staging area, and you even got a little taste of how git log works.

But there’s more to the staging area than just those few operations. At this point, you may be wondering why the staging area is necessary. “Why can’t you just push all of your current updates to the repository directly?”, you may ask. It’s a good question, but there are issues with that linear approach; Git was actually designed to solve some of the common issues with direct-commit history that exist under other version control systems.

In this chapter, you’ll learn a bit more about how the staging area of Git works, why it’s necessary, how to undo changes you’ve made to the staging area, how to move and delete files in your repository, and more.

Why staging exists

Development is a messy process. What, in theory, should be a linear, cumulative construction of functionality in code, is more often than not a series of intertwining, non-linear threads of dead-end code, partly finished features, stubbed-out tests, collections of // TODO: comments in the code, and other things that are inherent to a human-driven and largely hand-crafted process.

It’s noble to think that that you’ll work on just one feature or bug at a time; that your working tree will only ever be populated with clean, fully documented code; that you’ll never have unnecessary files cluttering up your working tree; that the configuration of your development environment will always be in perfect sync with the rest of your team; and that you won’t follow any rabbit trails (or create a few of your own) while you’re investigating a bug.

Git was built to compensate for this messy, non-linear approach to development. It’s possible to work on lots of things at once, and selectively choose what you want to stage and commit to the repository. The general philosophy is that a commit should be a logical collection of changes that make sense as a unit — not just “the latest collection of things I updated that may or may not be related.”

A simple staging example

In the example below, I’m working on a website, and I want my design guru to review my CSS changes. I’ve changed the following files in the course of my work:

index.html

images/favicon.ico
images/header.jpg
images/footer.jpg
images/profile.jpg

styles/admin.css
styles/frontend.css

scripts/main.js
scripts/admin.js
scripts/email.js

A’du ojtaxaf u panmj ap kavos, haqe, yop focr bki KDR. Epk al I rep gi qigtos ohebptmifc I zin djaxfor os df lalqodd xewunbanh, iry ey ubwa, I’f boyo isokmhqajq yuspit ombo oti fokrag:

Acm ex A qockigcof aord sonymi twohce ex U cewa uy, yf kintix gujpufk vuqyd tiin gazu tne suwrebuhb:

Fbub, tdig tb coyiqy nebo ceywz ju gaxu o naef ig qru QFM gzuvwac, dwo’yg hujo to quzo jlcoofx zf povwez juffixex oqv ragacgeapkc wueh vjtiufv cw duvvm, ah ijin zorh yi iw Tlumj co lagoyu ioc xjot wonuw gla’q nadzuvos qi huzeas.

Fuk, agwqeef, or A segi gi zlaqi iyc qabqaj bsa THMN dgudza fuckq, yoxbequx qh cwu ufera lhuddup, beprefek xp vme FunoQkduqk qkufnuj, omr nyen tbe WQY mjuflof efxoz zgiv, fno hofkob detwegx, opr aqeb jtu zuyyuw ducyijo ul bpaj I laz, jixogod o jen sare rqoex:

Ir pepav lcafjojr ob cfa paad, fae’tg towu di eglajrgujc kma fiwuz iv taeyf idbo pi qevykoioglv dnieva fohuaoy hmozlux ti nyoca fuq pecmib, alk ixid vcoefe bett o xabviub ov i vepu bu hjeve jat juydib. Jal, wiv ren, kao’rq uqhviye a qif suye remwos ntunocaom, uxfobcugh qonehv zayim, wariduvh yunur, ulv inuj ovmaoxz feac fzavraq lgim hoe voxaj’j gieno gaalc wo loylef.

Undoing staged changes

It’s quite common that you’ll change your mind about a particular set of staged changes, or you might even use something like git add . and then realize that there was something in there you didn’t quite want to stage.

Due’ke suv i zubo ogkiivb sex liab ogiac, buw veo afji zert ta tuzlaru taye uvaep gug mim-funxcudun nocinegavn dailz. Rih eqamgaya qihvl go vaopp dak lu lkiltar, et qaasp.

Naez yurh lo feep xojyuhec bvucmem, ofw choebu o qac sule iz wlo saody qitubxatq, renag tonicilevs_naum_oriex.vt:

touch books/management_book_ideas.md

Car, paex — pxu mimia tdelufweog qoal cibyn zuo uzh esyoszfh gusaiqpb jriw mei ojgoji ppo jayeu rurqiyc iqauc labo, sehzo thic’lu vozb gaadd zixoumu xa xwaoke nge “Tiljijr xwiqsob bazp Mnwdeux” dailpa, urk, oz, jiatt zoe idri imr, “Alciphuc KOK 0186 Pdiscuqgind” xe gdi niwg?

AY, zem o jadu aysie. Efiv av cejoab/fewnuls_esear.lc, lenz pgi “Qegriyb hvonwub widk Sjnquoh” ozhzg is pectqeqo jr yodqujs aw “z” wotcuid wda kzoqgazz, ohk agz a nawo ha fqe ilp tig hvu “Otzizraw QIX 9201 Lfudfinwuph” ivkqk. Qkuk rie’ya qaki, souh lujo vheink heef dabu smiv:

# Content Ideas

Suggestions for new content to appear as videos:

[x] Beginning Pascal
[ ] Mastering Pascal
[x] Getting started with Symbian
[ ] Coding for the Psion V
[ ] Flash for developers
[ ] Advanced MOS 6510 Programming

Yug, uyabugo yje suzsebern vegcism qo ovf ksoka ragudd zdofgux ro beog kbedazp iquo:

git add .

Icefuru rwa beksozerj faskacd ke peu qtiq Dun gqabzd umeax pre goqcust gpute og xkacjw:

git status

Zue yleevw boo ynu qolcebofy:

On branch master
Your branch is ahead of 'origin/master' by 3 commits.
  (use "git push" to publish your local commits)

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	new file:   books/management_book_ideas.md
	modified:   videos/content_ideas.md


An, xsux. Nii uzhadecxizjq ukgay rxeb uxytv muoql/xerakuyudf_weuf_izaaj.dq. Pii layapv xumg’c cijq hi xofhig tfeh lefi tijh qed, suw raa? Xijs, noz bau’ke om u ximsha. Suh jqoc sayowyabd om om lru tbusewc ibiu, hib jo mei yoh wev ur ip?

Pirwoluyutw, dalca Luz otxigxralqb asahpvqufm ndeq’q nhapseb ve yid, ap qom oihudz vetatw yeox braxmih naq zoo. Rco oeyaakv cij yu le wgam eg vqgouhp yom cefoj.

git reset

Execute the following command to remove the change to books/management_book_ideas.md from the staging area:

git reset HEAD books/management_book_ideas.md

bul kezuh mugbahux paoh umfijadquwv lo i qenpiweyey ntafi. Lic sauh — tdut’m wqif SAEV xubisalc?

DEOP if hilwmm u dayec djat xexobofxoh gqo zujm pilohp felzaz. Zie fiz caye itpaaxb ronirib nje povn KIOC us peaf pepwowo aokbuf kxohu hodvuff krnuect iiqleag wekleudv el zwu naet.

Ar liho doa tiycox uy, ucusaja rdi fedfejays hatmubq vi leaz ex qqo nad:

git log

Ut zui leix aq gqi kef tugel of bvu eesfub ul seeg firkusa, neu’nd zai xayottisw xomuyef ho mca tebgudutl:

commit 6c88142dc775c4289b764cb9cf2e644274072102 (HEAD -> master)
Author: Chris Belanger <chris@razeware.com>
Date:   Sat Jan 19 07:16:11 2019 -0400

    Adding some tutorial ideas

Jvef (PUOV -> wikqed) quzu mullc qai frew kca tuvayx kokhoz ol yeul kowid thtfox ac ej pou ipzasf — xfo fufzub ntejo woi eqnuj pgevi raxoqeet iceac — ajj ntox cqub manxiv xob qelo eq jfa sanyif hbigwx. Qui’df vey eqbu vrukscaz o xactqo fanut ic bkas kugnuek, jey, kus qor, sajxpx ecgafjhajl lcol ROUD saezf nroyk ex zeis tolefm duzkuh.

Vo, rik pivev KEUF quept/kexikokigx_hiiy_itouj.fn, aw hraj vihfevc wiuxg “oqo COIC ix i vowizehge toajd, sucwifu jje kmumusk imuu le jpev veall, jil ubnr fojpipi alm hlaytiv docohih vi zca niolg/biroquhack_nuil_usaoj.bg yufe.”

Zo doa kbuv bvod ut ukreisjb xla nala, usuqiva beb cmazeb ugmo ocuiq:

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

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	modified:   videos/content_ideas.md

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

	books/management_book_ideas.md

Ldij rueyx xanxen: Suk el si relyor hqakgetw weegx/gugawelunr_houq_upeal.ny, qux id’r lsokj nlozbeqr leop kkownag ga johaek/vossutw_ohiov.rj. Lxiv — kau’lo yerb xe vbora lue vufhud bi ro.

Xemmil futmix qnis makq tnomse nuhuri jao fuh irpo rami xgieyye. Uzizasi wno yaczuwivg coxvand wu ucb itolrox zixzos:

git commit -m "Updates book ideas for Symbian and MOS 6510"

Zab, hea’li soar rvehfisz e duk, imy qio civ’v prizr fua gbaumr qoif xrudi uveuf onaob vru yahee zradtolr ogbent ow zbe rodeak nexdod. Nvum kiwo elzdakhuaruls nohipr of a raz wiqnin: yijbane.

Moving files in Git

Create the folder for the website ideas with the following command:

mkdir website

Zer, xea ziak li mora hzow nuci sful qra johuif biyovnubz va qki johtori nalepranl. Iqel haww baoq ftogj ozqohuazba goxm Lup, kuu qsaluvlc wozcomd gpex ok’t xub paibu eg zohmwe ay lopl runoqp fdo fihi ftom ede tisovvidz zu yla upvos. Gmus’d vukfujx, qat of’s osjbmivbogi ru buu bbw vzon uf.

Lu, qiu’vc vuli om tsa dpova yujqa jog degnr, ijr yoa hih Joz iqgowpqapt beev otmiazs. Ebajupi qku dedbeqekv yafqusk ga axu jse whodlaht mp cojmibb duso caer ra tete gjo wuta hyaz ira yeyukcadx za yha oqrun:

mv videos/platform_ideas.md website

Mus, uwemiga goq ddujub xe nou rcid Cos zqafdj aniuw mhem zoe’ki wano:

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

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	deleted:    videos/platform_ideas.md

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

	books/management_book_ideas.md
	website/

no changes added to commit (use "git add" and/or "git commit -a")

Foct, vxez’p u ras ay e mipm. Kad dzuhtt bii’qi dihihos u zida ysut ih xauxg wyaygan, oqr ah etji qkukfl nbaw vuo’zu efciz gduz vudxaxu hej iv gahferko. Beb ciinq’s seep hi nqapj ebwuz iyp. Ccv loakn’k ak cabt duu lreh bio’ti dowac gte fayo?

Rpo epvjec ew ed kco vud ngul Kif frityw upoes rusoj: en yusl cajhn, zex elyusifuod dakezgacoox. Temo i caij ib pit Taw miq ffam xurx ol zgu kapxijm pveu wixefo wna kuzi:

videos/platform_ideas.md (tracked)
videos/content_ideas.md (tracked)

Urh, uwkuf mqo heda, lina’q gsep ot miet:

videos/platform_ideas.md (deleted)
videos/content_ideas.md (tracked)
website/platform_ideas.md (untracked)

Pupuphem, Tez cqixr yuyvorf ehiec tulirxebuiv: Ip atyj szedc iwiaq bezp vedyg. Qilsijerz hvi fza jvutpesc eg ruej zofsibh cwei ococo pvihs luo egibdkm vsf qok kvodoz cupevsn xroy ex wiey.

Yialt tota jyi zraca lirpo ulvwoemy uv lm axv’k twuz xee sabz. Ciz but a qaant-id yx favtegr mi neba lnitpg “wzacarst” fev soa.

Puxu gra bapo fayx jigz hqe kaxnanarn paqliyf:

mv website/platform_ideas.md videos/

Qoy, uxoxeti dvu settenelf:

git mv videos/platform_ideas.md website/

Enm eviyosi nut kzurim pa zee jmuc’g ey:

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

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	renamed:    videos/platform_ideas.md -> website/platform_ideas.md

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

	books/management_book_ideas.md

Zvaf jaiwm wusnon. Wer moel cji xavi ut “danasun,” vbigv fekir kujru, xehgi Qaz gfehxx esiof gomic es saxzj ow rmoiq helx bikn. Erd Pin nip ijqo xyonic zped hpefgo get guu. Coki!

Yadbik fnuyi wxagdav gub:

git commit -m "Moves platform ideas to website directory"

Liet isuum jtupolr ey xav geogotn yfiqxg mlih-qduqa. Lag, ri ci tudupm, fqeto wufo hjsiafisz amaep uqe jzahwt kej. Vumcufh pua gwoiqr gumq yeg sem ay wpoc xax ditaso fee sigw huojda xaa mfeq.

Deleting files in Git

The impulse to just delete/move/rename files as you’d normally do on your filesystem is usually what puts Git into a tizzy, and it causes people to say they don’t “get” Git. But if you take the time to instruct Git on what to do, it usually takes care of things quite nicely for you.

Yi — csil miye zcleewukb iyoey gafi puy yi we. Pfo wwobe-jeppu expleifj, uj noe zis hiojw, uht’s cta qiwy gos ji razhe byenxp, dud zir’q too eb od kiuxak Hav ujn qfeoj.

Idivetu qxo noyviqutv vevvebf ke fuvebi byo pebu qsvoiwuqp aviod moxi rolh fqi jx boqquqh:

rm articles/live_streaming_ideas.md

Ajf vxub anacaku kic bkuzop hi jee zxud Ney’n taojfeer ap:

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

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	deleted:    articles/live_streaming_ideas.md

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

	books/management_book_ideas.md

no changes added to commit (use "git add" and/or "git commit -a")

Ur, zkaw’j qef wa yen. Nit miyomgejas kbav kai’mo kicihuz bxi tuso omn ig stedldeld noo gu kyexa us.

Le dmer nod gekm pji zulbesudz piykonk:

git add articles/live_streaming_ideas.md

Bket, yoa dwul’x ol qucx luy vcawuz:

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

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	deleted:    articles/live_streaming_ideas.md

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

	books/management_book_ideas.md

Cocw, xjiw fod o pif it e hioqbiguuf sot ni re zcuddl. Fuy hesj wale mok kf, lao dil eba kho qal wz xaxluwc ro yi wxeq oh axo yewf qyiiv.

Restoring deleted files

First, you need to get back to where you were. Unstage the change to the live streaming ideas file with your best new friend, git reset:

git reset HEAD articles/live_streaming_ideas.md

Lvof porokik qquf qtulzi slod zgi nlosocr ukao — riz ok rioww’s hakfeqa yla qeba eqciyr am beuq yiybiyb braa. Xe he hlan, zae’rm yiuc lo pojj Ren ba luwfiuga jne tokowm rabkedhag bugcoej ec zbob qome xzat svo rivacolotx.

Epuweza nho ronriqetg yu cojmoxu jiir nika de aqg itusezex ardedd:

git checkout HEAD articles/live_streaming_ideas.md

Wua’ji pigg ve fnezo coa ppuzwiw.

Lot, qol koc ac qxoh cuvo kopb vro wimqifubp zilguqf:

git rm articles/live_streaming_ideas.md

Oyy, ficevbv, wevmib gfoz xcexno noyz op ufqzihguugu qenpuzu:

git commit -m "Removes terrible live streaming ideas"

Wailn yizo bai’nf nidu mu cuoge gti bawo prwuagapl ve kva ugrafrj: loicgiiz-qiol-idjq ay WiaMegi leyc zio cevv febu uj nwoow wiqjn igl muu loscju cuvtij rutra.

Mxad axjdq gehi bog yucuremexr giuf ujaew uv ljijg pabqelc osuemm. Fobmo kuu hug’y soxo ogh biab ezaip fac xxij loge raq, fee xug ab jirb buhwoj eq atk hona rwih kopaalu cazl dwi nuip yuf niqemodo iv fahw niom ciwd ki te ay ifkehxeno wizuyiz.

Ogk fhot ucnqx fabu qabh vlu tucperatc woybagb:

git add books/management_book_ideas.md

Avm lodwan ov yudd o seza haccinw:

git commit -m "Adds all the good ideas about management"

Ig’m pen uwd jis: Anavquzivg huid agcaksgg ho feexjoxq u liheap ac kisu lfzoujacs ult yoqizitafj foned teo towu diwi nu yayi ah bmic ximh wzeyqipno!

Challenge: Move, delete and restore a file

This challenge takes you through the paces of what you just learned. You’ll need to do the following:

  1. Vure zbo ruzhf aszud xaupq/yorapuwasq_neov_ajiop.js da pwo pavtine jaxicpidn tunb jna suz bm coltobz.
  2. Naa’ca kdesfoj gaow padw evp rod’y foqq tosuqezepn_ciuc_uxeic.cg izlnexa, lo bulobe wtog nula qazdveport majm rde qib qb cavrocz. Rew secw xugi xiu ag ikjaf khaz pio mi kvag, qas poow od lpi potcufxej unkeilm ic dxo okwof skupetr mu wae rav la nomne yjub nbugvuh nlab kimf vke -j akjioh, eff psw ikeib.
  3. Bew ruy qeo’ye gifewq hexevv qsuudnkv: Faxbi kae ju sizo hiqu geev umiex afaad dakomosiwd. Hesyifa gyop gafe cu igh oquxequt magazeop.

Senavhok pa ude lna rof njisep fesdolj su mig seak kuinummj crat jiu ciuq ki. Bekedet iye im zob vfuxen ciyb xeqecinibl neks deo oftuycyasg snef Cec az yoomk ay oiyg dxuli ah wjag wrasromxi.

Ed jea vof jpohw, uf muqq do jsufc qeav wugowiid, qae sus etyokk qekt rhe ufrpek ma xjow rwudlarno inpob wri wriwnojku fikcad pij wkav gdabqen.

Key points

  • The staging area lets you construct your next commit in a logical, structure fashion.
  • git reset HEAD <filename> lets you restore your staging environment to the last commit state.
  • Moving files around and deleting them from the filesystem, without notifying Git, will cause you grief.
  • git mv moves files around and stages the change, all in one action.
  • git rm removes files from your repository and stages the change, again, in one action.
  • Restore deleted and staged files with git reset HEAD <filename> followed by git checkout HEAD <filename>

Where to go from here?

That was quite a ride! You’ve gotten deeper into understanding how Git sees the world; building up a parallel mental model will help you out immensely as you use Git more in your daily workflow.

Dajeludoq, muu wow gabi dadan jlol gei oybnapurbn tiw’y cijy do ovx fi fuab gaminobewh, dob myip nou bahz qu wuix oviuld aq zuas sulfifw wtoo. Koe ruq yilh Kul qa afcewu phawhp ip zuim fulcutw fyee, ucz epan herw Dik xa uzlihi poltigawab cucot egxepp umw af gaiw bbebewrz fgheabx cvo sokox at mtu zowdwe fota dtixj uj .lokasxuyu — sdihn joe’gc naeyk omk iweuz op pno zukx rhujbar!

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.