LoginSignup
5
6

More than 1 year has passed since last update.

【備忘録】現場でのGitの運用【SourceTreeの使い方】

Posted at

はじめに

現場で初めてGitを使ったので備忘録としてまとめます。
SourceTreeの使い方がメインになります。
今までプログラミングスクールでGitコマンドでのチーム開発をしたり、同期とEclipseのGUIで操作したことはありましたが、SourceTreeは初めてで慣れるまでに少し時間がかかりました。

環境

・Windows11 Home
・SourceTree v3.4.10
※今回はASP.NET Core MVCのアプリをGit管理します

前提

・Git、SourceTreeがインストールされていること
・GitHubアカウントがあること
・Gitの基礎知識があること

最初の設定(管理者)

今回の現場は新規プロジェクトで新規作成から経験したので記載します。
個人開発の場合などに参考にしてください。

新規リポジトリ作成

①「ファイル」→「新規/クローンを作成する」→「Create」を選択
image.png
②「保存先のパス」にGit管理したいプロジェクトのパスを選択
image.png
③「作成」をクリック
すでに作成済みのフォルダなので以下のようなエラーが出るかもしれませんが「はい」で問題ありません。
image.png

※ASP.NETで作成する場合の注意点

RailsやSpringBootでは意識したことなかったのですが、ASP.NETの場合余計なファイルもたくさんコミットされてしまうので、最初に.gitignoreファイルをコミットする必要があります。
image.png
gitignoreファイルはVisualStudioのパッケージマネージャーコンソールに以下のコマンドを実行すると、プロジェクトに合わせたgitignoreファイルを自動生成してくれます。

dotnet new gitignore
ちなみに.NET Core 7.0で作成されたgitignoreファイルは以下でした。
.gitignore
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore

# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Mono auto generated files
mono_crash.*

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/

# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# Visual Studio 2017 auto generated files
Generated\ Files/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

# Benchmark Results
BenchmarkDotNet.Artifacts/

# .NET
project.lock.json
project.fragment.lock.json
artifacts/

# Tye
.tye/

# ASP.NET Scaffolding
ScaffoldingReadMe.txt

# StyleCop
StyleCopReport.xml

# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb

# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap

# Visual Studio Trace Files
*.e2e

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json

# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info

# Visual Studio code coverage results
*.coverage
*.coveragexml

# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj

# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/

# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets

# Microsoft Azure Build Output
csx/
*.build.csdef

# Microsoft Azure Emulator
ecf/
rcf/

# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload

# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/

# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs

# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk

# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak

# SQL Server files
*.mdf
*.ldf
*.ndf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl

# Microsoft Fakes
FakesAssemblies/

# GhostDoc plugin setting file
*.GhostDoc.xml

# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt

# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw

# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp

# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp

# Visual Studio 6 technical files
*.ncb
*.aps

# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions

# Paket dependency manager
.paket/paket.exe
paket-files/

# FAKE - F# Make
.fake/

# CodeRush personal settings
.cr/personal

# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config

# Tabs Studio
*.tss

# Telerik's JustMock configuration file
*.jmconfig

# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

# OpenCover UI analysis results
OpenCover/

# Azure Stream Analytics local run output
ASALocalRun/

# MSBuild Binary and Structured Log
*.binlog

# NVidia Nsight GPU debugger configuration file
*.nvuser

# MFractors (Xamarin productivity tool) working folder
.mfractor/

# Local History for Visual Studio
.localhistory/

# Visual Studio History (VSHistory) files
.vshistory/

# BeatPulse healthcheck temp database
healthchecksdb

# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/

# Ionide (cross platform F# VS Code tools) working folder
.ionide/

# Fody - auto-generated XML schema
FodyWeavers.xsd

# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace

# Local History for Visual Studio Code
.history/

# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp

# JetBrains Rider
*.sln.iml

##
## Visual studio for Mac
##


# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/

# Mac bundle stuff
*.dmg
*.app

# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Dump file
*.stackdump

# Folder config file
[Dd]esktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp

# Windows shortcuts
*.lnk

インデックスに追加(git add)

