Git: Undoing Changes

Git Documentation

1. Modifying the last commit

1
$ git commit -- amend

1.1 Changing The last Commit

running git commit --amend, your code editor will open up, and let you edit it.

1.2 Add Forgotten Files To Commit

  • edit the file(s)

  • save the file(s)

  • stage the file(s)

  • and run git commit --amend

2. Reverting a commit

1
$ git revert <SHA-of-commit-to-revert>
  • will undo the changes that were made by the provided commit

  • creates a new commit to record the change

3. Resetting Commits

IMPOTANT: It’s recommended to establish $ git branch backup before reset commits.

1
2
3
4
$ git reset <reference-to-commit>

# EX:
$ git reset --hard HEAD~3
  • erase commits with the --hard flag

  • moves committed changes to the staging index with the --soft flag

  • unstages committed changes --mixed flag


  • ^ – indicates the parent commit

  • ~ – indicates the first parent commit

    EX

  • the parent commit
    • HEAD^
    • HEAD~
    • HEAD~1
  • the great-grandparent commit
    • HEAD^^^
    • HEAD~3
  • HEAD^^^2: ^2 : the merged other parent branch commit

4. restore working tree files

1
$ git checkout

Tagging,Branching, and Merging

Git Tagging

List all tags

1
$ git tag

Tag commits

1
$ git tag -a v1.0
  1. add a tag to the most recent commits

  2. -a means annotated, include extra information for the tag

    You can also $ git tag v1.0, but -a is recommended

Tag a specific commit

1
$ git tag -a v1.0 a87984

See all commits with the tag

1
$ git log v1.0

Delete a tag

1
$ git tag -d v1.0

Git Branch

1. List all branches

1
$ git branch

You can also find which branch you are currently in through it.

2. Create a branch

1
$ git branch sidebar
  • newly created branch sidebar points to the same commit as master

2.1 Create a brach points to a specific commit

1
$ git branch sidebar 42a69f

3. Switch branch

1
$ git checkout sidebar
  • remove all files and directories from the Working Directory that Git is tracking

    • (files that Git tracks are stored in the repository, so nothing is lost)
  • go into the repository and pull out all of the files and directories of the commit that the branch points to

4. See all commits in the branch

  • Fistly, checkout to this branch, then:
1
$ git log

HEAD--> points to the active branch

5. Delete a brach

1
$ git branch -d sidebar

6. Switch and Create Branch In One Command

1
$ git checkout -b sidebar

7. See All Branches At Once

1
$ git log --oneline --graph --all

Git Merging

1
$ git merge <name-of-branch-to-merge-in>

In the branch A, git merge B, then merge branch B to A

  • Fast-forward Merge

the branch being merged in must be ahead of the checked out branch. The checked out branch’s pointer will just be moved forward to point to the same commit as the other branch.

  • the regular type of merge
    • two divergent branches are combined
    • a merge commit is created

Merge Conflitcs

1. $ git merge heading-update

image-20180615164340641

2. $ git status can tell us merge conflict is inside index.html

image-20180615163421278

3. open index.html

Merge Conflict Indicators Explanation

The editor has the following merge conflict indicators:

  • <<<<<<< HEAD everything below this line (until the next indicator) shows you what’s on the current branch
  • ||||||| merged common ancestors everything below this line (until the next indicator) shows you what the original lines were
  • ======= is the end of the original lines, everything that follows (until the next indicator) is what’s on the branch that’s being merged in
  • >>>>>>> heading-update is the ending indicator of what’s on the branch that’s being merged in (in this case, the heading-update branch)

3. save the file, stage and commit it.

Add Commits To A Repo

1. create the Repo

1
$ git init new-git-project

2. move to correct project

1
$ cd new*

3. Chek Status (IMPORTANT!)

1
$ git status

4. Make Changes (Create Files)

1
2
$ touch index.html
$ open -a /Applications/Subli* index.html
1
2
$ mkdir css
$ touch css/app.css

5. Check Status Again

1
$ git status

img

6. Staging Files(git add)

6.1 Staging all files and directories

1
$ git add .

6.2 Staging specific files

1
2
3
$ git add <file1> <file2> ... <fileN>

$ git add index* css/app.css js/app.js

7. Check Status

1
$ git status

8. Make a Commitment

If not configured, configure it first

1
$ git config --global core.editor <your-editor's-config-went-here>

Commit it

1
$ git commit

Then open it in the code editor, Edit, save and close the file, then return back to the terminal

Note: you can directly add message with -m

1
$ git commit -m 'Initial commit'

Git Commit Recap

The git commit command takes files from the Staging Index and saves them in the repository.

1
$ git commit

This command:

  • will open the code editor that is specified in your configuration
    • (check out the Git configuration step from the first lesson to configure your editor)

Inside the code editor:

  • a commit message must be supplied
  • lines that start with a # are comments and will not be recorded
  • save the file after adding a commit message
  • close the editor to make the commit

