0% found this document useful (0 votes)
5 views3 pages

Essential Git Commands and Workflows

This document provides comprehensive Git commands and workflows for managing projects, including creating and cloning repositories, tracking files, committing changes, and working with branches and submodules. It also covers advanced topics such as orphan branches, worktrees, and syncing with remote services like AWS S3. Additionally, it outlines a workflow for submitting pull requests and downloading single files from Git repositories.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Essential Git Commands and Workflows

This document provides comprehensive Git commands and workflows for managing projects, including creating and cloning repositories, tracking files, committing changes, and working with branches and submodules. It also covers advanced topics such as orphan branches, worktrees, and syncing with remote services like AWS S3. Additionally, it outlines a workflow for submitting pull requests and downloading single files from Git repositories.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

## Git Notes

### To create a new project


mkdir mypoject
cd myproject
git init

### To clone a existing project into the current directory


git clone [Link]

### To clone a existing project into a specified directory


git clone [Link] mypath/[Link]

### To untrack specified file or directories


echo 'myfile' >> .gitignore

### To track files


git add filename // To stage specific file
git add . // To stage all new and modified files
git add -U // To stage, modified and deleted files
git add -A // To stage all changes

### To commit the changes


git commit -m 'commit message'

// Shortcut for
#git add modifiedFile
#git commit -m 'commit message'

git commit -am 'commit message'

### To push to remote server


git push

## Tag
Tag is a permanent pointer for a specific commit

git tag 1.0

## Update git password


It is a two step process

git config --global [Link] store


git pull //Now this command will ask for password

## Branches
Branch is a pointer to specific commit.
Branch is a moving pointer to series of commits in the repository.
Whenever there is a new commit in the branch, pointer will move to new commit.

Firt commit is the root of the tree. Master is the default pointer to it.

### List branches


git branch // list of branches higlighing active branch with *

### Working with branches


git branch kanna // creates a new branch kanna
git checkout kanna // moves HEADER to kanna from the master (assuming one is in master branch)

git checkout -b kanna // short cut for above two steps

git checkout master // moves HEAD to master

git merge kanna // merges the commits made in the kanna branch into master

// deletes branch
git branch -d <branch_name>

// deletes a remote branch


git push -d origin <branch_name>

### Rename Branch


git checkout <old_name>
git branch -m <new_name>
git push origin -u <new_name>
git push origin --delete <old_name>

### Remote Branches // TODO


git remote add origin remoteURL
git push origin mybranch

origin/myBranch is the remote branch

### List Remote urls


git remote -v

### To overwrite remote urls use set-url:


git remote set-url origin git://[Link]

### Orphan Branch


git checkout --orphan branchName
// Orphan branch can't be created with "git branch" command
// Purpose of creating orphan branch is to create new branch without commit history
// And start making commits in it as if that is the start of the commit history

### worktree branch


git worktree add myworktree // creates myworktree folder and myworktree branch

### Git Revert


// list of commits with refs
git reflog

// reverts latest 2 commits without asking for commit messages


git revert --no-commit HEAD@{2}..HEAD

// now commit
git commit -m 'reverted to old commit'

### Reset Vs. Revert // TODO


git reset // use for local branches as it erases history
git reset HEAD~2 // moves the head to specified point and erases history

git revert // use for remote branches. It reverts specifi commit(s)


git revert sha1ID // for reverting single commit
git revert sha1ID1 sha1ID2 // for reverting multiple commits

git revert is safest option as it creates new commit without touching history.

### Rebase Vs. Cherry-pick // TODO


git rebase

## Submodules
Useful for third party modules like modules that goes into 'vendor' directory in golang.
Warning: Don't make any changes in submodules repositories directly! to avoid unnecessay conflicts.

git submodule add urlpath destintionFolder


git submodule add [Link] vendor/[Link]/ekanna/SubProject

Also useful for statci site generators like Hugo


where you can have source files in one repo and generated content in another repo and link them using submodule

git submodule add [Link] public


cd public
// commit changes
// Here we will commit changes to submodule folder itself directly
// because it is auto genereated unlike vendor folder above

### Clone a repository along with submodules


git clone --recursive [Link]

### Pulling in Upstream changes


git submodule update --remote vendor/[Link]/ekanna/SubProject

## Worktrees
To convert branch into directory/folder

Useful for simultaneously comparing the behavior (not source) of different versions.
For example different versions of a web site or just a web page.