先に.gitignoreファイルだけコミットします。
「作業ツリーのファイル」の「選択をインデックスに追加」をクリック
image.png
「Indexにステージしたファイル」に移動していることを確認
image.png

コミットする(git commit)

今は下にコミット欄が出ていますが、左上の「コミット」をクリックすると出てきます。
コメントを記載し、「コミット」ボタンでコミットされます。
コミット後が以下です。
image.png

全てのファイルをインデックスに追加する

これでgit管理が不要なファイルは省かれましたので、全てのファイルをインデックスに追加します。
「全てインデックスに追加」クリックであとは同様です。
Indexにステージしたファイルは「インデックスから除く」ボタンで除くこともできます。
全てコミットしたのが以下です。
image.png

リモートの設定をする

プッシュの前に、まだリモートの設定をしていないので設定をします。
①GitHubでリポジトリを新規作成する
image.png
②SorceTreeにて「設定」→「追加」クリック
image.png
③以下を入力
・「URL/パス」に先ほどGitHubで作成したURLを貼り付け
・「リモート名」は「デフォルトリモート」にチェック
 ※リモート名はリポジトリ名と勘違いして入力していましたが違いました。。
・Remote Accountに自分のGitHubを選択
image.png
入力後がこちら
image.png
④「OK」で設定完了
image.png

プッシュする(git push)

左上の「プッシュ」で以下が出るので、チェックを確認して「プッシュ」をクリックします。
image.png
個人開発ではいつもこれが出るのですが、特に変更なく「Select」をクリックしています。
image.png

ブランチを切る(git branch)

これで新規プロジェクト作成ができたので、開発用のブランチを切ります。
今の現場は以下のようにブランチを分けています。
master
└develop
 └feature/統合用
 ├feature/個人名
  :
developはテスト完了後に最終的にプッシュするそうです。
画面ごとや機能ごとでブランチを切ったりもしていましたが人ごとになりました。
別で一つ統合用のブランチがあり、自分のブランチにプッシュした後に統合用にもプッシュして一つにまとめます。
※featureは「フィーチャー」と読みます。「フューチャー」に聞こえて、「future」とブランチを作成しまったことがあります。

①「ブランチ」をクリック
②「新規ブランチ」にブランチ名を入れて、「新規ブランチを作成してチェックアウト」にチェックを入れたまま「ブランチを作成」をクリック
image.png

メンバーの作業

クローンする(git clone)

①「ファイル」→「新規/クローンを作成する」をクリック(「Clone」が表示されているはず)
image.png
②「元のパス」にGitHubのリポジトリURL、「保存先のパス」に保存したい任意の場所を選択
③「クローン」をクリック

※エラーが出る場合

現場ではエラーが出たのですが認証のエラーでした。
現場の端末が特殊だと思うのですが、シャットダウンのたびに.gitconfigファイルが削除されてしまい、毎回作成しなければなりませんでした。
(プッシュやプルでも同じエラーが出ることがありますが同様の問題でした)
そのときに必要なコマンド

$ git config --global http.sslVerify false

もしくは.gitconfigファイル(「C:\Users\ユーザ名」にあるはず)に以下を追加

[http]
   sslVerify = false

※今回の個人開発ではSSL証明を使っていないので出ません

ブランチを切る(git branch)

①developブランチに切り替えてある状態で「ブランチ」クリック
②その他は同様で、ブランチ名を入れて「ブランチを作成」クリック
image.png

コミット・プッシュする

image.png
ステージ追加、コミット、自分のブランチへのプッシュまでは先ほどと同様のため省略します。
注意点として、プッシュする際は自分のブランチだけにチェックが入っていること確認
image.png
今の現場ではその後、統合ブランチに切り替え、自分の変更をマージします。
手順としては以下になります。

最新のソースを取り込む 

最新の履歴を確認する(git fetch)

自分の変更を統合ブランチにマージする前に、最新のソースを取り込みます。
左上の「フェッチ」→「すべてのリモートからフェッチ」→「OK」
image.png
※もしSourceTree上、統合ブランチの前回履歴が自分の場合でも、画面上に反映されていない場合があるので、毎回フェッチをして確認します。
プルをせずマージして履歴があった場合、エラーが出てマージの取り消しをしなければならないのでめんどくさいです。

