Skip to main content

Git Commands And Practice

Setup project using Github source

//following is the commands to set project on your server of source using git repository,

# go to your project public folder
$ cd /var/www/html

# get your git repository url for source code using https or ssh then clone repositiry
$ git clone git@github.com:someprojectpath/projectdir.git
 
$ cd projectdir

# FOR DEVELOPER (User development branch)
$ git checkout -b development origin/development
$ git pull origin development

========================================================================

Undo 'git add' before commit


You can undo git add before commit with
git reset <file>
which will remove it from the current index (the "about to be committed" list) without changing anything else.
You can use
git reset

OR


You want:
git rm --cached <added_file_to_undo>
Reasoning:
When I was new this, I first tried
git reset .
(to undo my entire initial add), only to get this (not so) helpful message:
fatal: Failed to resolve 'HEAD' as a valid ref.
========================================================================

As a standard procedure developers need to adhere to following points:



Branches
Master -> Development -> Feature -> Development -> Release -> Master and Development
git-branching-model.png

Create a development branch:

  • Clone the repo
git clone git@github.com:projectrepository/projectname.git


INITIAL Creation of development Branch (Ignore if development branch available on origin)

  • Create an empty development branch locally and push it to the server

git branch development

git checkout development

git push -u origin development

  • Developers should check out using the development as base (and not master)

git checkout -b development origin/development

Begin new feature:

  • Each developer need to create separate branches for their respective features.

Instead of basing it on master, they should base their feature branches on development.

git checkout development
git pull origin development
git checkout -b some-feature development

  • Add commits to the local feature branch
  • Do not forget to use diff and confirm about the changes to be committed.
git status
git diff
git add <some-file>
git commit


Git pull request for code review:
  • After the feature is complete, push the feature branch
git push -u origin some-feature

  • Create a pull request (Help)
  • The lead reviews pull request and adds any comments.
  • When feature is ready to merge, one can click on the merge button to approve the pull request and merge into the release branch. ( Help )


Resolve Conflicts:
git checkout development # Make sure in development branch
git pull origin development # Make sure you have lasted code
git checkout branch_name
git merge development

Then you can resolve the conflicts by:
git checkout --ours filepath
or
git checkout --theirs filepath
or
manually modify to resolve
git add file
git commit
git push origin feature-branch




ONCE THE PULL REQUEST IS MERGED, DELETE THE FEATURE BRANCH.




Finish the Feature:
  • Makes sure the development branch is up to date before trying to merge in the feature
git pull origin development
git checkout development
git merge --no-ff some-feature
git push
git branch -d some-feature


Prepare for a release:
This branch is a place to clean up the release, test everything, update the documentation, and do any other kind of preparation for the upcoming release. It’s like a feature branch dedicated to polishing the release.
git checkout development
git pull origin development
git checkout -b release-0.1 development
git push -u origin release-0.1


Release:
  • Merges it into master and development, then deletes the release branch.
git checkout master
git merge --no-ff release-0.1
git push
git checkout development
git merge --no-ff release-0.1
git push
git branch -d release-0.1

  • Tag the commit for easy reference
git tag -a 0.1 -m "Initial public release" master
git push --tags


Bugs on production:
  • Hotfix branch
git checkout -b issue-#001 master
Fix the bug
git push -u origin issue-#001
Create pull request to master branch
Create pull request to development branch
IMPORTANT: pull request to development and master both branches


OR WITHOUT GITHUB
# Fix the bug
git checkout master
git merge --no-ff issue-#001
git push

  • Merge the hotfix with development branch as well
git checkout development
git merge --no-ff issue-#001
git push
git branch -d issue-#001

Always merge with --no-ff:merge-without-ff.png

  • The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward.
  • This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.
  • Reverting a whole feature (i.e. a group of commits), is easily done if the --no-ff is used.


DEVELOPMENT CHECKLIST
  • Attend all the netbeans error and warnings
  • format source and remove trailing source (tabstop 4, tabs to spaces enabled)
  • write unit test and verify by negative testing
  • run xdebug profile (use sort by self and optimise, sort by called count and optimise)
  • use debug bar and verify the sqls, use EXPLAIN to check the query performance
  • confirm memcache caching works by checking the execution time and xdebug profiler output
  • use web developer plugin and verify html/css
  • use yslow and google page speed and do the necessary optimisations
  • create a pull request to development branch and check for any conflicts
  • get the code reviewed and merged
  • pull to development branch to your workstation / laptop and verify the integration
  • pull to stage


