@@ -9,6 +9,9 @@ const tc = require('@actions/tool-cache');
99const io = require ( '@actions/io' ) ;
1010const releases = require ( '@hashicorp/js-releases' ) ;
1111
12+ // Constants
13+ const CACHE_KEY = 'terraform' ;
14+
1215// arch in [arm, x32, x64...] (https://nodejs.org/api/os.html#os_os_arch)
1316// return value in [amd64, 386, arm]
1417function mapArch ( arch ) {
@@ -28,7 +31,7 @@ function mapOS (os) {
2831 return mappings [ os ] || os ;
2932}
3033
31- async function downloadCLI ( url ) {
34+ async function downloadCLI ( url , version ) {
3235 core . debug ( `Downloading Terraform CLI from ${ url } ` ) ;
3336 const pathToCLIZip = await tc . downloadTool ( url ) ;
3437
@@ -40,7 +43,24 @@ async function downloadCLI (url) {
4043 throw new Error ( `Unable to download Terraform from ${ url } ` ) ;
4144 }
4245
43- return pathToCLI ;
46+ // Cache for later
47+ const cachedPath = await tc . cacheDir ( pathToCLI , CACHE_KEY , version ) ;
48+ return cachedPath ;
49+ }
50+
51+ async function checkWrapper ( pathToCLI ) {
52+ const exeSuffix = os . platform ( ) . startsWith ( 'win' ) ? '.exe' : '' ;
53+ const target = [ pathToCLI , `terraform-bin${ exeSuffix } ` ] . join ( path . sep ) ;
54+
55+ core . debug ( 'Checking for existing wrapper' ) ;
56+
57+ const hasWrapper = io . which ( target ) ;
58+
59+ if ( hasWrapper ) {
60+ core . debug ( 'Wrapper found, skipping creation.' ) ;
61+ }
62+
63+ return hasWrapper ;
4464}
4565
4666async function installWrapper ( pathToCLI ) {
@@ -70,9 +90,6 @@ async function installWrapper (pathToCLI) {
7090 core . error ( `Unable to copy ${ source } to ${ target } .` ) ;
7191 throw e ;
7292 }
73-
74- // Export a new environment variable, so our wrapper can locate the binary
75- core . exportVariable ( 'TERRAFORM_CLI_PATH' , pathToCLI ) ;
7693}
7794
7895// Add credentials to CLI Configuration File
@@ -126,14 +143,24 @@ async function run () {
126143 throw new Error ( `Terraform version ${ version } not available for ${ platform } and ${ arch } ` ) ;
127144 }
128145
129- // Download requested version
130- const pathToCLI = await downloadCLI ( build . url ) ;
146+ // Check cache for requested version, then download if not present
147+ let pathToCLI = tc . find ( CACHE_KEY , release . version , os . arch ( ) ) ;
148+
149+ // Check to see if wrapper has been installed in a previous run
150+ const hasWrapper = pathToCLI && checkWrapper ( pathToCLI ) ;
151+
152+ if ( ! pathToCLI ) {
153+ pathToCLI = await downloadCLI ( build . url , release . version ) ;
154+ }
131155
132156 // Install our wrapper
133- if ( wrapper ) {
157+ if ( wrapper && ! hasWrapper ) {
134158 await installWrapper ( pathToCLI ) ;
135159 }
136160
161+ // Export a new environment variable, so our wrapper can locate the binary
162+ core . exportVariable ( 'TERRAFORM_CLI_PATH' , pathToCLI ) ;
163+
137164 // Add to path
138165 core . addPath ( pathToCLI ) ;
139166
0 commit comments