git worktree add folder branch


git worktree add v1 version1

git worktree list


git worktree add folder // converts current branch upto latest commit into directory and also creates a newBranch
git worktree add folder mybranch // converts specified branch into directory
git worktree add folder -b newBranch // creates directory and branch with different names
git worktree add folder -b newBranch mybranch

// It creates a new directory/tree named "kanna" and also a new branch named "kanna" based on current HEAD
// To go to this newly created branch use "cd kanna/"
git worktree add kanna

// It creates a new directory/tree named "koti" and attach "mybranch" to it. It won't create a new branch named koti.
// Now mybranch can be navigated simply "cd koti/" and HEAD is pointed to mybranch.
git worktree add koti mybranch

// It creates worktree with directory named chinna and a new branch with the name mybranch77 instead of default branch name chinna.
git worktree add chinna -b mybranch77

// It throws an error as mybranch is already attached to koti worktree above.


// This is to prevent accidentlly creating new worktree based on the same branch.
git worktree add chinna2 mybranch

// It will create a new worktree based on mybranch, eventhough mybranch already attached to koti worktree.
It basically overcomes the above limitation
git worktree add chinna2 -b chinna2 mybranch

### List worktrees


git worktree list

### Clean worktree


rm -rf folder
git worktree prune
rm -rf .git/worktrees/folder/

### worktree use case example


[Link]

## Submodules vs Worktree
submodules are meant for linking external repos
worktrees are meant for viewing branches as directories

### TimeStamps
when you clone a project, all files will have timestamps of cloning time in local machine
They won't get remote reposity file timestamps.
If you wan't sync files to remote service like AWS-S3 which syncs based on created and modified timestamps
and file sizes. This can lead to problems like uploading same files again and again.
To overcome this, one may use below bash script OR etags
### Syncing data based on changes in data to remote AWS S3 for satic site generators like Hugo
* [Link]
```bash
#!/bin/bash
set -ex

FILES=()
for i in $( git status -s | sed 's/\s*[a-zA-Z?]\+ \(.*\)/\1/' ); do
FILES+=( "$i" )
done
#echo "${FILES[@]}"

CMDS=()
for i in "${FILES[@]}"; do
CMDS+=("--include=$i""*")
done
#echo "${CMDS[@]}"

echo "${CMDS[@]}" | xargs aws s3 sync . s3://[Link] --dryrun --delete --exclude "*"
```
The above code is more like hack.
Proper way todo this is to create etag(EntityTag) for all local files using crypto/md5
AWS S3 automatically creates etags for uploaded files.
Compare localetags with awsetags identify New/Modified/Deleted files
And sync them using aws-sdk

### Workflow when you submit a Pull request


```
// Create a new branch out of master
git checkout -b myBranch

// make some changes and do commit

git add .
git commit -m ‘kkkk’

// make some more changes and commit

git add .
git commit -m ‘kkkk’

// Now rebase against master branch to merge commits as single commit

git rebase -i master

Now pick top most commit and squash rest


And add final commit message

And send a pull request.

Repo Main Author does below:


// Review
git fetch myBranch
git checkout myBranch
git status
git diff

// Merge
git checkout master
git merge myBranch

// short hand for fetch and merge commands


git pull myBranch
```

### To download a single file from git

#### Using git and ssh


```
git archive --remote=ssh://[Link]/ekanna/[Link] master [Link] | tar -x
```

#### Using wget and password


```
wget --user=ekanna --ask-password [Link]
OR
wget --user=ekanna --password=SUPERSECRET [Link]
```
Notice ```src``` replaced with ```raw``` in the path

### git url with and without password


```
git clone [Link]
git clone [Link]
```
It will prompt you for your password.

Common questions

Powered by AI

'Git revert' is used for remote or shared branches and creates a new commit that undoes changes from a previous commit, thereby preserving the commit history. It is considered a safe option as it allows for tracking of the changes being undone . Conversely, 'git reset' is used for local branches as it erases history by moving the HEAD to a specified commit and discards changes after that point, effectively altering the commit history. This can potentially cause complications when working with others, as it rewrites the commit history . 'Git reset' is more suitable for local feature branches where history rewriting is not an issue, while 'git revert' should be used for commits in shared history to maintain a clear record of changes.