PRODUCTION RELEASE CHECKLIST
  • Create Release branch from development
  • Set the release branch on stage
  • Run unit test and get the QA to verify it
  • Pull request to master
  • Version it and tag it.
  • stop memcache on production
  • Disable cloudflare
  • pull code (master) on production
  • Verify file permissions
  • restart Apache
  • restart memcached
  • Enable cloudflare


SERVER SETUP CHECKLIST
  • set umask to 002
  • set users and group staff
  • apache fine tune
  • mysql fine tune
  •  

Release lifecycle


1. Developers will create a local branch on their computer using developer branch as base and work on the separate local branch for each feature. That feature is later merged to the development branch and then pushed to github.


2. After first level of testing by developers, they have to deploy the code on Local testing server as and when its done without any cut of time.

3. QA team will test the code feature wise, and all tested code will be then deployed on stage server, which will be used as UAT instance (User Acceptance Testing), Code deployment should be done on this server before 5:00PM IST, so that after quick test by QA Team, it will be available for US team for the Acceptance Test.

4. All accepted stories will be pulled into release branch and they all will be deployed on Production environment on Monday & Thursday at 2:30PM IST.

  • In case of holiday on Tuesday or Friday we should avoid any release day before holiday.
  • In case of urgency developers will be allowed to do emergency push, which has to be approved by manager(s).

5. Release manager has to document of  all commands & branch, tag names etc. It should also have a proper rollback plan.

6. Each release tag should be postfixed with -yymmdd, in case of 2 releases on same day it should be -yymmddr1, -yymmddr2 and so on.

7. deploy and rollback commands should be tried on stage environment before executing on live servers.

8. Each release should have a “Release Note” which mention about the changes & bug fixes going in the release along with Pivotal ID.

========================================================================

 Setup Laravel project using Github repository

# go to your project public folder
$ cd /var/www/html

# get your git repository url for source code using https or ssh then clone repositiry
$ git clone git@github.com:someprojectpath/projectdir.git
 
$ cd projectdir

# FOR DEVELOPER (User development branch)
$ git checkout -b development origin/development
$ git pull origin development

# FOLDER PERMISSIONS
$ sudo chown -R apache storage
$ sudo chown -R apache bootstrap/cache  // if require then only


# TOOLKIT (SDK/FRAMEWORK) PACKAGES
$ composer install --no-dev (for development without --no-dev option)
$ composer update --no-dev (for development without --no-dev option)
NOTE: DEPENDENCIES get installed to vendor/ directory

# if you create any new class or route then please run bellow command
$ composer dump-autoload

# CREATE DATABASE
$ CREATE DATABASE databasename DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;


# CONFIG - Create a new file in root ".env"
$ sudo vi .env

# Add following content in the file
    APP_ENV=local
    APP_DEBUG=true
    APP_KEY=somekeyofappkey
    DB_HOST=localhost
    DB_DATABASE=databasename
    DB_USERNAME=databaseuser
    DB_PASSWORD=databasepassword
    CACHE_DRIVER=memcached
    SESSION_DRIVER=memcached

# ARTISAN COMMANDS - Artisian Commands useful to create base database for laravel and migrate schema with seeding data
# list available command
$ php artisan

# Migrate the database tables
$ php artisan migrate

# Seed the dummy data to tables
$ php artisan migrate --seed

# Following command is used to create a migration class for the tablename.
$ php artisan migrate:make create_tablename_table --create=tablename

# for clear artisan cache
$ php artisan cache:clear

# Vendor publish command
$ php artisan vendor:publish

(NOTE : find sql in the database/migrations folder)
   
# modules based migration commands
$ php artisan module:migrate admin
$ php artisan module:make-migration create_users_table admin

# RUN IN BROWSER
http://localhost/projectname/public/index.php/admin


# PHP INI SETTINGS
    post_max_size = 100M
    upload_max_filesize = 100M
    max_file_uploads = 100

