🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

FaithfulDanburite6249

Uploaded by FaithfulDanburite6249

ENSAM

Tags

git version control software development

Full Transcript

1 Git...

1 Git Head First be Get Going with Git g in nin g Git Start your engines... Creating a Git repository involves running the git init command inside the top folder of your project. We will start with telling $ git config --global user.name "Abdelhakim ZETATI" Git our full name : tell Git our email $ git config --global user.email "[email protected]" address. The md extension stands for Now we are ready to commit our work. Markdown. You can find more $ git add Checklist.md information about it here $ git commit -m "My first commit" www.markdownguide.org In Git, the commit object doesn't directly store changes but notes their location within the repository. It records this information along with other details in the commit..git he o n inside t e lo cati anges o in ter to th st or ed your ch A p t has r w here Gi fo l d e ented m a de , repres mit was ry 1, 19 70. only the files that you t im e the com Ja n u a The since add are committed. c on d s elapsed in s e Commit objects are stored by Git in binary format, making them very hard for humans to read but super safe and efficient for Git. Making a commit in Git involves two steps: first, you use 'git add' to put your changes in a staging area called the index, like a temporary holding space. Then, with 'git commit,' you move those changes from the index to the main storage area called the object database. The index lets you decide which changes to commit, giving you a chance to review and confirm before making a permanent record of your work in Git. When you add files to Git, it doesn't change your actual files; it just Git commands and makes a copy of their contents in the index, which is key to how Git subcommands are keeps track of your changes always lowercase keep in mind that Git is moving copies of your file from the working git add file1 file2 directory, to the index, to its object database. Git compares the copy it has in its object database with the one in the index and sees they are the same. It also compares the copy in the index with the one in the working directory and sees that they are the same. new file, never been added to Recall that any file in your working directory is either the index untracked or tracked. Also, a tracked file can be if the modified file is not added so it is not staged either staged, unmodified, or modified. It’s often useful to check the status of the files in your working directory. One of the most useful commands in your Git arsenal is the git status command. The Git commit history is often referred to as a directed acyclic graph, or DAG for short, wherein the commits form the “nodes” and the pointers to the parent form the “edges.” br an Multiple Trains of Thought ch ing ou t n Git, a commit is like a snapshot in time, and a branch is a collection of these snapshots. Branches are separate histories of commits in the same place. You can make new branches, switch between them, delete unwanted branches, and combine or 'merge' different branches Git by default uses a branch called master, which explains why git status reported that you were on that branch. You can use the branch command to create a new There is nothing special about the default branch, list all the branches in your repository, and branch or the name master. This branch is no even delete branches. different from any branch that you can create. Creating a new branch : git branch my-first-branch list all your branches : git branch To switch to another branch : git switch my-first-branch This will prompt Git to create the branch called git switch -c my-first-branch my-first-branch and switch to it immediately A branch is simply a reference to a commit via its ID. This A branch always points to the last commit on that branch, and reference is updated every time every commit, in turn, points to another commit (its “parent” you make another commit on that commit), and so on and so forth. branch. Every time you switch branches, Git rewrites your working directory to look like it did when you made the most recent commit on the branch you just switched to. Bringing the work that was done in separate branches together is called merging Merging in Git typically involves two branches—the branch that you are on (we’ll refer to this as the “proposer”) and the branch you wish to merge or “mix” in (we’ll call this the “proposee”). $ git merge proposee-branch git --help git branch -v git help record the branch name and the latest commit ID git -h Since master branch is the integration branch, you should merge the add- one Short fall-menu branch into the master branch. You will have to first switch to the info in t the master branch, and then merge the add-fall-menu branch into it. promp The add-fall-menu branch is based on the latest commit on the master branch. The master branch has not changed (no new commits on it) since the inception of the add-fall-menu branch. In other words, the add-fall-menu branch has everything the master branch does! Which means, for Git to make master (the proposer) look like addfall-menu, Git could simply move master to the same commit as the last commit on the add-fall-menu branch. This is referred to as a “fast-forward” merge—where a branch, in this case master, simply jumps forward. 2 It doesn’t quite work the other way Merging master into add-fall-menu is just another way saying “Hey Git, addfall-menu should be the combination of add-fall-menu and master.” Well, add-fall-menu is based on master, which means it already has everything that master has to offer. A little more Git setup If Git ever needs to create a commit, Git will present you with a text editor to type your commit message in. The question is—what editor should it use? git config --global core.editor "code -w" Git is configured to use a default editor, which is Vim. To use vs code you’re all set up and ready to merge add-thurs-menu into master. git merge add-thurs-menu Git is trying to create a “merge commit”. Since this is a new commit, Git needs a commit message. Git has to reconcile two different sets of changes into one. So Git pulls a fast one— it creates a new commit for us that represents the combined work from both branches. This is called a merge commit, and it is comprised of all the changes that were introduced in the two separate branches. But what if all three branches worked with the same file, modifying it in different ways? Git has absolutely no way of determining which version to keep, so it stops the merge midway and reports a merge conflict. The easiest way to resolve merge conflicts is to open the files that have merge conflicts in your editor. Once you make your choice and finish editing the file in your text editor, save the file. Next, we just follow the instructions that git status offered us. We use git add to add the final result to the staging area, then follow that with git commit. Cleaning up (merged) branches To delete a branch, we supply the -d (or --delete) flag to git branch along with the name of the branch we wish to delete, like so: git branch -d feat-home-screen You can’t delete the If the branch you are deleting has been merged, then your commit history does branch that you are on! not change! git branch. This will allow you to undo an accidental delete. Deleting unmerged branches Git will display the ID of the latest commit of the branch that you force deleted (-D), so you can always recover it like we showed you a few pages ago Typically, base your new branches on commits on integration branches. Merge back into the integration branch once you are done. Don’t reuse branches. look Investigating Your Git Repository ing a roun d Git provides us a command, called log, that does just that. By default the git log command lists all the commits in the current branch, with the latest commit at the top, followed by its parent You cam customize git log to see exactly what you want git log --abbrev-commit : Only displays enough characters to identify a commit uniquely git log --pretty=oneline : If you don’t care to see all the information about the author and the date git log --oneline : Produces the same output as git log --pretty=oneline --abbrev-commit. Git looks at the last commit you made and displays details about that commit per the flags you supplied. It then follows the pointer to the parent commit and repeats. Lather, rinse, repeat till it reaches a commit that has no parents. --all : displays all branches in the repository. git log --oneline --all --graph --graph : display the commits as a graph. Git also knows how many branches you have in your repository! This implies that Git should be able to find the latest commit on every branch and trace the lineage of that commit simply by following the parent pointer. Visualizing file differences The git diff command is short for “difference.” This command can be used to find the difference Running git diff in a repository compares the version that Git has in its index with the version of the file in the working directory The git diff command’s output is one file at a time, divvied up into separate areas of changes, each called a hunk. Git chooses to display only the parts of the file that have changed (hunks). 3 There are a bunch of tools available that can show diffs in a visually appealing way, and Git supports using many of these. git diff --word-diff : This shows how individual words differ rather than how lines differ. This tells Git to compare the contents of the --staged is just a git diff --cached : object database with those of the index. synonym for --cached. git diff edit-per-scotty add-skills : Supply the names of the two branches you wish to compare as arguments to the git diff command. “a” represents the changes in the edit-perscotty branch. When you compare two branches, Git simply compares the latest commits on each branch—often referred to as the tips of the branches. If you do this ** git diff add-skills ** Git assumes that your implied second argument is the working directory. like if its like this : ** git diff add-skills ** git diff 38a7176 846c398 : You can compare any two commits in your repository. Case of a new file Fixing Your Mistakes undo ing git restore file.md : Replacing the changes in the working directory by the ones in the index The Git restore command moves the file from the index to the working directory. git restore --staged file.md : Restore files in the index to their previous state git rm file.md : git rm command takes the paths of one or more tracked files you can only use and removes them from the working directory and the index. the git rm What does the git rm command really do? Its role is to remove (“rm”) tracked files. command to One effect of the git rm command is to delete the file from the working directory. It delete tracked also removes the file from the index files. If you choose to use the Finder (for Mac) or File Explorer (for Windows) to delete a file, you will then have to run the git add command with a special flag, -u or --update, to tell Git to record the name of the deleted file in the index : git add -u file.md Git deletes a file with a single command, but for directories, the 'git rm' command requires the '-r' flag to recursively remove all files and subdirectories. git mv file-a.md file-b.md : git mv work the same as rm but to move a file Editing commit messages git commit --amend -m "initial outdoors plan" editing the last commit messages in the branch To edit the message you must have a clean working directory. or else the changes you’ve staged will be part of the amended commit! the resulted commit that you will see in your Git log from now on. It has all the same metadata as the commit you amended, including the author info, timestamp, and the same parent commit. Renaming branches Switch to the branch you wish to fix, then rename: Rename a branch without switching: git branch -m glamping-trip git branch -m camping-trip glamping-trip new name. Or you could use --move. the name of the branch the new name. you wish to correct The HEAD Every time you switch branches, HEAD moves to reflect the branch you switched to. HEAD is simply a reference, like branches are. This difference is that a Git repository can have many branches, but there is only one HEAD. commit that HEAD points to will be the parent of the next commit—it’s how Git knows where to add the new commit in the commit history. When you add a commit, —Git moves HEAD to the new commit as well. A number n following the tilde operator represents the nth generational ancestor git diff HEAD~1 HEAD HEAD~ is an alias for HEAD~1 For a merge commit, querying HEAD~1 in Git refers to the first parent, following the same path as HEAD^1. 4 Undoing commits git reset 3e3e847 : you want to move HEAD to HEAD~1. you can use The three types of reset HEAD~1 Git reset provides three options to undo commits, affecting the working directory, index, and object database; it consistently moves the HEAD and branch to the specified commit, leaving the primary question about the fate of the committed changes. git reset --soft Using 'git reset --soft' is like undoing a commit, putting the changes back in the staging area (index) and working directory. It's as if you never made the commit, but you can quickly commit those changes again with 'git commit'. The current position is now at commit A. git reset (or git reset --mixed) In simple terms, using 'git reset --mixed' takes the changes from the commit you're undoing (let's call it B), puts them back in the index, and then copies them to your working folder. Also, it makes the index look like the commit you reset to (commit A), so now only your working directory reflects the changes from commit B. git reset --hard 'git reset --hard' goes all in - not only does it put commit A's changes in the index like 'git reset --mixed,' but it completely replaces your working files with those changes. After a hard reset, everything looks as if commit B never happened, with your working files, index, and HEAD all matching commit A. Another approach to undoing a commit is as simple as negating a commit—for every file added, you could delete it, and vice versa. For every line in every file that was added, you delete it, and for every line that was deleted, bring it back. git revert HEAD : create “anti-commits” colla bora Forking is a GitHub feature ting with G that makes it easy to copy a Remote Work it–p art I publicly available repository to your account. git clone : Create a copy (a “clone”) of an existing repository To change the default folder name created during a Git clone operation, provide the desired name as the second argument in the 'git clone name-of-folder-to-be-created' command. A remote refers to a copy of a Git repository hosted on a server The local and remote repositories are independent,when you clone a repository, the remote remains unaware, but your local copy knows its origin. git push : synchronizes local changes with the remote repository by pushing new commits from the local repository to the remote. Another bit of Git configuration To see the value of a config git config push.default git config --global push.default simple Push only the current branch: When you run git push There are other possible values for push.default: without specifying any branch names, it will only push matching: This tries to match local branches to the branch you're currently on. It won't try to push other existing remote branches based on names. branches or tags. current: This always pushes the current branch, Push to the branch with the same name: The branch you even if it doesn't track a remote branch. push will be pushed to a remote branch with the same nothing: This prevents pushing anything unless name. This assumes that your local branch has been you explicitly specify branches. configured to track a remote branch with the same name. git remote : name of your remote repository. in git put git ask you for your “password,” but it’s really asking for is your “personal access token.” Git offers another configuration, called credential.helper, that you can configure to use one of the When you invoke the git push command, Git is actually performing git credential managers push origin. This, in turn, pushes your changes to the URL listed in the “push” entry when you run the git remote command. the r emo If you do something that changes the ID of a commit befo te re th com e that is now public,Git will reject your push, telling mits you that the two commit histories don’t line up. 5 One thing to note here is the remote only has the merge commit “F,” as well as both its parents: “E” (on the master branch) and “D” (on feat-a branch). It does not, however, have the feat-a branch! Pushing local branches You can use the -u flag instead of --set-upstream with git push They mean the same thing In Git, specifying the remote (e.g., 'origin') when setting the upstream branch is essential because Git supports communication with multiple remotes. While Git is aware of the default remote, explicitly specifying You can use pull requests for merging it grants flexibility, enabling users to clone from one The first option for creating pull requests is easy—simply type repository and push changes out the URL in your browser window to a different remote repository if needed. second one... Instead of merging your local branch directly into master, you push the branch to the remote and create a pull request. This tells your colleagues that you wish to merge some work and displays the commits and the files changed, so they know what changes you’ve made. The pull request also gives your colleagues a way to make suggestions on how you could change or improve your work. Once they approve your pull request, you can go ahead and merge your changes. You’re done! To implement suggested changes after a pull request, make edits locally, commit, and push again. The push updates the remote, automatically reflecting changes in the pull request. Colleagues can review the updated commits and provide feedback. But how do we synchronize the local with changes that GitHub’s default behavior is to happened in the remote? always create a merge commit. colla bora ting with Go, Team, Go! Git– part I I Git provides various configuration options; for instance, setting push.default to 'simple' ensures Add someone a collaborator on GitHub only the current branch is pushed or pulled. While experienced users may explore other options Catching up with the remote (git pull) The git pull command attempts to find the remote counterpart of the branch you are on, then asks the remote if there are any new commits on that branch. If there are, it will fetch those commits and add them to your local history. The branches that Git creates when you clone (prefixed with the name of the remote) are called remote tracking branches. The references to "origin/master" in Git In fact, you have no control over these branches. represent bookmarks for They are meant to be managed by Git. remote branches, guiding Reasons for remote tracking branches: actions like push and pull. They serve crucial roles, knowing where to push ensuring updated versions, identifying local commits not in the remote, and providing a safe method to sync with the remote repository. The first reason for remote tracking branches is so Git knows what to do when you perform certain Git operations, like pushing or pulling. How does Git know where to push a newly created branch? When we “set” the “upstream” for a branch—origin feat-a, we are telling Git that the branch it should be tracking in the remote (origin) is a branch called feat-a. git fetch When you perform a fetch, much like pull, your clone gets the latest commits. But this is where the behavior of fetch is different from pull—fetch only updates the remote tracking branches, whereas pull, as you know, updates both the remote tracking branch and your local branch. getting (all) updates from the remote 6 Executing 'git fetch' retrieves all new commits and branches from the remote repository,incorporating changes into your clone. For instance, if a collaborator creates a new branch, makes commits, and pushes them, a Just remember, though, your local branches remain unaffected. Only subsequent fetch brings the new branch the remote tracking branches get updated. and its commits to your local clone, marked as a remote tracking branch. Notice that you skip the “origin/” in the name. Git recognizes that you have a remote tracking branch with that name, so it simply creates a local branch called addison-add-faqs. Its remote tracking branch is automatically set to origin/addison-add-faqs (since that’s where it originated from). knowing you need to push Remote tracking branches can tell you where your branch is in relation to the remote tracking branch. However, remember, remote tracking branches don’t update themselves. They getting ready to push wait for you to run the git fetch command Suppose your local branch (say it’s master) has indeed diverged from its counterpart in the remote. What happens when you push? ch f et You now know that remote tracking branches are, in fact, You can't merge into the remote tracking branches. Which means you can merge origin/master into your branch because you can't switch to it local master branch. The git pull command it first performs a git fetch, then merges the remote tracking branch of the branch you are on into its local counterpart. Use git fetch + git merge. Avoid git pull. Doing a git fetch does not affect your local branches. Doing a git fetch gives you an opportunity to think about what to do. “Always leave the campground cleaner than you found it” git push -d origin feat-a : Git will first delete the branch in the remote, and then clean up the remote tracking branch in your clone To remove remote tracking branches without corresponding remotes, use the 'git fetch -p' or '--prune' flag. sear chin g Git repo Git a Grep sitor ies git blame file : When a line was changed, who changed it, and the since git blame only looks ID of the commit that introduced that change. at the lines in the file at the git blame to show us the revision history of a file at any commit time you run it, it cannot it tell you about deleted lines. git blame c3668177 drinks.md c o mm r e e y o ua p l y t h la m e. ng Su p b Stri ng for t o git ki ID loo You can use Blame in GitHub git grep fall If you are looking for a phrase, wrap it in double quotes too, just go to the content of the file and click to -i ( --ignore-case), -n(--line-number), -l(--name-only [file names only])..... git log's “pickaxe” capability (-S) If you are interested in when the word “tired” first appeared or disappeared, you can use the git log command with the -S (uppercase “S”) flag. This lets you search the diffs of each commit like so: git log -S tired You can restrict git log to only display the log for a single file by supplying the filename at the end. git log -S tired pickaxe-demo.md Using the “patch” flag with git log 7 If you ever wanted to see the actual diff that each commit introduced, you can use yet another flag with git log, which is -p (shorthand for --patch). we combine them to get a better result for serching git log -p --oneline -S tired --word-diff git log's other “pickaxe” flag (-G) -G option accepts regular expressions if you want to find every time a particular piece as arguments (unlike -S, which by of text showed up in the diff of a commit use -G default only accepts strings). Searching commit messages git log --grep “some word” : find every commit that uses the phrase “some word” in its commit message git checkout 6b11ec8 : Git rewrites your working directory to look exactly like it did when you made the commit. When you check out a commit using its ID, Git says You are in 'detached HEAD' state. What this means is that you are no longer on a branch. The commit that HEAD points to will be the parent of the next commit. There is nothing stopping you from making edits to your repository and making a commit at this point! What would your history look like if you did make a commit? If you switch away to another commit or branch—you’d leave all your commits behind, and unless you remember the commit IDs, there is no easy way to get back to them! Searching for commits using git bisect Git's pickaxe options are great for finding changes, but they stumble when you're unsure what to search for. Imagine a bug in the master branch, and you don't know what's causing it. Pickaxe won't help. Instead, you can use 'git checkout' to go back in time, checking each commit to find the bug. It's like a detective story—look around, test, and if needed, go back further. But here's a cooler trick: 'git bisect.' It's like a smart search that quickly finds the bug in your commits. Imagine it as a game of 'hot or cold,' and Git guides you to the bug. It's much faster than the 'git checkout' method. Ready for some Git magic? Next you have to tell Git the “bad” commit ID—in this scenario, HEAD has the bug, so let’s tell Git that. Then you tell Git the “good” commit ID, which in this case is commit ID 6b11ec8. Git immediately gets to work—starting a binary search. It finds a commit somewhere halfway between the “bad” and “good” commits, and uses the git checkout command to check out that commit If you do see the bug in this commit, then you tell Git just that: On the other hand, you might not see the bug. Then you use git bisect good. Telling Git whether a commit is bad or good tells Git which direction to keep searching in After a few iterations with git bisect (depending on how many commits it has to search), Git will show you the commit that you’ve identified as the one that introduced the bug: You’ll need to signal to Git that you are done: #ProTips making y our life e asier wit h Git 8 When you use "git config --global", Git saves the setting in a file named.gitconfig in your home directory for use across all repositories. Git to the rescue—we can override global options for a particular project. The git config command supports another flag, --local, lt that writes a configuration file for a specific repository: d e fau e a l is t h git config --local user.email “[email protected]” c - - lo Git stores the local configuration in a file called “config” inside the hidden.git folder The git config command does not check if the section and key name git config --local --unset user.email you supply are valid! Let’s say you accidentally supply the option as --list flag : list all the options you’ve set, global or local user.nme—Git will record it in a new --show-origin : show you where Git picked up a particular setting key-value pair Git reads the global configuration first, followed by the local configuration. The --list flag lists the options in the order Git encounters them—entries at the top are global, followed by any local entries Git aliases, aka your personal Git shortcuts Now, instead of having to type git log --oneline --graph --all, you simply invoke git loga and you get the exact same output! Finally, always make your aliases lowercase. This fits with how Git commands work and they are easier to type. Telling Git to ignore certain files and folders When you initialize a Git repository, Git creates a hidden.git folder. The root directory of your project contains this.git folder, and you can create a.gitignore file there to specify files for Git to ignore, preventing them from being tracked in the repository. Now suppose we add a.gitignore file at the root of the project After creating the.gitignore file, you should add it to the index and then commit it. This makes it consistent across all collaborators working on the repository, and any changes to it will be part of your commit history. note is that if you want to ignore a folder, you need to append it with a forward slash (/). Without the trailing slash, Git will treat it as a filename. Here are some guidelines for writing a good commit message: Always use the imperative mood (updated documentation, update documentation) Avoid using the -m (or --message) flag with the git commit command (You can use all of your text editor’s capabilities to craft a good commit message.) The anatomy of a good commit message The most important thing to remember about a commit message is that it should focus on the why of a change, not the how or the what. GitHub and other repository managers, like the --oneline option, display only the first line of every commit message you must separate the body from the header using a blank line. rg : Prefix the name of the Create helpful branch names branch with your initials

Use Quizgecko on...
Browser
Browser