Then, use git log to review the commit you just made!

9. git diff

see changes that have been made but haven’t been committed, yet:

1
$ git diff

10. Commit Message

书写建议

Udacity Style (For reference)

11. Having Git Ignore Files

the .gitignore file is used to tell Git about the files that Git should not track. This file should be placed in the same directory that the .git directory is in.

Step1: Add file .gitignore, in the same directory as .git

1
$ touch .gitignore

Step2: write the ignored file name in the .gitignore

1
$ open .gitignore

Add the following line in it.

1
2
3
4
project.docx

samples/*.jpg
# All the .jpg files in 'samples' directory

image-20180610202156014

Display A Repos's Commits

1. when Return a repo, Check status

1
$ git status

2. Display commits

1
$ git log

Display the SHA, Auother, Date, and content

Navigating in Less)

  • to scroll down, press

    • j or to move down one line at a time
    • d to move by half the page screen
    • f to move by a whole page screen
  • to scroll up, press

    • k or to move up one line at a time
    • u to move by half the page screen
    • b to move by a whole page screen
  • press q to quit out of the log

    (returns to the regular command prompt)

Search commits by message

EX: Message Set article timestamp color

1
$ git log --grep='Set article timestamp color'

OUTPUT:

1
2
3
4
5
commit 5de135ab4ca51b7d86b53ea1f81bca100c6eeb40
Author: Richard Kalehoff <richardkalehoff@gmail.com>
Date: Sat Dec 3 15:42:07 2016 -0500

Set article timestamp color

Display commits in oneline

1
$ git log --oneline

This command:

  • lists one commit per line
  • shows the first 7 characters of the commit’s SHA
  • shows the commit’s message

OUTPUT

1
2
3
4
5
6f04ddd Add breakpoint for large-sized screens
50d835d Add breakpoint for medium-sized screens
0768f3d Add space around page edge
f9720a9 Style page header
...

git log --stat Recap

--stat is a flag

To recap, the --stat flag is used to alter how git log displays information:

1
$ git log --stat
1
$ git log 8d3ea36  --stat

This command:

  • displays the file(s) that have been modified
  • displays the number of lines that have been added/removed
  • displays a summary line with the total number of modified files and lines that have been added/removed

git log -p Recap

To recap, the -p flag (which is the same as the --patch flag) is used to alter how git log displays information:

1
$ git log -p

This command adds the following to the default output:

  • displays the files that have been modified
  • displays the location of the lines that have been added/removed
  • displays the actual changes that have been made
1
$ git log -p -w

With-w, don’t highlight lines where only whitespace changes occurred.

Annotated git log -p Output

git log -p or git log --patch

img

Using the image above, let’s do a quick recap of the git log -p output:

  • 🔵 - the file that is being displayed
  • 🔶 - the hash of the first version of the file and the hash of the second version of the file not usually important, so it’s safe to ignore
  • ❤️ - the old version and current version of the file
  • 🔍 - the lines where the file is added and how many lines there are
    • -15,83 indicates that the old version (represented by the -) started at line 15 and that the file had 83 lines
    • +15,85 indicates that the current version (represented by the +) starts at line 15 and that there are now 85 lines…these 85 lines are shown in the patch below
  • ✏️ - the actual changes made in the commit
    • lines that are red and start with a minus (-) were in the original version of the file but have been removed by the commit
    • lines that are green and start with a plus (+) are new lines that have been added in the commit

git show

git show can be combined with most of the other flags we’ve looked at:

  • --stat - to show the how many files were changed and the number of lines that were added/removed
  • -p or --patch - this the default, but if --stat is used, the patch won’t display, so pass -p to add it again
  • -w - to ignore changes to whitespace

Create A Git repo

Create A Git repo

1. Create A Repo From Scratch

  1. 手动Create你的项目文件夹 the_Repo
  2. 运行:
1
2
$ cd the_Repo
$ git init

2. Clone An Existing Repo

一下命令将会在定位Directory下,新建子Repo

1
$ git clone https://github.com/udacity/course-git-blog-project

Then Don’t forget to cd to the Repo

如果需要Rename the project

1
$ git clone https://github.com/udacity/course-git-blog-project Project_Name

3. Determine A Repo’s Status

1
$ git status

Move and Rename

mv Move and Rename

1. Use mv ro rename

1) if file1 in Documents, and currently in Documents

Rename file1 to file2

1
$ mv file1 file2

2) if file1 not in Documents

Move file1 to Documents and rename it to file2

1
$ mv file1 file2

Note: file1 的位置可以在GUI里拖拽到Terminal

2. Move File

Formula

1
$ mv File Diretory

File可以是File/Directory

移动文件到上一级Directory

1
$ mv File ../

移动到当前文件夹

1
$ mv File .

49. Group Anagrams

Given an array of strings, group anagrams together.

Example:

1
2
3
4
5
6
7
8
> Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
> Output:
> [
> ["ate","eat","tea"],
> ["nat","tan"],
> ["bat"]
> ]
>

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.
  1. sorted(String):

    return a sorted list of String

    EX: sorted('tae') —> return ['a', 'e', 't']

  2. 如果要反复访问,用map,比用list 遍历要快得多

  3. list(dic.values())

RES

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
mapp = {}
for s in strs:
temp = ''.join(sorted(s))
if temp not in mapp:
mapp[temp] = [s]
else:
mapp[temp].append(s)
return list(mapp.values())

Shell Command

Shell Command

echo

Just like print in Python

1
$ echo 'Hello, World!'

1. cd: Change Directory

1
$ cd downloads

To parent directory ..

1
$ cd ..

2. ls: list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ cd Pictures; ls
# chage directory to 'Pictures', and list it.

$ ls Pictures
# list 'Pictures' Directory

$ ls Pictures/../Pictures

$ ls .
# list current directory

$ ls

$ ls ~
# list home directory

2.2 ls Other command

1
2
3
4
5
6
7
8
$ ls -l
# Long information about files

$ ls -l Documents/*.pdf
# Long information for pdf files in Documents folder

$ ls Sub*
# Show all the files start with 'Sub'(Case Sensitive)

3. pwd print working directory

1
2
$ pwd
/Users/yukizhong/Dropbox/02_Coding/Local_Blog (Path)

4. Directory names

  1. ls ..: Parent directory
  2. ls .: Current Directory
  3. ls ~: Home Directory

5. mkdir make directory, mv move

EX: Move epub files to ‘Books’ Directory

1
2
$ mkdir Documents/Books
$ mv Documents/*.epub Documents/Books

curl: C URL —> See URL

1. Download

to download https://tinyurl.com/zeyq9vc and save it as the file dictionary.txt

1
$ curl -o dictionary.txt -L 'https://tinyurl.com/zeyq9vc'
  1. -o download as
  2. -L redirect

cat: Catenate (连接) /concatenate; less

1. Display Text Files

1
$ cat dictionary.txt

Multiple files also works

1
$ cat mytext.txt mytext2.txt

2. Create a new file

1
2
3
4
5
$ cat > filename.txt

#....(file Content)
# 键入回车
# 然后 Ctrl + D 退出

3. 合并/复制文件

1
2
3
$ cat file1 file2 > newFile3

$ cat file4 > newFile5

4. Append text file

1
$ cat file1.txt >> To_be_appended_File.txt

rm: remove rmdir: remove directory

$ rm filenme —> 直接删除,可以批量删除

$ rm -i filename —> 删前询问,批量的话每个文件问一遍 (i: interactive)

EX:

  1. Good File
  2. Bad Name Good File
  3. Bad File
  4. Good Name Bad Face

You want to remove files 3 and 4, while leaving 1 and 2 intact.

1
2
3
$ rm 'Bad File' 'Good Name Bad Face'

$ rm *'Bad F'*

rmdir (When the directory is not empty)

1
$ rm -rf filename

mkdir Create new directory

1
2
3
4
5
$ mkdir newDir

$ mkdir -p newDirPath new Dir

$ mkdir -p udacity-git-course/new-git-project && cd $_

rename

In Mac, there is no rename command by default.

So, firstly use homebrew to install rename

1
2
$ brew install rename
$ rename [switches|transforms] [files]

grep Search txt file, wc: word count

  1. $ grep ibo dictionary.txt

OUTPUT: all the words containing ‘ibo’ in the file

  1. $ grep ibo dictionary.txt | less

Pip to less, show only one page

  1. $ grep -c ibo dictionary.txt

OUTPUT: Count how many words containing ‘ibo’

  1. $ curl -L https://tinyurl.com | grep fish | wc -l

wc: Count how many words

-l: How many lines

Shell and environment variables

$Variable distinguish it

1. Establish variable

1
2
$ num='1,2,3'
$ echo $num

2. Shell Variable

Shell Variable is all about fixed for shell

1
$ echo $LINES x $COLUMNS

OUTPUT: 12 x 80

3. Environment variable

Change in diff environments

1
2
3
4
5
6
7
$ echo $PATH
#.....

$ PATH=$PATH:/new/dir/here
# add new directories in the path

$ echo $PWD

Aliases

  1. You can use Aliases just as common commands
  2. Aliases only work in this terminal window.
  3. If you hope to keep alias work for all terminal, keep it in ‘.bash_profile’
1
2
3
4
5
6
7
# Give alias to a command
$ alias ll='ls -la'
# Run 'ls -la'
$ ll

# Show all alias
$ alias

find mdfind

1. find

在当前文件夹下搜索

1
$ find filename

2. mdfind

类似Spotlight 强大版本

搜索包含keyword的文件

1
$ mdfind keyword

搜索名字为filename的

1
$ mdfind -name filename