Git submodules are used to include and manage external repositories within a project. They are particularly useful for linking third-party modules like those in the 'vendor' directory of frameworks such as Golang or static site generators like Hugo . Submodules allow a main project to reference commits from another repository, helping to keep dependencies separated and in sync without integrating them directly . Conversely, Git worktrees enable the use of multiple branches simultaneously by checking out those branches into separate directories. This is useful for comparing different versions of a project or working on multiple features in parallel . The key difference is that submodules link external repositories, while worktrees manage multiple branches of the same repository. Submodules are ideal for dependency management, whereas worktrees improve workflow by allowing seamless switching and comparison of branches.

Git worktrees facilitate version comparison by allowing different branches of a repository to be checked out into separate directories, making it possible to view and work on different branch versions side-by-side. To create a worktree, the command 'git worktree add [directory] [branch]' is used, which checks out the specified branch into the named directory . Users can list all active worktrees with 'git worktree list' and remove them using 'git worktree prune' . This functionality can improve productivity by enabling users to work on multiple branches without switching contexts, simplify testing, and support development of features with dependencies on different branch states.

Git submodules allow one repository to include another as a subdirectory, effectively managing project dependencies by linking specific commits of the submodule. A significant aspect of managing submodules is updating or pulling changes. To ensure the submodule is updated to the latest commit, the command 'git submodule update --remote [path]' can be used, which synchronizes the submodule with the latest commit on the origin URL branch . This approach requires careful version tracking in the parent repository to avoid conflicts and version mismatches. Including submodules necessitates additional coordination for clones and updates, ensuring all collaborators synchronize appropriately, which can complicate repository management compared to a monolithic approach.

An orphan branch in Git is created using the 'git checkout --orphan [branchName]' command, resulting in a branch that does not maintain any commit history from its parent branch. Unlike a regular branch, which carries the history of commits it branched from, an orphan branch starts with the root commit, appearing as though the branch has no prior existence . This makes orphan branches useful for starting new independent projects or including code without any historical baggage from other repositories. The distinction between orphan and regular branches is in their historical ties; regular branches maintain lineage with their parent, whereas orphan branches do not.

Cloning a project with submodules using the '--recursive' option is beneficial because it automatically initializes and updates each submodule within a project, ensuring that all parts of the project and their dependencies are present and up-to-date immediately after cloning . This reduces manual post-cloning steps and ensures consistent project setup across development environments. However, a limitation is that it assumes all remote submodules are accessible and that no conflicts exist in their current state, which may not always be the case if permissions or network issues arise. Additionally, projects with extensive submodules may increase clone times and disk usage.

When cloning a project, the resulting files on the local machine receive the clone time timestamps rather than preserving the original commit timestamps. This discrepancy can lead to synchronization issues with remote services like AWS S3, which track and sync files based on timestamp and size. Consequently, files may be unnecessarily re-uploaded, as the modification time does not match the expected value . To solve this, scripts can be implemented that compare local files to those already in S3, using entity tags ('etags') to examine file changes based on content rather than modification dates. This approach relies on generating and comparing MD5 checksums rather than timestamps to determine sync eligibility properly.

Preparing and submitting a pull request typically involves the following Git commands: Create a new branch from the master with 'git checkout -b myBranch', make necessary changes, and commit them using 'git add .' followed by 'git commit -m [message]'. Use 'git rebase -i master' to squash and tidy commit history, ensuring cleaner submission . The master branch serves as the base or target branch from which the feature branch is created and against which any changes are rebased to resolve conflicts and condense changes. Finally, the pull request is submitted to merge changes back into the master, maintaining a streamlined and coherent project history.

The 'git rebase -i', or interactive rebase, allows users to edit commit history by squashing, reordering, or modifying commits before merging them into the upstream branch. This results in a cleaner and more organized commit history, making it easier for reviewers to understand changes when submitting a pull request. The steps involve checking out the branch from master, making necessary changes, and committing them. Before sending a pull request, 'git rebase -i master' is executed, enabling users to pick the primary commit to retain and squash any unnecessary commits. After finalizing the rebase, users should push the changes and request a review. This process reduces noise in the commit log and showcases the work as a single, coherent effort .

The 'git checkout -b newBranch' command combines the creation and switching of a branch into a single step, reducing the need for separate 'git branch newBranch' and 'git checkout newBranch' commands . This command enhances development workflows by streamlining branch management, saving time when context-switching between features or tasks. It allows developers to quickly create a workspace for new feature development without the overhead of multiple commands, fostering an efficient and organized workflow conducive to exploratory and agile development practices.

You might also like