5
0
mirror of https://github.com/wailsapp/wails.git synced 2025-05-02 23:51:44 +08:00
wails/cmd/helpers.go
Lea Anthony 79188c503f
Develop (#343)
* Support Distribution 'ArcoLinux' #310 (#312)

* Support Distribution 'ArcoLinux' #310

* Vuetify2 support (resurrected from git@github.com:MichaelHipp/wails.git) (#315)

* Initial create of vuetify2-basic folder

* Change template descr of vuetify-basic to say Vuetify 1.5

* Get vuetify2 template installing vuetify v2.0 (but with styling probs)

* Update App.vue, HelloWorld.vue for Vuetify v2

* Remove babel-polyfill, add mdi/font

* fix: codacy corrections

* fix: babel -> core-js, regenerator-runtime

Co-authored-by: Michael Hipp <michael@redmule.com>
Co-authored-by: Lea Anthony <lea.anthony@gmail.com>

* Update Contributors

* v1.0.2-pre1

* [313-remote-conn] allow remote connections to the websocket bridge (#314)

* [313-remote-conn] feat: compute wsURL based on window.location

* [313-remote-conn] feat: allow any host to connect to vue server

removing the 'host: "localhost"' specification causes the development
server to listen on all interfaces.

* [313-remote-conn] feat: allow any host to connect to angular dev server

* test: reinject tabs

Co-authored-by: Lea Anthony <lea.anthony@gmail.com>

* fix: disable host check for vuetify 2 template

* v1.0.2-pre2

* fix: shutdown ipcmanager

* use channel to trigger shutdown

* load linuxdb from relative path

* Feat manjaro arm & deepin (#324)

* feat: new distros: manjaroARM & Deepin

* v1.0.2-pre3

* [326-platform-raspbian] feat: implement raspbian support (#327)

* fix: emit arguments (#306)

* v1.0.2-pre4 Raspbarian support

* Initial support for Typescript decl file (#330)

* v1.0.2-pre5

* revert to Go 1.12

* New CI (#331)

* prepare

* new CI/github actions

* Rename later-pre.yml to latest-pre.yml

* Update latest-pre.yml

* Update README.md

* Ensure version in go.mod is up to date (#339)

* release v1.0.2-pre6

* Fix typescript generation

* Release v1.0.2-pre7

* 316-multi-bridge-conn (#317)

* [316-multi-bridge-conn] feat: use callback func for bridge response

* [316-multi-bridge-conn] feat: implement multiple session support

* split client handling portion into 'session'
* keep track of sessions by remote address (ip & port)
* notify each of the sessions anytime an event comes across the bus

* [316-multi-bridge-conn] chore: move bridge files to package

* [316-multi-bridge-conn] chore: remove deprecated Callback function

The Callback function is no longer needed for the operation of
the frontend callback since the ipc.Dispatch function now requires
a callback function to be provided as an argument.
This function can be a private function since it is passed by reference.

* [316-multi-bridge-conn] chore: make webview.Callback private

* [316-multi-bridge-conn] chore: remove unused injectCSS function

I believe a slightly better method of doing this might need to be devised
if it is needed in the future. I presume it should collect the values
into a cache and then inject it into each sesssion as it appears.

* [316-multi-bridge-conn] ensure wails:ready event is emitted

Event is only emitted for the first session created from the Bridge.

* [316-multi-bridge-conn] emit events for session lifecycle

Emit an event for each session started and ended.

* [316-multi-bridge-conn] fix: session handling fixes

Co-authored-by: Lea Anthony <lea.anthony@gmail.com>

* Release v1.0.2-pre8

* Release v1.0.2

Co-authored-by: Byron <ktc@protonmail.com>
Co-authored-by: Travis McLane <tmclane@gmail.com>
Co-authored-by: Michael Hipp <michael@redmule.com>
2020-02-08 09:58:16 +11:00

344 lines
8.8 KiB
Go

package cmd
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/leaanthony/mewn"
"github.com/leaanthony/slicer"
"github.com/leaanthony/spinner"
)
var fs = NewFSHelper()
// ValidateFrontendConfig checks if the frontend config is valid
func ValidateFrontendConfig(projectOptions *ProjectOptions) error {
if projectOptions.FrontEnd.Dir == "" {
return fmt.Errorf("Frontend directory not set in project.json")
}
if projectOptions.FrontEnd.Build == "" {
return fmt.Errorf("Frontend build command not set in project.json")
}
if projectOptions.FrontEnd.Install == "" {
return fmt.Errorf("Frontend install command not set in project.json")
}
if projectOptions.FrontEnd.Bridge == "" {
return fmt.Errorf("Frontend bridge config not set in project.json")
}
return nil
}
// InstallGoDependencies will run go get in the current directory
func InstallGoDependencies() error {
depSpinner := spinner.New("Ensuring Dependencies are up to date...")
depSpinner.SetSpinSpeed(50)
depSpinner.Start()
err := NewProgramHelper().RunCommand("go get")
if err != nil {
depSpinner.Error()
return err
}
depSpinner.Success()
return nil
}
// BuildApplication will attempt to build the project based on the given inputs
func BuildApplication(binaryName string, forceRebuild bool, buildMode string, packageApp bool, projectOptions *ProjectOptions) error {
// Generate Windows assets if needed
if runtime.GOOS == "windows" {
cleanUp := !packageApp
err := NewPackageHelper().PackageWindows(projectOptions, cleanUp)
if err != nil {
return err
}
}
// Check Mewn is installed
err := CheckMewn()
if err != nil {
return err
}
compileMessage := "Packing + Compiling project"
if buildMode == BuildModeDebug {
compileMessage += " (Debug Mode)"
}
packSpinner := spinner.New(compileMessage + "...")
packSpinner.SetSpinSpeed(50)
packSpinner.Start()
buildCommand := slicer.String()
buildCommand.Add("mewn")
if buildMode == BuildModeBridge {
// Ignore errors
buildCommand.Add("-i")
}
buildCommand.Add("build")
if binaryName != "" {
// Alter binary name based on OS
switch runtime.GOOS {
case "windows":
if !strings.HasSuffix(binaryName, ".exe") {
binaryName += ".exe"
}
default:
if strings.HasSuffix(binaryName, ".exe") {
binaryName = strings.TrimSuffix(binaryName, ".exe")
}
}
buildCommand.Add("-o", binaryName)
}
// If we are forcing a rebuild
if forceRebuild {
buildCommand.Add("-a")
}
// Setup ld flags
ldflags := "-w -s "
if buildMode == BuildModeDebug {
ldflags = ""
}
// Add windows flags
if runtime.GOOS == "windows" && buildMode == BuildModeProd {
ldflags += "-H windowsgui "
}
ldflags += "-X github.com/wailsapp/wails.BuildMode=" + buildMode
// If we wish to generate typescript
if projectOptions.typescriptDefsFilename != "" {
cwd, err := os.Getwd()
if err != nil {
return err
}
filename := filepath.Join(cwd, projectOptions.FrontEnd.Dir, projectOptions.typescriptDefsFilename)
ldflags += " -X github.com/wailsapp/wails/lib/binding.typescriptDefinitionFilename=" + filename
}
buildCommand.AddSlice([]string{"-ldflags", ldflags})
err = NewProgramHelper().RunCommandArray(buildCommand.AsSlice())
if err != nil {
packSpinner.Error()
return err
}
packSpinner.Success()
// packageApp
if packageApp {
err = PackageApplication(projectOptions)
if err != nil {
return err
}
}
return nil
}
// PackageApplication will attempt to package the application in a platform dependent way
func PackageApplication(projectOptions *ProjectOptions) error {
// Package app
message := "Generating .app"
if runtime.GOOS == "windows" {
err := CheckWindres()
if err != nil {
return err
}
message = "Generating resource bundle"
}
packageSpinner := spinner.New(message)
packageSpinner.SetSpinSpeed(50)
packageSpinner.Start()
err := NewPackageHelper().Package(projectOptions)
if err != nil {
packageSpinner.Error()
return err
}
packageSpinner.Success()
return nil
}
// BuildFrontend runs the given build command
func BuildFrontend(buildCommand string) error {
buildFESpinner := spinner.New("Building frontend...")
buildFESpinner.SetSpinSpeed(50)
buildFESpinner.Start()
err := NewProgramHelper().RunCommand(buildCommand)
if err != nil {
buildFESpinner.Error()
return err
}
buildFESpinner.Success()
return nil
}
// CheckMewn checks if mewn is installed and if not, attempts to fetch it
func CheckMewn() (err error) {
programHelper := NewProgramHelper()
if !programHelper.IsInstalled("mewn") {
buildSpinner := spinner.New()
buildSpinner.SetSpinSpeed(50)
buildSpinner.Start("Installing Mewn asset packer...")
err := programHelper.InstallGoPackage("github.com/leaanthony/mewn/cmd/mewn")
if err != nil {
buildSpinner.Error()
return err
}
buildSpinner.Success()
}
return nil
}
// CheckWindres checks if Windres is installed and if not, aborts
func CheckWindres() (err error) {
if runtime.GOOS != "windows" {
return nil
}
programHelper := NewProgramHelper()
if !programHelper.IsInstalled("windres") {
return fmt.Errorf("windres not installed. It comes by default with mingw. Ensure you have installed mingw correctly")
}
return nil
}
// InstallFrontendDeps attempts to install the frontend dependencies based on the given options
func InstallFrontendDeps(projectDir string, projectOptions *ProjectOptions, forceRebuild bool, caller string) error {
// Install frontend deps
err := os.Chdir(projectOptions.FrontEnd.Dir)
if err != nil {
return err
}
// Check if frontend deps have been updated
feSpinner := spinner.New("Ensuring frontend dependencies are up to date (This may take a while)")
feSpinner.SetSpinSpeed(50)
feSpinner.Start()
requiresNPMInstall := true
// Read in package.json MD5
fs := NewFSHelper()
packageJSONMD5, err := fs.FileMD5("package.json")
if err != nil {
return err
}
const md5sumFile = "package.json.md5"
// If node_modules does not exist, force a rebuild.
nodeModulesPath, err := filepath.Abs(filepath.Join(".", "node_modules"))
if err != nil {
return err
}
if !fs.DirExists(nodeModulesPath) {
forceRebuild = true
}
// If we aren't forcing the install and the md5sum file exists
if !forceRebuild && fs.FileExists(md5sumFile) {
// Yes - read contents
savedMD5sum, err := fs.LoadAsString(md5sumFile)
// File exists
if err == nil {
// Compare md5
if savedMD5sum == packageJSONMD5 {
// Same - no need for reinstall
requiresNPMInstall = false
feSpinner.Success("Skipped frontend dependencies (-f to force rebuild)")
}
}
}
// Md5 sum package.json
// Different? Build
if requiresNPMInstall || forceRebuild {
// Install dependencies
err = NewProgramHelper().RunCommand(projectOptions.FrontEnd.Install)
if err != nil {
feSpinner.Error()
return err
}
feSpinner.Success()
// Update md5sum file
ioutil.WriteFile(md5sumFile, []byte(packageJSONMD5), 0644)
}
// Install the runtime
err = InstallRuntime(caller, projectDir, projectOptions)
if err != nil {
return err
}
// Build frontend
err = BuildFrontend(projectOptions.FrontEnd.Build)
if err != nil {
return err
}
return nil
}
// InstallRuntime installs the correct runtime for the type of build
func InstallRuntime(caller string, projectDir string, projectOptions *ProjectOptions) error {
if caller == "build" {
return InstallProdRuntime(projectDir, projectOptions)
}
return InstallBridge(projectDir, projectOptions)
}
// InstallBridge installs the relevant bridge javascript library
func InstallBridge(projectDir string, projectOptions *ProjectOptions) error {
bridgeFileData := mewn.String("../runtime/assets/bridge.js")
bridgeFileTarget := filepath.Join(projectDir, projectOptions.FrontEnd.Dir, "node_modules", "@wailsapp", "runtime", "init.js")
err := fs.CreateFile(bridgeFileTarget, []byte(bridgeFileData))
return err
}
// InstallProdRuntime installs the production runtime
func InstallProdRuntime(projectDir string, projectOptions *ProjectOptions) error {
prodInit := mewn.String("../runtime/js/runtime/init.js")
bridgeFileTarget := filepath.Join(projectDir, projectOptions.FrontEnd.Dir, "node_modules", "@wailsapp", "runtime", "init.js")
err := fs.CreateFile(bridgeFileTarget, []byte(prodInit))
return err
}
// ServeProject attempts to serve up the current project so that it may be connected to
// via the Wails bridge
func ServeProject(projectOptions *ProjectOptions, logger *Logger) error {
go func() {
time.Sleep(2 * time.Second)
logger.Green(">>>>> To connect, you will need to run '" + projectOptions.FrontEnd.Serve + "' in the '" + projectOptions.FrontEnd.Dir + "' directory <<<<<")
}()
location, err := filepath.Abs(projectOptions.BinaryName)
if err != nil {
return err
}
logger.Yellow("Serving Application: " + location)
cmd := exec.Command(location)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return err
}
return nil
}