最新のソースをローカルに取り込む(git pull)

左上の「プル」→「プル」ボタンをクリック(オプションのコミットするチェックは外しています)。
そうすると自分のローカル上のファイル(今回の場合はVisual Studio)に最新のソースが反映されます。
※現場の手順書に「プルをするな」と書いてあって混乱したのですが、プルをしないと自分のローカルに取り込めません。

マージする(git merge)

自分のブランチにプッシュした内容を統合ブランチにマージします。
①左上の「マージ」をクリック
②取り込みたい履歴を選択し「OK」クリック(オプションのコミットするチェックは外しています)
image.png

※マージでエラーが発生した場合について、競合解決の後に記載しています

競合が出なければ、今までと同様にコミット・プッシュします。
※統合用ブランチにプッシュした後は忘れずに自分のブランチに切り替える

競合がある場合コミット時に黄色いビックリマークが出ます。
image.png

競合解決

セッション情報を書いたファイルやプロジェクトファイル等、複数人が同じファイルに変更を加える場合競合が発生します。
「Indexにステージしたファイル」の黄色いビックリマークが出ているファイル右クリック→「競合を解決」→「外部のマージツールを起動」をクリック
image.png
現場だとこれでマージツールが起動するのですが、起動せずWinMergeの設定をしました。
「ツール」→「オプション」
WinMergeをインストールして「WinMergeU.exe」のパスを選択しました。
image.png
.gitconfigファイルに書く場合は以下

[difftool "sourcetree"]
	cmd = 'C:/Program Files/WinMerge/WinMergeU.exe' \"$LOCAL\" \"$REMOTE\"

右の「外部Diff」クリックでWinMergeが起動します。
image.png
慣れている現場のマージツールの方がよいのですが(最初はとても分かりづらかったですが)、オレンジ部分を修正して「表示更新」をクリックして保存し、左上が緑になればよさそうです。
[before]
image.png
[after]
image.png
ビックリマークは自動的に消えないみたいなので右クリックで解決済みにしました。作業ツリーのBACKUPファイルは不要のため右クリック→削除で削除します。
image.png
競合解決後コミット・プッシュしたのがこちらです。
マージミスがないかVisual Studio上でビルドして問題ないことを確認します。
image.png
最後に自分のブランチに切り替えて、最新をマージしプッシュします。
image.png

マージを取り消す(git reset)

例えばプルをせずマージをしてしまった時など、プルとプッシュに番号が出てエラーが出ることがあります。
その状態を作り出すのが難しかったので画像はないのですが文章だけで書きます。
戻したいところの履歴を右クリック→「現在のブランチをこのコミットまでリセット」をクリック
以下の3つを選べます。
・Sort:ローカルの変更を全てそのままにする
・Mixed:作業コピーの変更はこのままにするが、インデックスの状態はそのままにする
・Hard:全ての作業コピーの変更を破棄する
これから自分のブランチの変更をプッシュしたい場合だとSortかなと思います。
その後そのままコミット・プッシュで問題なかったはずです。
また実践する機会があったら追記します。
ちなみに「このコミットを打ち消し」は現場では使わないです。

※改行コードに気をつける

ソースレビューで改行コードについて指摘を受けました。
現場によってどの改行コードがいいとかあると思いますが、今の現場ではCRLFがよく、私のファイルはLFになっているようでした。改行コードを修正しても反映されず、以下が必要でした。
コマンド

$ git config --global core.autocrlf true

もしくは.gitconfigファイルに以下を追加

[core]
   autocrlf = true

上記設定にすると以下のようになるそうです。
・コミット時: CRLF から LF に変換
・チェックアウト時: LF から CRLF に変換
ローカルでLFなのがCRLFに変換されないのだと思って理解に少し時間がかかりました。

改行コードに気を付けないといけないことだったり、Windowsでの注意点を初めて知りました。

最後に

今までコマンドやEclipseのGUIでGit操作をしていた時よりも動きの理解ができました。
ここで書いたことしかまだ経験がないので、随時更新していけたらいいなと思います。

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6