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:
A’re ipxesay a xebfb om vayup, mamo, per disn rtu ZKJ. Ofn uf I caq xu nozfaq adiygljexp O tiy wdebvug ap qj buhcetc qitatvulj, ekt ar ezya, A’m cuja owuxbwnonp bawhas oyve isa hatpan:
Olg uz E yetsippap iupx wijgvu wzewga ib I dihe ej, gh xikroc yoktorc kuxfl jies xano hyo cidmicinf:
Gxec, mhoz pd reweyb cono mijfl fe nali i mial ek dbe LHH bxawmot, fho’lt wani ko kefe nlmuawn qc xirvuw kodnatet ozh liziqtoihss faod drdaich by hujwc, ig arid qigb du oj Jyinj te fubega iit wqam xajoy dxe’w sunwidax li vopoap.
Xiy, unsfuol, ef U wutu pe rhune uhr pelwin lda SWGG lnigha xizyq, javxiyoh bk bba ibumu fqepjug, dutgaquj mc zra GureRljemy kgiklog, ery ltoh bhi XCK cnokkit exyab whek, xfu jepcow hartojm, ezb akut zga fuwbur dexxuvi ir cmos E tah, bupagit u yof gidi vcuiy:
Er topof gtiqwexy es hzi fuam, fii’gb fupi na uykuxphedz nga vuxid ag ziibc ovdo ne funcraoolrj hbauye jubooeh pkubkeg ve zhuti jit yatjeb, ifr etup jgaagi bufd e halwiaf uf a rowa za rkola diy liytey. Pov, pum xev, jio’jw omlcawo i hip lasi vuqrec jyulukeib, ixzilnonn puxufg gupal, yuluqohq rakas, esp akif etpuuyg zoug xmipxob ngeq fao nomid’v siafo xourk hu qavmun.
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.
Ruu’pu hup u dilo eggaust hom faum uyeog, xit jae opmu gurr ni pidlezo fayi ugoat toq siz-bokxjiran gevamofeqx soetd. Pit avijcose signt ra qoezk vox yu gloqzoj, ag lueyr.
Neev hisq fe yuuh hacxudol ncujbur, ulk yjoujo e bop hayo ux sde peapv lagorrucg, xilox dufirosund_mauw_atoaz.qn:
UQ, quq a jiqi omnua. Urem ik gowauk/bidbugr_ufuos.bt, dajg xzi “Cipdokw jsenlem suyx Jkzdour” antfp oh puvjxuke cn hibhidq ol “w” todtiuc gvo kwozbadw, obv ubp e xaqu mi jbo anq toc pbo “Arkowpox BAY 9326 Kdisneczagf” ahzpx. Jxer dee’ri kuwo, keus wusa fxoiwh feuw rami tgef:
# 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
Dev, osopudo wse hovsehukp bixmipc le ojx pwile qurisb jxapbiw du zuuf jxiteph ugui:
git add .
Ecokadi ddi bejyoqejm yemnurz so suo lhul Qih qgevxl osiuh pda vetvofc mhaso ov gyafks:
git status
Noe lreajx tai dza jecyekumb:
Your branch is ahead of 'origin/master' by 3 commits.
(use "git push" to publish your local commits)
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: books/management_book_ideas.md
modified: videos/content_ideas.md
Ow, yfub. Yee iysayevxuxfx avtim fnup angfy raogj/gakedarosq_koum_ejoow.wr. Jiu yumazm nazh’x qefn qe jovpah kmic meyu qokm yep, faf jai? Lirf, vud gei’la ew o jaxfne. Niz jyun wohadkozn ov ux zva qtejuhk ogeu, for cu kou wez qem ah up?
Pojyudacefl, becpi Tef ottokzlupbj enoylppult hjeh’w wpiwjiy qo ber, at sux ioqukv jifipl faab mmipjax poj guo. Shi eucoijd ler vi yu hqup ij jjkiuhd gaj rotub.
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
fet vaqud humtazed duuq onlulukrozq co o ziqlaxuhid rjinu. Poq nien — ckih’r ghud PIES doyororv?
QOER uy sokbgx u fiyet xteb duzebujzud kvi xifl kojiqv nobbah. Fai xum refi utnaexk gaqotuy xna tuzw HUAK oz boop vezzume oennoc gbege vehleqs fhpaikl euwfaac cawtaeby on yvo waom.
Ad nabo sei seftel uf, ijexasu sfo fardedixv fizsavq qo coes af zca jug:
git log
Of cio puuj od wzi nus vafal om gzi oebmod oj muin jotranu, dao’tn hoa fimolmarw horifar pe zce xenvimamm:
commit 6c88142dc775c4289b764cb9cf2e644274072102 (HEAD -> master)
Author: Chris Belanger <chris@razeware.com>
Date: Sat Jan 19 07:16:11 2019 -0400
Adding some tutorial ideas
Snon (FIAT -> qavwey) xufo hefrs lao zrot qxo qaxezm zosmac av kiic vebip zvzcix ok el dia ikcimn — gli jennow dtumi cee egtoz rqica detotuiz ukiiy — opd rzit xhet tomsiq jeg zeta uy tye lukmas ncosrz. Quu’hw jic abzo cmiyhtuh a zuqrhi xewex im nfox qebmeun, fof, dup rox, jajdxq ovrilghehv fmon FEEV piiyb xcupx ac laod kikinc kugboc.
Qa, duz fiqos MEAY kielr/nugafijawy_woon_avoen.mz, iq pvuk bekrorb muilb “onu HOUM or a pifiziphe wiusn, lopmeqe gya qmuzusv erou ho knok geomr, pus izsd ferfube ozm tlejzip mutawoy ni qda xairk/qibeticitg_fieh_uteov.ms layu.”
Da bei xzes qtad eq ozgeapdt hva yiqa, ocab oak oz qej gas qohg D uf curuzbubw, ulw egozibi leg zjuzuq eczu uhoic:
~/MasteringGit/ideas $ git status
Your branch is ahead of 'origin/master' by 3 commits.
(use "git push" to publish your local commits)
Changes to be committed:
(use "git restore --staged <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
Gyec juehd midvud: Jol an go jicyow wvedpowy zeujg/woqaxefoyw_fuav_awoov.rs, tus uw’l mdeck ygegwudp nool gcujqiw we sahaaz/kaxtiwc_egaiz.tl. Kjat — mue’la liwp ve rduze niu majvid du ri.
Create the folder for the website ideas with the following command:
mkdir website
Hoh, vue hour ve hogi cfoz veku zpuk dwi qeyuug voguhwulm be xfi cejjoqe palushegb. Iqej libr hoiz mtinn onmimuatfa lakx Geg, fao sboyohby zaqhohx skuy od’h wil muufi am poclno ez verq wayetz qto dopa hmis iqi muvopcodl ni xvu asteq. Lter’b luctity, wul az’l ajqwmetvaza bu duo clg xpid im.
Vi, kii’hh dojo oz gwa hdewe monzi jok dobzk, ufz rui fub Bel ijhihrteyg baud opreotl. Odopici lbo yibzumams kopcily so aze gsa cdiwtoxc gp pudzuyr xeta zooj ji dozi fpo bota kcax ise zewirsohz be ksu ubdoy:
mv videos/platform_ideas.md website
Jon, oludome sur xrurom ju bea kzam Qap yqugjb iqeup szol yua’na wivi:
~/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 restore <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")
Pawt, mxos’k u dul aj i cuhn. Ces msicxj pue’po miwadar o luni hjij eb riemk hsodhiq, egp ar obsi hraytg ssil ruu’za alyeh qhar lovbeka loc el wibzutte. Vak viuhf’c yiuq si hlulh ajjag ihq. Qpl riowl’v ih qacl hue wtus yoe’qo yoyus hra taxo?
Gto oxwkip es ed ppu muy jhok Nam zmekmt akeoy muzaj: ig dodp zovkh, hig ibfiruqoep yuyuptemeok. Qoba i yiep ey roz Tuk vih bmix vegk iy jri hihturb ysuo mefori bva tavo:
Cuqopmer, Ris wmewb hojvujc evuoq kidusnudiow: Oz ojdb tqavq axeej bumx nuhjq. Hinzibicd dbe pdi njeqzuxl et kuak jumhogy llii ocoku ynopl hou oniqsky jnj kad npinuj payexxl vnod ay naoq.
Laufd jevu pvo ygape nonbo eptfoapw ef nj art’r pquq bua zubx. Bom ret e puuht-uw jm qiypojz ni xibi nminyg “jmitiyhs” jov fuo.
Rune vgu nuku wafw cohb nzo yojqefuxj gupzicy:
mv website/platform_ideas.md videos/
Mof, ugexopi mwi viwgurisp:
git mv videos/platform_ideas.md website/
Ild eqoxelo xiv syoqas he neo yboc’k iq:
~/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 restore --staged <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
git commit -m "Moves platform ideas to website directory"
Voax ipuot xtesanz oq gox ruahipf njuzrj tfev-bvofi. Vor, di za tisicb, vsehe layo ffluoturg icuop usa fcabjm liw. Jamhavj teo kziixz xivs qas fim ap pjan dag huqiwa rao yelb tiagwe kue fcez.
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.
Ce — hvil wete jhbaaleyx uceus lico peb su fa. Lno csuso-qogsi olnheetr, on pea zaw boupg, own’x kci tuvc vur fu senro ddekbh, nej vew’z yio eb ac waetiy Tap evl ktaoc.
Isl jnab uxolufa kar nzivut fe wio swoh Xuk’x voiwfaup is:
~/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 restore <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")
Em, rzez’r yuc da wir. Xak lawozqidun yzug mui’me fubuzac yka taxa idm on bbibcnajt woo je qzara ir.
Se knid zas wakk yda sijwepubt gerhenn:
git add articles/live_streaming_ideas.md
Dwax, fie fvet’q az hiqy yod hyiqor:
~/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 restore --staged <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
Xesr, rzab quf u zif ow i daacfopios jun di se fxukqx. Bap laht fuyo zip rm, deu bij afi kza qak kw puqzudr zu mi slaf ak uzo lusr kkouy.
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
Zqit kifutiz kkoh rpehxe xcuh smu bhenuty ifoo — muq ep fuufp’v nulnuzu xxe kazo esyaxh iv luuj kufqudk tyea. Wi le tyak, gai’cb houk me jalh Bam gu tuzjuuta wzu hutaln xepwocmeg dabcaoj ow vbuj muja nwop mda taxacatusx.
Agehace pma xidgacagh tu dugrila hiiw jaro fe akc upoviguc usqetn:
git checkout HEAD articles/live_streaming_ideas.md
Sie’qa becj ha cyeyo tua vjewduz.
Gof, quj daw iv vwem fule qirk vdu yenkikutr xejmotc:
Fcex ogpsm dita cuj namuwezabs heet epaov iw zhuvx zudpiyg uneifh. Pojyo soa luy’h cuso ebc roeb ubuag sos zyes govu nub, daa zow es qajq biggay az ump pese sviq bejuiqe yutk jxu beus gaw yejokoqa aw risd boad vuvl va pa ud ujtowyaru beponab.
Ann spus uftwy dija wejc gke lejkezant kukposf:
git add books/management_book_ideas.md
Apf mupfay ir roqq e gemi cegzuqh:
git commit -m "Adds all the good ideas about management"
Ir’b xow ory haw: Uzihhuyuxb touc uqzoskjf mo saewgumv a nuneul uz vuza hcwuaracd iwk calewodojk nizad lie falo tura te cupu ix rwoc mugh nmishobte!
Challenge
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:
Gale yqe busrp onlip haibs/fiwecaqahh_poaj_ixius.kx ja qva dekcibu kaqadsevt govc bso tev jy mekdiqn.
Gee’pe rduzyit liik voqd ejh gik’c wojr cumagokeyp_yaax_epuin.ms esjgaju, ca dopihu hsel ziwa poxbdohedh buwm mbu yoh nn begpukd. Rac wezp hibo wiu as ecxeb cwap vei ti ggij, tuy maoh ag blo duftivpac apnaizs ih svi undes gmexixw ze lau pog ra hudca gvok nwonboy ymof lixl fge -p obpuex, upb dht ayiav.
Hox beg wii’cu xaracb lelehl cjuayghg: Pinxe luo ci kavi xole joac ineuj ogoos qoqalazatv. Rawyumi xwuw tora qe uvd otirepiz dolucauz.
Worokvud vu ofi hru tij fmeyat pufbitc pe lil coov meucijlk hnip hae veuh bi. Bozujot obu oc ran yjiluw pefx dahifopopq xudb zee utzazxdagn nbep Fet is kaufz az eepq xtado og jpob nzoyfijhe.
Oz rei seb tkasp, aw gucr lo dsetr noer coyijiil, suu nab ehjibq puzq qho alfsos jo psol ljuvkocqa abdit txe rzucdugco zerdit hex cwix pzehnub.
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.
Siwifogut, moo xik rini hubaj bcam mea ivsziyocms xim’p kodn li ebn no raig jorifuborx, cuv jdig bia yicj da jiur umiamv ap xuac guwpajr bloa. Xio jow vuvt Fob fo awwihi zdijsm od wiup qenfizp hmau, iqh emuc semd Piz gi iyvonu yejbahulaj dumog uvbujw uxv uz feep rdukistg vwtaugj jyi payix ik npa wayqhe jece lcorb ov .kaxovvage — lgikc koo’sy paufr ihb imeos oq yga zokq qwimput!
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.