# following are useful commands for artisan modulewise

# run seed and migration by clearing old migration and seed
$ php artisan module:migrate-refresh --seed admin


$ php artisan module:make-migration create_users_table admin
$ php artisan module:make-seed users admin
$ php artisan module:migrate admin
$ php artisan module:migrate-reset admin



//laravel artisan installation commands
# php artisan migrate
$ php artisan db:seed

$ php artisan module:migrate-rollback
$ php artisan module:migrate-reset
$ php artisan module:migrate-refresh

========================================================================

  Generating ssh keys

SSH keys are a way to identify trusted computers, without involving passwords. Following are the commands and steps to generate ssh keys and add to git repository for push pull

Step 1: Check for SSH keys

First, we need to check for existing SSH keys on your computer. Open Terminal and enter:
ls -al ~/.ssh
# Lists the files in your .ssh directory, if they exist
Check the directory listing to see if you already have a public SSH key. By default, the filenames of the public keys are one of the following:
  • id_dsa.pub
  • id_ecdsa.pub
  • id_ed25519.pub
  • id_rsa.pub
If you see an existing public and private key pair listed (for example id_rsa.pub and id_rsa) that you would like to use to connect to GitHub, you can skip Step 2 and go straight to Step 3.
Tip: If you receive an error that ~/.ssh doesn't exist, don't worry! We'll create it in Step 2.

Step 2: Generate a new SSH key

  1. With Terminal still open, copy and paste the text below. Make sure you substitute in your GitHub email address.
    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
    # Creates a new ssh key, using the provided email as a label
    # Generating public/private rsa key pair.
    
  2. We strongly suggest keeping the default settings as they are, so when you're prompted to "Enter a file in which to save the key", just press Enter to continue.
    # Enter file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]
    
  3. You'll be asked to enter a passphrase.
    # Enter passphrase (empty for no passphrase): [Type a passphrase]
    # Enter same passphrase again: [Type passphrase again]
    
    Tip: We strongly recommend a very good, secure passphrase. For more information, see "Working with SSH key passphrases".
  4. After you enter a passphrase, you'll be given the fingerprint, or id, of your SSH key. It will look something like this:
    # Your identification has been saved in /Users/you/.ssh/id_rsa.
    # Your public key has been saved in /Users/you/.ssh/id_rsa.pub.
    # The key fingerprint is:
    # 01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db your_email@example.com
    

Step 3: Add your key to the ssh-agent

To configure the ssh-agent program to use your SSH key:
  1. Ensure ssh-agent is enabled:
    # start the ssh-agent in the background
    eval "$(ssh-agent -s)"
    # Agent pid 59566
    
  2. Add your SSH key to the ssh-agent:
    ssh-add ~/.ssh/id_rsa
    

Tip: If you didn't generate a new SSH key in Step 2, and used an existing SSH key instead, you will need to replace id_rsain the above command with the name of your existing private key file.

Step 4: Add your SSH key to your account

To configure your GitHub account to use your SSH key:
Copy the SSH key to your clipboard. Keep in mind that your key may also be named id_dsa.pub,id_ecdsa.pub or id_ed25519.pub, in which case you change the filename below:
sudo apt-get install xclip
# Downloads and installs xclip. If you don't have `apt-get`, you might need to use another installer (like `yum`)

xclip -sel clip < ~/.ssh/id_rsa.pub
# Copies the contents of the id_rsa.pub file to your clipboard

Warning: It's important to copy the key exactly without adding newlines or whitespace.
Add the copied key to GitHub:
  1. Settings icon in the user barIn the top right corner of any page, click your profile photo, then click Settings.
  2. SSH keysIn the user settings sidebar, click SSH keys.
  3. SSH Key buttonClick Add SSH key.
  4. In the Title field, add a descriptive label for the new key. For example, if you're using a personal Mac, you might call this key "Personal MacBook Air".
  5. The key fieldPaste your key into the "Key" field.
  6. The Add key buttonClick Add key.
  7. Confirm the action by entering your GitHub password.

Step 5: Test the connection

