nothing serious here yet, just having fun with powershell and my nerves - but it works

Former-commit-id: ec83062ab7a588e9bfc6c42ce59834abf24723fa
This commit is contained in:
Gerasimos (Makis) Maropoulos 2019-06-24 04:49:24 +03:00
parent edbb128c68
commit c512222b9b
6 changed files with 153 additions and 47 deletions

4
.gitignore vendored
View File

@ -2,4 +2,6 @@
_authortools
.directory
node_modules
package-lock.json
package-lock.json
_benchmarks/benchmarker/benchmarker.exe
_benchmarks/benchmarker/platforms

View File

@ -10,17 +10,36 @@ import (
"github.com/kataras/golog"
)
var debug = false
var logger = golog.Default
func init() {
if len(os.Args) > 1 && os.Args[1] == "debug" {
debug = true
}
if debug {
logger.SetLevel("debug")
}
}
var bundles = []bundle{
{
names: []string{"dotnet"},
installDir: "./dotnet_bin",
installDir: "./platforms/dotnet",
installArguments: []string{"-NoPath", "-InstallDir", "$installDir", "-Channel", "Current", "-Version", "3.0.100-preview6-012264"},
},
{
names: []string{"node", "npm"},
installDir: "./node_bin",
installDir: "./platforms/node", // do no change that.
installArguments: []string{"$installDir", "12.4.0"},
},
{
names: []string{"git"},
installDir: "./platforms/git",
installArguments: []string{"-InstallDir", "$installDir"},
},
}
func install(b bundle) error {
@ -30,6 +49,8 @@ func install(b bundle) error {
return installDotnet(b)
case "node", "nodejs", "npm":
return installNode(b)
case "git":
return installGit(b)
}
}
@ -68,24 +89,30 @@ type platform struct {
executable string
}
func (p *platform) exec(args ...string) string {
func (p *platform) text(args ...string) string {
cmd := exec.Command(p.executable, args...)
b, err := cmd.Output()
if err != nil {
golog.Error(err)
logger.Error(err)
return ""
}
return string(b)
}
func (p *platform) attach(args ...string) error {
func (p *platform) exec(args ...string) error {
cmd := exec.Command(p.executable, args...)
attachCmd(cmd)
return cmd.Run()
}
func attachCmd(cmd *exec.Cmd) {
func (p *platform) attach(logLevel string, args ...string) error {
cmd := exec.Command(p.executable, args...)
attachCmd(logLevel, cmd)
return cmd.Run()
}
func attachCmd(logLevel string, cmd *exec.Cmd) {
level := golog.ParseLevel(logLevel)
outputReader, err := cmd.StdoutPipe()
if err == nil {
outputScanner := bufio.NewScanner(outputReader)
@ -93,7 +120,7 @@ func attachCmd(cmd *exec.Cmd) {
go func() {
defer outputReader.Close()
for outputScanner.Scan() {
golog.Println(outputScanner.Text())
logger.Log(level, outputScanner.Text())
}
}()
@ -103,7 +130,7 @@ func attachCmd(cmd *exec.Cmd) {
go func() {
defer errReader.Close()
for errScanner.Scan() {
golog.Println(errScanner.Text())
logger.Log(level, errScanner.Text())
}
}()
}
@ -114,6 +141,7 @@ func getPlatform(name string) (p *platform) {
for _, b := range bundles {
for _, bName := range b.names {
if bName == name {
// temporarily set the path env to the installation directories
// in order the exec.LookPath to check for programs there too.
pathEnv := os.Getenv("PATH")
@ -123,21 +151,30 @@ func getPlatform(name string) (p *platform) {
}
}
pathEnv += b.installDir + "/bin;"
pathEnv += b.installDir
os.Setenv("PATH", pathEnv)
executable, err := exec.LookPath(name)
if err != nil {
golog.Debugf("%s executable couldn't be found from PATH. Trying to install it...", name)
logger.Infof("%s executable couldn't be retrieved by PATH or PATHTEXT. Installation started...", name)
err = install(b)
if err != nil {
golog.Fatalf("unable to auto-install %s, please do it yourself: %v", name, err)
logger.Fatalf("unable to auto-install %s, please do it yourself: %v", name, err)
}
executable = b.installDir + "/" + name
if runtime.GOOS == "windows" {
executable += ".exe"
name += ".exe"
}
// first check for installDir/bin/+name before the installDir/+name to
// find the installed executable (we could return it from our scripts but we don't).
binExecutable := b.installDir + "/bin/" + name
if _, err = os.Stat(binExecutable); err == nil {
executable = binExecutable
} else {
executable = b.installDir + "/" + name
}
}
@ -148,22 +185,26 @@ func getPlatform(name string) (p *platform) {
}
}
golog.Fatalf("%s not found", name)
logger.Fatalf("%s not found", name)
return nil
}
func main() {
golog.SetLevel("debug")
dotnet := getPlatform("dotnet")
dotnetVersion := dotnet.exec("--version")
golog.Infof("Dotnet version: %s", dotnetVersion)
dotnetVersion := dotnet.text("--version")
logger.Info("Dotnet version: ", dotnetVersion)
node := getPlatform("node")
nodeVersion := node.exec("--version")
golog.Infof("Nodejs version: %s", nodeVersion)
nodeVersion := node.text("--version")
logger.Info("Nodejs version: ", nodeVersion)
npm := getPlatform("npm")
npmVersion := npm.exec("--version")
golog.Infof("NPM version: %s", npmVersion)
npmVersion := npm.text("--version")
logger.Info("NPM version: ", npmVersion)
git := getPlatform("git")
gitVersion := git.text("--version")
logger.Info("Git version: ", gitVersion)
os.Stdin.Read(make([]byte, 0))
}

View File

@ -7,7 +7,7 @@ import (
)
func sh(script string, args ...string) error {
return (&platform{"bin/sh"}).attach(append([]string{script}, args...)...)
return (&platform{"bin/sh"}).attach("debug", append([]string{script}, args...)...)
}
func installDotnet(b bundle) error {

View File

@ -2,8 +2,12 @@
package main
import "errors"
var errUnableToInstall = errors.New("unable to install")
func powershell(script string, args ...string) error {
return (&platform{"powershell"}).attach(append([]string{script}, args...)...)
return (&platform{"powershell"}).attach("debug", append([]string{script}, args...)...)
}
func installDotnet(b bundle) error {
@ -20,9 +24,15 @@ func installDotnet(b bundle) error {
// Unblock-File + script
// Solution (requires manual action):
// Right click on the ./scripts/dotnet-install.ps1 and check the "unblock" property, save and exit the dialog.
//
// -ExecutionPolicy Bypass? (not tested)
return powershell("./scripts/dotnet-install.ps1", b.parseArguments()...)
}
func installNode(b bundle) error {
return powershell("./scripts/node-install.ps1", b.parseArguments()...)
}
func installGit(b bundle) error {
return powershell("./scripts/git-install.ps1", b.parseArguments()...)
}

View File

@ -0,0 +1,40 @@
# borrowed: https://github.com/PowerShell/vscode-powershell/blob/develop/scripts/Install-VSCode.ps1
# edited to support a custom install directory and fix an issue with ssl and
# simplify the script - we don't need update only a temp installation.
param([string]$InstallDir="$env:TEMP")
If(!(test-path $InstallDir))
{
New-Item -ItemType Directory -Force -Path $InstallDir
}
$filename=-join($InstallDir, "\", "git-installer.exe")
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
foreach ($asset in (Invoke-RestMethod https://api.github.com/repos/git-for-windows/git/releases/latest).assets) {
if ($asset.name -match 'Git-\d*\.\d*\.\d*-64-bit\.exe') {
$dlurl = $asset.browser_download_url
$newver = $asset.name
}
}
try {
$ProgressPreference = 'SilentlyContinue'
Write-Host "`nDownloading latest stable git..." -ForegroundColor Yellow
Remove-Item -Force $filename -ErrorAction SilentlyContinue
Invoke-WebRequest -Uri $dlurl -OutFile $filename
Write-Host "`nInstalling git..." -ForegroundColor Yellow
Start-Process -Wait $filename -ArgumentList /VERYSILENT, /DIR="$InstallDir", \FORCECLOSEAPPLICATIONS
# or SILENT
Write-Host "`nInstallation complete!`n`n" -ForegroundColor Green
}
finally {
$ProgressPreference = 'Continue'
}
$s = get-process ssh-agent -ErrorAction SilentlyContinue
if ($s) {$true}

View File

@ -1,38 +1,51 @@
$INSTALL_DIR=$args[0]
[cmdletbinding()]
$Install_Dir=$args[0]
$VERSION=$args[1]
# param([String]$VERSION="12.4.0",[String]$INSTALL_DIR="../nodejs_bin")
If(!(test-path $INSTALL_DIR))
$Install_Dir=[System.IO.Path]::GetFullPath($Install_Dir)
If(!(test-path $Install_Dir))
{
New-Item -ItemType Directory -Force -Path $INSTALL_DIR
New-Item -ItemType Directory -Force -Path $Install_Dir
}
function Say($str) {
Write-Host "node-install: $str"
}
$url = "https://nodejs.org/dist/v$VERSION/node-v$VERSION-x64.msi"
# i.e https://nodejs.org/dist/v10.16.0/node-v10.16.0-x64.msi
write-host "`n----------------------------"
write-host " downloading node "
write-host "----------------------------`n"
write-host "url : $url"
# Say "----------------------------"
# Say " downloading node "
# Say "----------------------------"
# Say "url : $url"
$filename = "node.msi"
$node_msi = "$INSTALL_DIR\$filename"
$node_msi = "$Install_Dir\$filename"
$start_time = Get-Date
$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $node_msi)
write-Output "Download of $filename finished at: $((Get-Date).Subtract($start_time).Seconds) second(s)"
# Say "Download of $filename finished at: $((Get-Date).Subtract($start_time).Seconds) second(s)"
write-host "`n----------------------------"
write-host " installing node "
write-host "----------------------------`n"
# Say "---------------------------"
# Say " installing node "
# Say "---------------------------"
$node_msi = $node_msi.substring(2)
# Say $node_msi
$INSTALL_DIR=[System.IO.Path]::GetFullPath($INSTALL_DIR)
write-host "installation directory: $INSTALL_DIR"
# $Install_Dir = $Install_Dir.replace("\","/")
$params = '/i', "$node_msi",
'INSTALLDIR="$INSTALL_DIR"',
'/qn',
'/norestart'
$p = Start-Process 'msiexec.exe' -ArgumentList $params -Wait -PassThru
# Say "installation directory: $Install_Dir"
# $params = '/i', "$node_msi",
# 'INSTALLDIR="$Install_Dir"',
# '/qn',
# '/norestart'
# # '/log $Install_Dir\install.log'
# $p = Start-Process 'msiexec.exe' -ArgumentList $params -PassThru -Wait
# Start-Process 'msiexec.exe' -ArgumentList '/i', "$node_msi", "INSTALLDIR=$Install_Dir", '/norestart' -Wait -PassThru
Start-Process -Wait 'msiexec.exe' -ArgumentList '/i', $node_msi, "INSTALLDIR=$Install_Dir", '/passive'