From 99b08059c48cfdb7c890e1d0071beb8d0f6967ff Mon Sep 17 00:00:00 2001 From: Shihab Hasan Date: Mon, 23 Mar 2020 12:12:52 +0600 Subject: [PATCH] Checkout a specific git commit --- README.md | 2 +- pkg/buildcontext/git.go | 24 +++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2e0de1929a..44c9fdb731 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ When running kaniko, use the `--context` flag with the appropriate prefix to spe | GCS Bucket | gs://[bucket name]/[path to .tar.gz] | `gs://kaniko-bucket/path/to/context.tar.gz` | | S3 Bucket | s3://[bucket name]/[path to .tar.gz] | `s3://kaniko-bucket/path/to/context.tar.gz` | | Azure Blob Storage| https://[account].[azureblobhostsuffix]/[container]/[path to .tar.gz] | `https://myaccount.blob.core.windows.net/container/path/to/context.tar.gz` | -| Git Repository | git://[repository url][#reference] | `git://github.com/acme/myproject.git#refs/heads/mybranch` | +| Git Repository | git://[repository url][#reference][#commit-id] | `git://github.com/acme/myproject.git#refs/heads/mybranch#` | If you don't specify a prefix, kaniko will assume a local directory. For example, to use a GCS bucket called `kaniko-bucket`, you would pass in `--context=gs://kaniko-bucket/path/to/context.tar.gz`. diff --git a/pkg/buildcontext/git.go b/pkg/buildcontext/git.go index 9908350b17..4338364e8e 100644 --- a/pkg/buildcontext/git.go +++ b/pkg/buildcontext/git.go @@ -41,6 +41,28 @@ func (g *Git) UnpackTarFromBuildContext() (string, error) { if len(parts) > 1 { options.ReferenceName = plumbing.ReferenceName(parts[1]) } - _, err := git.PlainClone(directory, false, &options) + r, err := git.PlainClone(directory, false, &options) + + if err == nil && len(parts) > 2 { + // ... retrieving the commit being pointed by HEAD + _, err := r.Head() + if err != nil { + return directory, err + } + + w, err := r.Worktree() + if err != nil { + return directory, err + } + + // ... checking out to desired commit + err = w.Checkout(&git.CheckoutOptions{ + Hash: plumbing.NewHash(parts[2]), + }) + if err != nil { + return directory, err + } + } + return directory, err }