To make sure everything is working, you'll now try to SSH into GitHub. When you do this, you will be asked to authenticate this action using your password, which is the SSH key passphrase you created earlier.
  1. Open Terminal and enter:
    ssh -T git@github.com
    # Attempts to ssh to GitHub
    
  2. You may see this warning:
    # The authenticity of host 'github.com (207.97.227.239)' can't be established.
    # RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
    # Are you sure you want to continue connecting (yes/no)?
    
    Verify the fingerprint in the message you see matches the following message, then type yes:
    # Hi username! You've successfully authenticated, but GitHub does not
    # provide shell access.
    
    It's possible that you'll see this error message:
    ...
    Agent admitted failure to sign using the key.
    debug1: No more authentication methods to try.
    Permission denied (publickey).
    
    This is a known problem with certain Linux distributions. 
  3. If the username in the message is yours, you've successfully set up your SSH key!
========================================================================

Adding an existing project to GitHub using the command line

  1. Create a new repository on GitHub. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub.
  2. Open Terminal (for Mac and Linux users) or the command prompt (for Windows users).
  3. Change the current working directory to your local project.
  4. Initialize the local directory as a Git repository.
    git init
    
  5. Add the files in your new local repository. This stages them for the first commit.
    git add .
    # Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.
  1. Commit the files that you've staged in your local repository.
    git commit -m "First commit"
    # Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.
  1. Copy remote repository URL fieldAt the top of your GitHub repository's Quick Setup page, click  to copy the remote repository URL.
  2. In Terminal, add the URL for the remote repository where your local repository will be pushed.
    git remote add origin remote repository URL
    # Sets the new remote
    git remote -v
    # Verifies the new remote URL
    
  3. Push the changes in your local repository to GitHub.
    git push origin master
    # Pushes the changes in your local repository up to the remote repository you specified as the origin

  =======================================================================

Setting your username in Git

Git uses your username to associate commits with an identity.
The git config command can be used to change your Git configuration, including your username. It takes two arguments:
  • The setting you want to change--in this case, user.name.
  • Your new name, for example, Billy Everyteen
To set your username for a specific repository, enter the following command in the root folder of your repository:
git config user.name "Billy Everyteen"
# Set a new name
git config user.name
# Verify the setting
# Billy Everyteen
To set your username for every repository on your computer:
  1. Navigate to your repository from a command-line prompt.
  2. Set your username with the following command.
    git config --global user.name "Billy Everyteen"
    
  3. Confirm that you have set your username correctly with the following command.
    git config --global user.name
    # Billy Everyteen
    
To set your username for a single repository:
  1. Navigate to your repository from a command-line prompt.
  2. Set your username with the following command.
    git config user.name "Billy Everyteen"
    
  3. Confirm that you have set your username correctly with the following command.
    git config user.name
    # Billy Everyteen
    
Tip: You don't have to use your real name--any name works. Git actually associates commits by email address; the username is only used for identification. If you use your email address associated with a GitHub account, we'll use your GitHub username, instead of this name.

Troubleshooting

My name doesn't show up on GitHub

If the email used in a commit matches a verified GitHub user account, the account's username is used, instead of the username set by Git.

New commits aren't using the right name

If git config user.name reports the correct username for the repository you're viewing, but your commits are using the wrong name, your environment variables may be overriding your username.
Make sure you have not set the GIT_COMMITTER_NAME or GIT_AUTHOR_NAME variables. You can check their values with the following command:
echo $GIT_COMMITTER_NAME
# prints the value of GIT_COMMITTER_NAME
echo $GIT_AUTHOR_NAME
# prints the value of GIT_AUTHOR_NAME
If you notice a different value, you can change it like so:
GIT_COMMITTER_NAME=Billy Everyteen
GIT_AUTHOR_NAME=Billy Everyteen

My old commits still have my old username

Changing your username in Git only affects commits that you make after your change.
To rewrite your old commits, you can use git filter-branch to change the repository history to use your new username.
==========================================================================

Setting your email in Git

GitHub uses the email address you set in your local Git configuration to associate commits with your GitHub account.

Setting your local Git email address using the git configcommand

The git config command can be used to change your Git configuration settings, including your email address. It takes two arguments:
  • The setting you want to change--in this case, user.email.
  • Your new email address--for example, your_email@example.com. Be sure to use your own real, unique email address.
