import fs = require ( "fs-extra" ) ; import * as tl from "azure-pipelines-task-lib/task" ; import * as path from "path" ; import * as toolLib from "azure-pipelines-tool-lib/tool" ; import { downloadFile , getTempPath , detar } from "./util" ; let yarnVersionsFile = path . join ( getTempPath ( ) , "yarnVersions.json" ) ; async function queryLatestMatch ( versionSpec , includePrerelease ) { await downloadFile ( "https://publicblobs.geeklearning.io/yarn/tarballsV2.json" , yarnVersionsFile ) ; let yarnVersions = JSON . parse ( fs . readFileSync ( yarnVersionsFile , { encoding : "utf8" } ) ) as { [ key ] : { uri : string ; isPrerelease : boolean ; } ; } ; let versionsCodes = Object . keys ( yarnVersions ) ; if ( ! includePrerelease ) { versionsCodes = versionsCodes . filter ( v => ! yarnVersions [ v ] . isPrerelease ) ; } let version = toolLib . evaluateVersions ( versionsCodes , versionSpec ) ; if ( ! version ) { return undefined ; } return { version : version , url : yarnVersions [ version ] . uri } ; } async function downloadYarn ( version ) { let cleanVersion = toolLib . cleanVersion ( version . version ) ; let downloadPath = path . join ( getTempPath ( ) , `yarn-${ cleanVersion }.tar.gz` ) ; await downloadFile ( version . url , downloadPath ) ; let detarLocation = path . join ( getTempPath ( ) , "yarn-output" ) ; fs . emptyDirSync ( detarLocation ) ; await detar ( downloadPath , detarLocation ) ; return await toolLib . cacheDir ( detarLocation , "yarn" , cleanVersion ) ; } async function getYarn ( versionSpec , checkLatest , includePrerelease ) { if ( toolLib . isExplicitVersion ( versionSpec ) ) { checkLatest = false ; } let toolPath ; if ( ! checkLatest ) { toolPath = toolLib . findLocalTool ( "yarn" , versionSpec ) ; } if ( ! toolPath ) { let version ; if ( toolLib . isExplicitVersion ( versionSpec ) ) { version = await queryLatestMatch ( versionSpec , true ) ; } else { version = await queryLatestMatch ( versionSpec , includePrerelease ) ; tl . debug ( "Matched version: " + version . version ) ; if ( ! version ) { throw new Error ( `Unable to find Yarn version '${ versionSpec }'.` ) ; } toolPath = toolLib . findLocalTool ( "yarn" , version . version ) ; } if ( ! toolPath ) { tl . debug ( "Downloading tarball: " + version . url ) ; toolPath = await downloadYarn ( version ) ; } toolLib . prependPath ( toolPath ) ; } let matches = tl . findMatch ( toolPath , [ "**/bin/yarn.cmd" ] ) ; if ( matches . length ) { toolPath = path . dirname ( matches [ 0 ] ) ; } else { throw new Error ( "Yarn package layout unexpected." ) ; } toolLib . prependPath ( toolPath ) ; } async function run ( ) { try { let versionSpec = tl . getInput ( "versionSpec" , true ) ; let checkLatest = tl . getBoolInput ( "checkLatest" , false ) ; let includePrerelease = tl . getBoolInput ( "includePrerelease" , false ) ; await getYarn ( versionSpec , checkLatest , includePrerelease ) ; } catch ( error ) { tl . setResult ( tl . TaskResult . Failed , error . message ) ; } } run ( ) ;