Skip to content

Commit

Permalink
Allow JS access to CLI flags via go STDLIB flagger
Browse files Browse the repository at this point in the history
  • Loading branch information
Nigel2392 committed May 29, 2024
1 parent 2862dbf commit f55be9f
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 22 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ QuickGo is a simple and easy to use golang command line tool for creating projec
quickgo can be installed using `go install` with the following command:

```bash
go install github.com/Nigel2392/quickgo/v2@v2.4.9
go install github.com/Nigel2392/quickgo/v2@v2.5.0
```

Optionally we provide a binary for Linux, MacOS and Windows.
Expand Down
26 changes: 18 additions & 8 deletions commands/git.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@ function main() {
// quickgo exec git tag=v1.0.0
// ...

// Make git aware of all changes.
let errD = os.exec("git add .");
if (errD.error) {
return Result(1, `Could not add files to git! ${errD.stdout}`);
return Fail(`Could not add files to git! ${errD.stdout}`);
};

if (quickgo.environ.tag === true) {
// Get the latest tag, increment the patch version and set it as the new tag.
// Only if the tag flag is set.
if (quickgo.environ.tag === true || quickgo.environ.tag === "true") {
let tagName = os.exec("git tag --sort=committerdate | tail -1").stdout;
let regex = `v(?:(\d+)\.)?(?:(\d+)\.)?(?:(\d+)\.\d+)`
let match = tagName.match(regex);
if (!match) {
return Result(1, `Could not find a valid tag to increment!`);
return Fail(`Could not find a valid tag to increment!`);
}

let major = parseInt(match[1]);
Expand All @@ -26,6 +29,7 @@ function main() {
quickgo.environ.tag = newTag;
}

// Commit changes with the message provided by the user or the default message.
if (quickgo.environ.m) {
console.info(`Committing changes with message: '${quickgo.environ.m}'`);
errD = os.exec(`git commit -m "${quickgo.environ.m}"`);
Expand All @@ -34,17 +38,22 @@ function main() {
errD = os.exec(`git commit -m "QuickGo update"`);
}
if (errD.error) {
return Result(1, `Could not commit changes to git! ${errD.stdout}`);
return Fail(`Could not commit changes to git! ${errD.stdout}`);
}

// Tag the commit with the tag provided by the user or the latest tag.
if (quickgo.environ.tag) {
console.info(`Tagging commit with tag ${quickgo.environ.tag}`);
errD = os.exec(`git tag ${quickgo.environ.tag}`);
}
if (errD.error) {
return Result(1, `Could not tag commit with tag ${quickgo.environ.tag}! ${errD.stdout}`);
return Fail(`Could not tag commit with tag ${quickgo.environ.tag}! ${errD.stdout}`);
}

// Push changes to the remote repository.
// If the origin flag is set, use it as the remote repository.
// If the tag flag is set, push tags to the remote repository.
// By default runs: git push -u origin <default-origin>
let pushStr = `git push`;
if (quickgo.environ.origin) {
console.info(`Pushing changes to remote repository`);
Expand All @@ -54,7 +63,7 @@ function main() {
// Try to get the default remote repository, should work for most cases
let d = os.exec("git symbolic-ref refs/remotes/origin/HEAD --short");
if (d.error) {
// Try fallback method
// Log a warning, let git handle the default origin
console.warn(`Could not determine default remote repository, trying fallback method ${d.stdout}`);
} else {
// Trim the origin
Expand All @@ -68,11 +77,12 @@ function main() {
pushStr += ` --tags`;
}

// Actually execute the push command.
console.info(`Executing git command: ${pushStr}`)
errD = os.exec(pushStr);
if (errD.error) {
return Result(1, `Could not push changes to remote repository! ${errD.stdout}`);
return Fail(`Could not push changes to remote repository! ${errD.stdout}`);
}

return Result(0, `QuickGo git command executed successfully!`);
return Success(`QuickGo git command executed successfully!`);
}
23 changes: 17 additions & 6 deletions commands/version.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,47 @@ function main() {
// The 'versionMapping' property must be an object with file paths as keys and regex strings as values.
// The regex strings must have a capture group to match the current version.
// The script will update the version in the files using the regex strings.


if (!quickgo.environ.v) {
return Result(1, `QuickGo version not provided in arguments: v=<version>`);
return Fail(`QuickGo version not provided in arguments: v=<version>`);
}

if (!quickgo.project) {
return Result(1, `This script must be run in a QuickGo project, or the directory for the project must be specified!`);
return Fail(`This script must be run in a QuickGo project, or the directory for the project must be specified!`);
}

if (!quickgo.project.context.versionMapping) {
return Result(1, `QuickGo version mapping not provided in '${fs.joinPath(quickgo.projectPath, 'quickgo.yaml')}' project.context`);
return Fail(`QuickGo version mapping not provided in '${fs.joinPath(quickgo.projectPath, 'quickgo.yaml')}' project.context`);
}

let version = quickgo.environ.v;
let versionMapping = quickgo.project.context.versionMapping;

// Mapping of file paths to regex strings to match and replace the current version.
const files = Object.keys(versionMapping);
for (let i = 0; i < files.length; i++) {
let file = files[i];
let regex = versionMapping[file];
let compiled = new RegExp(regex, 'g');

// Read the file content.
let content = fs.readTextFile(file);
let match = content.match(regex);

// Check if there is a match for the version in the file.
let match = compiled.exec(content);
if (!match) {
return Result(1, `Version ${version} not found in file ${file} using regex '${regex}'`);
return Fail(`Version ${version} not found in file ${file} using regex '${regex}'`);
}

// Replace the old version with the new version.
let oldVersion = match[1];
console.debug(`Updating version in file ${file} from ${oldVersion} to ${version}`);
content = content.replace(oldVersion, version);

// Write the updated content back to the file.
fs.writeFile(file, content);
}

return Result(0, `Updated project '${quickgo.project.name}' to version ${version}`);
return Success(`Updated project '${quickgo.project.name}' to version ${version}`);
}
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ func main() {
}

err = qg.ExecJS(
flagger.TargetDir, fn, ctx,
flagger.TargetDir, fn, args[2:], ctx,
)
if err != nil && !errors.Is(err, js.ErrExitCode) {
logger.Fatal(1, fmt.Errorf("failed to execute command: %w", err))
Expand Down
20 changes: 17 additions & 3 deletions quickgo/js/js.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ func (s *Command) AddFunc(f ...VMFunc) {
s._Funcs = append(s._Funcs, f...)
}

func newResult(importance int, message string) *CommandResult {
return &CommandResult{
Importance: importance,
Message: message,
}
}

func (s *Command) Run(scriptSource string) (result *CommandResult, err error) {

var vm *goja.Runtime
Expand All @@ -106,9 +113,16 @@ func (s *Command) Run(scriptSource string) (result *CommandResult, err error) {
)

vm.Set("base64", Base64())
vm.Set("Result", func(importance int, message string) *CommandResult {
return &CommandResult{
Importance: importance,
vm.Set("Result", newResult)
vm.Set("Success", func(message string) *CommandResult {
return newResult(0, message)
})
vm.Set("Fail", func(message string) *CommandResult {
return newResult(1, message)
})
vm.Set("GoError", func(message string) error {
return &CommandError{
Importance: 1,
Message: message,
}
})
Expand Down
23 changes: 20 additions & 3 deletions quickgo/quickgo_commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package quickgo

import (
"encoding/base64"
"flag"
"fmt"
"io"
"os"
Expand All @@ -17,6 +18,16 @@ import (
"github.com/pkg/errors"
)

type flagSet struct {
*flag.FlagSet
args []string
}

func (f *flagSet) Parse() error {
logger.Debugf("Parsing flags: %v", f.args)
return f.FlagSet.Parse(f.args)
}

func (a *App) ListJSFiles() ([]string, error) {
var (
dirPath = GetQuickGoPath(config.COMMANDS_DIR)
Expand Down Expand Up @@ -88,7 +99,7 @@ func (a *App) SaveJS(path string) error {
return nil
}

func (a *App) ExecJS(targetDir string, scriptName string, args map[string]any) (err error) {
func (a *App) ExecJS(targetDir string, scriptName string, rawArgs []string, args map[string]any) (err error) {
var (
scriptPath = GetQuickGoPath(
config.COMMANDS_DIR,
Expand Down Expand Up @@ -219,7 +230,7 @@ func (a *App) ExecJS(targetDir string, scriptName string, args map[string]any) (
},
}
osModule = map[string]any{
"args": os.Args,
"args": rawArgs,
"getEnv": func(key string) string {
return os.Getenv(key)
},
Expand Down Expand Up @@ -296,7 +307,13 @@ func (a *App) ExecJS(targetDir string, scriptName string, args map[string]any) (
}
)

vm.SetParserOptions()
vm.Set("flag", &flagSet{
FlagSet: flag.NewFlagSet(
scriptName,
flag.ExitOnError,
),
args: rawArgs,
})

cmd = js.NewScript(
"main",
Expand Down

0 comments on commit f55be9f

Please sign in to comment.