Your email address will be visible on commits to GitHub. If you'd like to keep your email address private, set your Git config email to username@users.noreply.github.com instead, replacing username with your GitHub username. For more information, see "Keeping your email address private".

Setting your email address for every repository on your computer

  1. Open Terminal (for Mac and Linux users) or the command prompt (for Windows users).
  2. Set your email address with the following command:
    git config --global user.email "your_email@example.com"
    
  3. Confirm that you have set your email address correctly with the following command.
    git config --global user.email
    # your_email@example.com
    

Setting your email address for a single repository

You may need to set a different email address for a single repository, such as a work email address for a work-related project.
  1. Open Terminal (for Mac and Linux users) or the command prompt (for Windows users).
  2. Change the current working directory to the local repository in which you want to set your Git config email.
  3. Set your email address with the following command:
    git config user.email "your_email@example.com"
    
  4. Confirm that you have set your email address correctly with the following command.
    git config user.email
    # your_email@example.com
    
Setting your Git config email will not change the email address used for past commits, nor is it the same as adding your email address to your GitHub account.

Troubleshooting

Commits on GitHub aren't linking to my account

Make sure that the email address you set in your local Git configuration has been added to your GitHub account's email settings. After adding your email, commits that used that email address will automatically be counted in your contributions graph. There is no limit to the number of email addresses you can add to your account.
Changing your email address in your local Git configuration settings only affects commits that you make after that change. Old commits will still be associated with the old email address.

New commits aren't using the right email

If git config user.email reports the correct email address for the repository you're viewing, but your commits are using the wrong email address, your environment variables may be overriding your email address.
Make sure you have not set the GIT_COMMITTER_EMAIL or GIT_AUTHOR_EMAIL variables. You can check their values with the following command:
echo $GIT_COMMITTER_EMAIL
# prints the value of GIT_COMMITTER_EMAIL
echo $GIT_AUTHOR_EMAIL
# prints the value of GIT_AUTHOR_EMAIL
If you notice a different value, you can change it like so:
GIT_COMMITTER_EMAIL=your_email@example.com
GIT_AUTHOR_EMAIL=your_email@example.com
=========================================================================

Merge changes on detached branch after git checkout <commit hash>

Scenario : $ git checkout 12wsed
Then I made more changes (I though I was still on feature branch...my mistake), and commited again. Then I run git branch ,it prints out :
* (detached from 
12wsed)
  feature

ANS >>> You are on a detached branch now. It seems you want to replace your feature branch with this one. A safe way to do that is to rename feature to something else and then turn the current branch into a proper branch named feature:

git branch -m feature feature-bakup
git checkout -b feature

In your first step, I think you wanted to do a git reset instead of a git checkout:
$ git reset 
12wsed

On the other hand, if you don't want to replace the feature branch but merge the changes in the current branch to feature, you can do like this:

$ git checkout -b temp
$ git checkout feature
$ git merge temp
=========================================================================

 rename branch feature to feature-bak

$ git branch -m feature feature-bak
 =========================================================================

remove or delete untrack files from given folder path

//first check untracked files to be delete
$ git clean -n -d

//then actually remove or delete untrack files from given folder path
$ git clean -df <path>

=========================================================================

View see commits that are not in any branch or all commits

$ git reflog 

========================================================================= 

small git session : -


DVCS - Data version centralize
Git internally treat for every file and tree of commit of file as SHA1 checksum
Easy to move branch point from and to.
Snapshots

CVS / SVN - Centralize version service
Has only diffes stores not files.
working with branch in cvs is very painful.

snapshot - index - repo local

- Snapshot -
- Sandbox -

- index / cache  = stores in .git folder it also contains config, sha1 of every file etc.

To discard cache - git reset --hard
git add - goes to cache
git commit bu not pushed - goes to repo local
git push, git pull, git clone - are permanent operation to remote repository, you can also revert the change using git checkout command.
git rebase -

index - staged or git add file is goes to index and also commited portion to goes in cache
git reset - is reset index, git add files goes removed using gig reset
git reset --hard  - is removes git add and commited but not pushed the changes.
git rebase - Is rewriting srepository. is to rewrite history in the repository itself. remove any of the commits in between connected commits.
git checkout - when we want to go to particular commit or branch then we can use this.
git stash - put changes into git stack or some where in .git to use same in laster time.
git stash apply - will apply change to current state.
git reset and git reset head - are the same. the purpose of both is same. it will goes to last commit in local.


