Git

Git is a popular version control system. It was created by Linus Torvalds in 2005, and has been maintained by Junio Hamano since then.
It is used for:
Tracking code changes
Tracking who made changes
Coding collaboration

Git
What does Git do?
  1. Manage projects with Repositories
  2. Clone a project to work on a local copy
  3. Control and track changes with Staging and Committing
  4. Branch and Merge to allow for work on different parts and versions of a project
  5. Pull the latest version of the project to a local copy
  6. Push local updates to the main project
Working with Git
  1. Initialize Git on a folder, making it a Repository
  2. Git now creates a hidden folder to keep track of changes in that folder
  3. When a file is changed, added or deleted, it is considered modified
  4. You select the modified files you want to Stage
  5. The Staged files are Committed, which prompts Git to store a permanent snapshot of the files
  6. Git allows you to see the full history of every commit.
  7. You can revert back to any previous commit.
  8. Git does not store a separate copy of every file in every commit, but keeps track of changes made in each commit!
Why Git?
  1. Over 70% of developers use Git!
  2. Developers can work together from anywhere in the world.
  3. Developers can see the full history of the project.
  4. Developers can revert to earlier versions of a project.
What is GitHub?
  1. Git is not the same as GitHub.
  2. GitHub makes tools that use Git.
  3. GitHub is the largest host of source code in the world, and has been owned by Microsoft since 2018.
  4. In this tutorial, we will focus on using Git with GitHub.
  1. check if Git version
                         
                            git --version
                            
    
  2. Configure Git
    Configure Git
    Note: Use global to set the username and e-mail for every repository on your computer.


    If you want to set the username/e-mail for just the current repo, you can remove global
                     
                    git config --global user.name "sohammanjrekar"
                
            
                     
                    git config --global user.email "mrsohammanjrekar@gmail.com"
                
            
  3. Creating Git Folder
    Creating Git Folder
    mkdir makes a new directory.

    cd changes the current working directory.


    Note: If you already have a folder/directory you would like to use for Git:

    Navigate to it in command line, or open it in your file explorer, right-click and select "Git Bash here"
        
            mkdir myproject
    
    
        
            cd myproject
    
    
  4. Initialize Git
    Initialize Git
    Once you have navigated to the correct folder, you can initialize Git on that folder

    In Java, there are different types of variables, for example:


    Note: Git now knows that it should watch the folder you initiated it on. Git creates a hidden folder to keep track of changes.
        
            git init 
    
    
  5. Git Adding New Files
    Git Adding New Files
    Files in your Git repository folder can be in one of 2 states:

    Tracked - files that Git knows about and are added to the repository


    Untracked - files that are in your working directory, but not added to the repository

    When you first add files to an empty repository, they are all untracked. To get Git to track them, you need to stage them, or add them to the staging environment.


    Note: Short status flags are:
    ?? - Untracked files
    A - Files added to stage
    M - Modified files
    D - Deleted files

                                    
                                        ls   
                                
                                

                                    
                                        git status
                                
                                

                                    
                                        git status --short
                                
                                
  6. Git Adding in Staging Environment
    Git Adding in Staging Environment
    One of the core functions of Git is the concepts of the Staging Environment, and the Commit.


    As you are working, you may be adding, editing and removing files. But whenever you hit a milestone or finish a part of the work, you should add the files to a Staging Environment.


    Staged files are files that are ready to be committed to the repository you are working on. You will learn more about commit shortly.

                                    
                                        git add index.html
                                
                                

                                    
                                        git add --all
                                
                                
  7. Git Commit
    Git Commit
    Since we have finished our work, we are ready move from stage to commit for our repo.

    Adding commits keep track of our progress and changes as we work. Git considers each commit change point or "save point". It is a point in the project you can go back to if you find a bug, or want to make a change.

    When we commit, we should always include a message.

    By adding clear messages to each commit, it is easy for yourself (and others) to see what has changed and when.

    The commit command performs a commit, and the -m "message" adds a message.


    Sometimes, when you make small changes, using the staging environment seems like a waste of time. It is possible to commit changes directly, skipping the staging environment. The -a option will automatically stage every changed, already tracked file.

    Warning: Skipping the Staging Environment is not generally recommended. Skipping the stage step can sometimes make you include unwanted changes.

                                    
                                        git commit -m "update"
                                
                                

                                    
                                        git commit -a -m "Updated"
                                
                                

                                    
                                        git log
                                
                                
  8. Git Help
    Git Help
    If you are having trouble remembering commands or options for commands, you can use Git help.


    There are a couple of different ways you can use the help command in command line:

    git command -help - See all the available options for the specific command

    git help --all - See all possible commands

                                            
                                                git commit --help
                                        
                                        

    Note: If you find yourself stuck in the list view, SHIFT + G to jump the end of the list, then q to exit the view.

                                            
                                        
                                            git help --all
                                    
                                    
  9. Git Branch
    Git Branch
    In Git, a branch is a new/separate version of the main repository.

    Let's say you have a large project, and you need to update the design on it.

    How would that work without and with Git:


    Without Git:
    Make copies of all the relevant files to avoid impacting the live version

    Start working with the design and find that code depend on code in other files, that also need to be changed!

    Make copies of the dependant files as well. Making sure that every file dependency references the correct file name

    EMERGENCY! There is an unrelated error somewhere else in the project that needs to be fixed ASAP!

    Save all your files, making a note of the names of the copies you were working on

    Work on the unrelated error and update the code to fix it

    Go back to the design, and finish the work there

    Copy the code or rename the files, so the updated design is on the live version

    (2 weeks later, you realize that the unrelated error was not fixed in the new design version because you copied the files before the fix)


    With Git:
    With a new branch called new-design, edit the code directly without impacting the main branch

    EMERGENCY! There is an unrelated error somewhere else in the project that needs to be fixed ASAP!

    Create a new branch from the main project called small-error-fix

    Fix the unrelated error and merge the small-error-fix branch with the main branch

    You go back to the new-design branch, and finish the work there

    Merge the new-design branch with main (getting alerted to the small error fix that you were missing)

    Branches allow you to work on different parts of a project without impacting the main branch. When the work is complete, a branch can be merged with the main project. You can even switch between branches and work on different projects without them interfering with each other. Branching in Git is very lightweight and fast!


    Emergency Branch
    Now imagine that we are not yet done with hello-world-images, but we need to fix an error on master.
    I don't want to mess with master directly, and I do not want to mess with hello-world-images, since it is not done yet.

                                            
                                                git branch hello     
                                        
                                        

                                        
                                            git branch
                                    
                                    

                                            
                                                git checkout hello
                                        
                                        

                                            
                                                git checkout -b emergency-fix 
                                        
                                        
  10. Git Branch Merge
    Git Branch Merge
    The text-align-last property specifies how to align the last line of a text.

    We divide modifiers into two groups:
    1) Access Modifiers - controls the access level
    2) Non-Access Modifiers - do not control access level, but provides other functionality

    1) Access Modifiers
    For classes, you can use either public or default

                                        
                                            git merge emergency-fix
                                        
                                        

                                        
                                            git branch -d emergency-fix
                                        
                                        
  11. Push Local Repository to GitHub
    Encapsulation
    git remote add origin URL specifies that you are adding a remote repository, with the specified URL, as an origin to your local Git repo.
                                
                                    git remote add origin https://github.com/w3schools-test/hello-world.git
                                
                                
                                    
                                        git push --set-upstream origin master
                                    
                                    
  12. Pulling to Keep up-to-date with Changes
    JPulling to Keep up-to-date with Changes
    When working as a team on a project, it is important that everyone stays up to date.

    Any time you start working on a project, you should get the most recent changes to your local copy.

    With Git, you can do that with pull.

    pull is a combination of 2 different commands:
    fetch
    merge


    Git Fetch
    fetch gets all the change history of a tracked branch/repo.


    Git Pull
    pull is a combination of fetch and merge. It is used to pull all changes from a remote repository into the branch you are working on.

                                                
                                                    git fetch origin
                                                
                                                

                                                
                                                    git pull origin
                                                
                                                
  13. Push Changes to GitHub
                                                
                                                    git push origin
                                                
                                                
  14. Push Local Repository to GitHub Pages
                                                                                        
                                                    git remote add gh-page https://github.com/w3schools-test/w3schools-test.github.io.git
                                                
                                                
                                                                                            
                                                        git push gh-page master
                                                    
                                                    
  15. Git Clone from GitHub
    JPulling to Keep up-to-date with Changes
    Note: According to Git naming conventions, it is recommended to name your own repository origin, and the one you forked for upstream Now we have 2 remotes:

    origin - our own fork, where we have read and write access
    upstream - the original, where we have read-only access

                                    
                                        git clone https://github.com/w3schools-test/w3schools-test.github.io.git
                                    
                                    

    we have a full copy of a repository, whose origin we are not allowed to make changes to.

                                    
                                        git remote -v
                                    
                                    

                                    
                                        git remote add origin https://github.com/kaijim/w3schools-test.github.io.git
                                         
                                    
  16. Git Ignore and .gitignore
    Git Ignore and .gitignore
    Git Ignore
    When sharing your code with others, there are often files or parts of your project, you do not want to share.

    Examples
    log files
    temporary files
    hidden files
    personal files
    etc.

    Git can specify which files or parts of your project should be ignored by Git using a .gitignore file.
    Git will not track files and folders specified in .gitignore. However, the .gitignore file itself IS tracked by Git.
    Note: In this case, we use a single .gitignore which applies to the entire repository.

    It is also possible to have additional .gitignore files in subdirectories. These only apply to files or folders within that directory. Rules for .gitignore Here are the general rules for matching patterns in .gitignore files:
    Pattern Explanation/Matches Examples
      Blank lines are ignored  
    # text comment Lines starting with # are ignored  
    name All name files, name folders, and files and folders in any name folder /name.log
    /name/file.txt
    /lib/name.log
    name/ Ending with / specifies the pattern is for a folder. Matches all files and folders in any name folder /name/file.txt
    /name/log/name.log

    no match:
    /name.log
    name.file All files with the name.file /name.file
    /lib/name.file
    /name.file Starting with / specifies the pattern matches only files in the root folder /name.file

    no match:
    /lib/name.file
    lib/name.file Patterns specifiing files in specific folders are always realative to root (even if you do not start with / ) /lib/name.file

    no match:
    name.file
    /test/lib/name.file
    **/lib/name.file Starting with ** before / specifies that it matches any folder in the repository. Not just on root. /lib/name.file
    /test/lib/name.file
    **/name All name folders, and files and folders in any name folder /name/log.file
    /lib/name/log.file
    /name/lib/log.file
    /lib/**/name All name folders, and files and folders in any name folder within the lib folder. /lib/name/log.file
    /lib/test/name/log.file
    /lib/test/ver1/name/log.file

    no match:
    /name/log.file
    *.file All files withe .file extention /name.file
    /lib/name.file
    *name/ All folders ending with name /lastname/log.file
    /firstname/log.file
    name?.file ? matches a single non-specific character /names.file
    /name1.file

    no match:
    /names1.file
    name[a-z].file [range] matches a single character in the specified range (in this case a character in the range of a-z, and also be numberic.) /names.file
    /nameb.file

    no match:
    /name1.file
    name[abc].file [set] matches a single character in the specified set of characters (in this case either a, b, or c) /namea.file
    /nameb.file

    no match:
    /names.file
    name[!abc].file [!set] matches a single character, except the ones spesified in the set of characters (in this case a, b, or c) /names.file
    /namex.file

    no match:
    /namesb.file
    *.file All files withe .file extention /name.file
    /lib/name.file
    name/
    !name/secret.log
    ! specifies a negation or exception. Matches all files and folders in any name folder, except name/secret.log /name/file.txt
    /name/log/name.log

    no match:
    /name/secret.log
    *.file
    !name.file
    ! specifies a negation or exception. All files withe .file extention, except name.file /log.file
    /lastname.file

    no match:
    /name.file
    *.file
    !name/*.file
    junk.*
    Adding new patterns after a negation will re-ignore a previous negated file
    All files withe .file extention, except the ones in name folder. Unless the file name is junk
    /log.file
    /name/log.file

    no match:
    /name/junk.file
                        
                            touch .gitignore
                             
                        
  17. Git Security SSH
    Git Security SSH
    Git Security Up to this point, we have used HTTPS to connect to our remote repository. HTTPS will usually work just fine, but you should use SSH if you work with unsecured networks.

    And sometimes, a project will require that you use SSH. What is SSH SSH is a secure shell network protocol that is used for network management, remote file transfer, and remote system access. SSH uses a pair of SSH keys to establish an authenticated and encrypted secure network protocol.

    It allows for secure remote communication on unsecured open networks.


    SSH keys are used to initiate a secure "handshake". When generating a set of keys, you will generate a "public" and "private" key.

    The "public" key is the one you share with the remote party. Think of this more as the lock.

    The "private" key is the one you keep for yourself in a secure place. Think of this as the key to the lock.

    SSH keys are generated through a security algorithm. It is all very complicated, but it uses prime numbers, and large random numbers to make the public and private key. It is created so that the public key can be derived from the private key, but not the other way around.
                        
                            ssh-keygen -t rsa -b 4096 -C "test@w3schools.com"
                             
                        
                            
                                ssh-add /Users/user/.ssh/id_rsa
                                 
                            
  18. Test SSH Connection to GitHub
                        
                            ssh -T git@github.com
                             
                        
                            
                                git remote add ssh-origin git@github.com:w3schools-test/hello-world.git
                                 
                            
  19. change a remote origin from HTTPS to SSH
                        
                            git remote set-url origin git@github.com:w3schools-test/hello-world.git
                                 
                            
  20. Git Revert Find Commit in Log
    Git Revert Find Commit in Log
    First thing, we need to find the point we want to return to. To do that, we need to go through the log.

    To avoid the very long log list, we are going to use the --oneline option, which gives just one line per commit showing:

    The first seven characters of the commit hash the commit message

    We want to revert to the previous commit: 52418f7 (HEAD -> master) Just a regular update, definitely no accidents here..., and we see that it is the latest commit.


    Git Revert HEAD
    We revert the latest commit using git revert HEAD (revert the latest change, and then commit), adding the option --no-edit to skip the commit message editor

                                    
                                        git log --oneline
                                    
                                    

                                    
                                        git revert HEAD --no-edit
                                    
                                    
  21. Git Reset
    Git Reset
    reset is the command we use when we want to move the repository back to a previous commit, discarding any changes made after that commit.


    Git Reset Find Commit in Log
    First thing, we need to find the point we want to return to. To do that, we need to go through the log.
    To avoid the very long log list, we are going to use the --oneline option, which gives just one line per commit showing:

    The first seven characters of the commit hash - this is what we need to refer to in our reset command. the commit message
                                    
                                        git reset 9a9add8
                                    
                                    
  22. Git Amend
    Git Amend
    reset is the command we use when we want to move the repository back to a previous commit, discardcommit --amend is used to modify the most recent commit. It combines changes in the staging environment with the latest commit, and creates a new commit. This new commit replaces the latest commit entirely.
                                    
                                        git commit --amend -m "Added lines to README.md"