- Git clone with --bare option
$ git clone --bare repositoryurl
 --bare option will only pull the .git folder of the repository and not the hole coding(sandbox )

- Git branch --all
--all option will fetch the all the remote and local branches and list them all.

Example:
master
origin/master
origin/development
localsomebranch
origin/somefeaturebranch

- Git log 
$git log master 
- will display all the commit history of the local master branch
$ git log origin/master
-   will display all the commit history of the remote master branch

- Git remote update
$ git remote update
- fetches from all remotes, not just one.


- Git fetch
 $ git fetch 
- fetches chanegs from current remote branch


$ git fetch --all
This will fetch from all of your configured remotes, assuming that you don't have remote.Fetching all remotes One way to fetch multiple remotes is with the --all flag.

- Change remote url
 $ git remote set-url
- set the remote url to user defined.
- Change your remote's URL from SSH to HTTPS with the git remote set-url command. 
 $ git remote set-url origin https://github.com/USERNAME/OTHERREPOSITORY.git
Change your remote's URL from HTTPS to SSH with the git remote set-url command.  
$ git remote set-url origin git@github.com:USERNAME/OTHERREPOSITORY.git

- Cherry pick
Cherry picking in Git is designed to apply some commit from one branch into another branch. It can be done if you eg. made a mistake and committed a change into wrong branch, but do not want to merge the whole branch. You can just eg. revert the commit and cherry-pick it on another branch.

 $ git cherry-pick master 
- Apply the change introduced by the commit at the tip of the master branch and create a new commit with this change. 

$ git cherry-pick ..master 
$ git cherry-pick ^HEAD master
- Apply the changes introduced by all commits that are ancestors of master but not of HEAD to produce new commits.

Example:  
dd2e86 - 946992 - 9143a9 - a6fd86 - 5a6057 [master]
           \
            76cada - 62ecb3 - b886a0 [feature]
 
Let’s say you’ve written some code in commit 62ecb3 of the feature branch that is very important right now. It may contain a bug fix or code that other people need to have access to now. Whatever the reason, you want to have commit 62ecb3 in the master branch right now, but not the other code you’ve written in the featurebranch. ~ Here comes git cherry-pick. In this case, 62ecb3 is the cherry and you want to pick it!
$ git checkout master
$ git cherry-pick 62ecb3




- Git Rebase
git-rebase - Forward-port local commits to the updated upstream head.
If <branch> is specified, git rebase will perform an automatic git checkout <branch> before doing anything else. Otherwise it remains on the current branch.
If <upstream> is not specified, the upstream configured in branch.<name>.remote and branch.<name>.merge options will be used  and the --fork-point option is assumed. If you are currently not on any branch or if the current branch does not have a configured upstream, the rebase will abort.


Example:  
Assume the following history exists and the current branch is "topic":
          A---B---C topic
         /
    D---E---F---G master
From this point, the result of either of the following commands:
git rebase master
git rebase master topic
would be:
                  A'--B'--C' topic
                 /
    D---E---F---G master

=========================================================================//How to undo a git merge with conflicts

Latest Git:
$ git merge --abort
This attempts to reset your working copy to whatever state it was in before the merge. That means that it should restore any uncommitted changes from before the merge, although it cannot always do so reliably. Generally you shouldn't merge with uncommitted changes anyway.

Prior to version 1.7.4:
$ git reset --merge
This is older syntax but does the same as the above.

Prior to version 1.6.2:
$ git reset --hard
which removes all uncommitted changes, including the uncommitted merge. Sometimes this behaviour is useful even in newer versions of Git that support the above commands. 
=========================================================================

other useful commands


git clean -dxfq

git reset --hard

git status -u

git log --oneline

=========================================================================

What is a bare git repository?

What is the difference between a repository created using the git init command and the git init --bare command?
Repositories created with the git init command are called working directories. In the top level folder of the repository you will find two things:
  1. A .git subfolder with all the git related revision history of your repo
  2. A working tree, or checked out copies of your project files.
Repositories created with git init --bare are called bare repos. They are structured a bit differently from working directories. First off, they contain no working or checked out copy of your source files. And second, bare repos store git revision history of your repo in the root folder of your repository instead of in a .git subfolder. Note… bare repositories are customarily given a .git extension.
Why use one or the other?
Well, a working repository created with git init is for… working. It is where you will actually edit, add and delete files and git commit to save your changes. If you are starting a project in a folder on your dev machine where you will add, edit and delete files of your project, use “git init”. Note: if you git clone a repository you will be given a working repository with the .git folder and copies of the working files for editing.
A bare repository created with git init --bare is for… sharing. If you are collaborating with a team of developers, and need a place to share changes to a repo, then you will want to create a bare repository in centralized place where all users can push their changes (often the easy choice is github.com). Because git is a distributed version control system, no one will directly edit files in the shared centralized repository. Instead developers will clone the shared bare repo, make changes locally in their working copies of the repo, then push back to the shared bare repo to make their changes available to other users.
Because no one ever makes edits directly to files in the shared bare repo, a working tree is not needed. In fact the working tree would just get in way and cause conflicts as users push code to the repository. This is why bare repositories exist and have no working tree.
To summarize
I use a working directory created with git init or git clone when I want to add, edit and delete files in myproject locally on my dev machine.
When I am ready, I share my local changes with a git push to a bare repositorymyproject.git (usually on a remote server like github.com) so other developers can access my local changes.
 =========================================================================

Error: Permission denied (publickey)


A "Permission denied" error means that the server rejected your connection. There could be several reasons why, and the most common examples are explained below.

Should the sudo command be used with Git?

You should not be using the sudo command with Git. If you have a very good reason you must usesudo, then ensure you are using it with every command (it's probably just better to use su to get a shell as root at that point). If you generate SSH keys without sudo and then try to use a command like sudo git push, you won't be using the same keys that you generated.

Check that you are connecting to the correct server

Typing is hard, we all know it. Pay attention to what you type; you won't be able to connect to "githib.com" or "guthub.com". In some cases, a corporate network may cause issues resolving the DNS record as well.
To make sure you are connecting to the right domain, you can enter the following command:
ssh -vT git@github.com
OpenSSH_5.6p1, OpenSSL 0.9.8r 8 Feb 2011
debug1: Reading configuration data /Users/you/.ssh/config
debug1: Reading configuration data /etc/ssh_config
debug1: Applying options for *
debug1: Connecting to github.com [192.30.252.131] port 22.
Note the IP address (the numbers within the [ ] brackets). The connection should be made to a GitHub IP address, on port 22, unless you're overriding settings to use SSH over HTTPS.

Always use the "git" user

All connections must be made as the "git" user. If you try to connect with your GitHub username, it will fail:
ssh -T billy.anyteen@github.com
Permission denied (publickey).
Instead, you should verify your connection by typing:
ssh -T git@github.com
Hi username! You've successfully authenticated...

Make sure you have a key that is being used

  1. Open the terminal.
  2. Verify that you have a private key generated and loaded into SSH. If you're using OpenSSH 6.7 or older:
    # start the ssh-agent in the background
    eval "$(ssh-agent -s)"
    Agent pid 59566
    ssh-add -l
    2048 a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/you/.ssh/id_rsa (RSA)
    
    If you're using OpenSSH 6.8 or newer:
    # start the ssh-agent in the background
    eval "$(ssh-agent -s)"
    Agent pid 59566
    ssh-add -l -E md5
    2048 MD5:a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/you/.ssh/id_rsa (RSA)
    

The ssh-add command should print out a long string of numbers and letters. If it does not print anything, you will need to generate a new SSH key and associate it with GitHub.
Tip: On most systems the default private keys (~/.ssh/id_rsa, ~/.ssh/id_dsa and ~/.ssh/identity) are automatically added to the SSH authentication agent. You shouldn't need to run ssh-add path/to/key unless you override the file name when you generate a key.

Getting more details

You can also check that the key is being used by trying to connect to git@github.com:
ssh -vT git@github.com
...
debug1: identity file /Users/you/.ssh/id_rsa type -1
debug1: identity file /Users/you/.ssh/id_rsa-cert type -1
debug1: identity file /Users/you/.ssh/id_dsa type -1
debug1: identity file /Users/you/.ssh/id_dsa-cert type -1
...
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /Users/you/.ssh/id_rsa
debug1: Trying private key: /Users/you/.ssh/id_dsa
debug1: No more authentication methods to try.
Permission denied (publickey).
In that example, we did not have any keys for SSH to use. The "-1" at the end of the "identity file" lines means SSH couldn't find a file to use. Later on, the "Trying private key" lines also indicate that no file was found. If a file existed, those lines would be "1" and "Offering public key", respectively:
ssh -vT git@github.com
...
debug1: identity file /Users/you/.ssh/id_rsa type 1
...
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/you/.ssh/id_rsa

Verify the public key is attached to your account

You must provide your public key to GitHub to establish a secure connection.
  1. Open Terminal.
  2. Start SSH agent in the background.
    eval "$(ssh-agent -s)"
    Agent pid 59566
    
  3. Find and take a note of your public key fingerprint. If you're using OpenSSH 6.7 or older:
    ssh-add -l
    2048 a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/USERNAME/.ssh/id_rsa (RSA)
    
    If you're using OpenSSH 6.8 or newer:
    ssh-add -l -E md5
    2048 MD5:a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/USERNAME/.ssh/id_rsa (RSA)
    
  4. Settings icon in the user barIn the top right corner of any page, click your profile photo, then click Settings.
  5. SSH keysIn the user settings sidebar, click SSH keys.
  6. SSH key listing in GitHubCompare the list of SSH keys with the output from the ssh-add command.

If you don't see your public key in GitHub, you'll need to add your SSH key to GitHub to associate it with your computer.
Warning: If you see an SSH key you're not familiar with on GitHub, delete it immediately and contact GitHub support, for further help. An unidentified public key may indicate a possible security concern. For more information, see "Keeping your SSH keys safe."
=========================================================================

 Check git log of particular file in git

$ git log -p filepath.php > git-log.txt

Comments

Popular posts from this blog

Learn phpfox

PHPFox  is a social network script, it is an internet application and when you install it, it is a website. The  phpfox  script comes in 3 packages, each with a different set of modules. it has two products: 1. Nebula (upto phpfox 3.8) 2. Neutron (Newer) You can check the demo on :  http://www.phpfox.com =================================================== To clear cache in phpfox follow the following steps, admincp >> Tools >> Maintenance >> Cache Manager >> Click on Clear All button =================================================== To work facebook app on local Following settings need to done in facebook app   1) go => setting => Advance 2) see "OAuth Settings" area and set "Valid OAuth redirect URIs" =  http:// projectdomain /index.php?do=/user/login/, http:// projectdomain .com/index.php?do=/user/register/, http:// projectdomain .com, http:// projectdomain .com/index.php 3) en...

Interview PHP

>> Why do you want to work at our company? Sir, It is a great privilege for anyone to work in a reputed company like yours. When I read about your company I found that my skills are matching your requirements.  Where I can showcase my technical skills to contribute to the company growth. >> What are your strengths? I am very much hard working and optimistic. Hard Working: Work with dedication and determination. Optimistic: work with positive attitude. I am a team player. I am also very hardworking, and will do what it takes to get the job done. >> What are your weaknesses? Gets nervous when talk to strangers I am a bit lazy about which I am not interested I tend to trust people too easily. I am working on it. >> Why should I hire you? With reference to my work experience, I satisfy all the requirement for this job. I am sincere with my work and would never let you down in anyway. I promise you will never regret for the decision to a...

How to Make Your Own PHP Captcha Generator

In this article we will create file based simple yet successful captcha generator. 3 Major Anti-spamming techniques used? Mathematical Operation like Random number + Random Number = -> The user must specify the answer Random word -> User must type the word Random question -> Obvious one which the user should answer correctly [ex: Are you human?] How Captcha works? The captcha generator generates an IMAGE with the question and then put up a session variable storing the value. User input though an input box. Using php POST, we compare the session variable data with the user input and tell whether its a bot or human. Its coding time The Code First let's write the php script which generates the captcha image. We use the simple header-content change technique, from which we can easily bring up an image from a given text. captcha.php PHP Code: array("Num" => "Num"), 1 => array("Are y...