Skip to content

Commit

Permalink
Merge branch 'HuskyBC-Go' of github.com:xxxAlvaDevxxx/HuskyBC
Browse files Browse the repository at this point in the history
  • Loading branch information
RaulCatalinas committed Jul 22, 2024
2 parents 7fa40ba + 1199e97 commit 107a6a1
Show file tree
Hide file tree
Showing 51 changed files with 4,167 additions and 949 deletions.
Binary file removed bun.lockb
Binary file not shown.
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/RaulCatalinas/HuskyBC

go 1.21.4

require github.com/toqueteos/webbrowser v1.2.0 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/toqueteos/webbrowser v1.2.0 h1:tVP/gpK69Fx+qMJKsLE7TD8LuGWPnEV71wBN9rrstGQ=
github.com/toqueteos/webbrowser v1.2.0/go.mod h1:XWoZq4cyp9WeUeak7w7LXRUQf1F1ATJMir8RTqb4ayM=
38 changes: 38 additions & 0 deletions internal/config/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package config

import (
"fmt"
"os"

"github.com/RaulCatalinas/HuskyBC/internal/constants"
"github.com/RaulCatalinas/HuskyBC/internal/handlers"
)

func printOptions() {
fmt.Print("Usage: HuskyBC [options]\n\n")
fmt.Print("Command line for easy Husky configuration\n\n")
fmt.Println("Options:")
fmt.Printf("%s \t%s \tOutput the version number\n", constants.OPTION_VERSION, constants.OPTION_VERSION_SORT)
fmt.Printf("%s \t%s \tOpen GitHub repository for collaboration\n", constants.OPTION_COLLABORATE, constants.OPTION_COLLABORATE_SORT)
fmt.Printf("%s \t%s \tStart Husky's configuration\n", constants.OPTION_BUILD, constants.OPTION_BUILD_SORT)
fmt.Printf("%s \t%s \tDisplay help for command\n\n", constants.OPTION_HELP, constants.OPTION_HELP_SORT)
}

func ConfigureOptions() {
if len(os.Args) != 2 {
printOptions()
os.Exit(0)
}
switch os.Args[1] {
case constants.OPTION_COLLABORATE_SORT, constants.OPTION_COLLABORATE:
handlers.HandlerOptionCollaborate()
case constants.OPTION_BUILD_SORT, constants.OPTION_BUILD:
handlers.HandlerOptionBuild()
case constants.OPTION_VERSION_SORT, constants.OPTION_VERSION:
fmt.Println("HuskyBC ->", constants.VERSION)
case constants.OPTION_HELP_SORT, constants.OPTION_HELP:
printOptions()
default:
printOptions()
}
}
44 changes: 44 additions & 0 deletions internal/constants/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package constants

const (
PATH_PACKAGE_JSON = "package.json"
PATH_DIR_HUSKY = ".husky"
REPOSITORY = "https://github.com/RaulCatalinas/HuskyBC"
ISSUES = REPOSITORY + "/issues"
VERSION = "1.0.0"
NPM = "npm"
YARN = "yarn"
PNPM = "pnpm"
//BUN = "bun"
UTF8_ENCODING = "UTF-8"
SPECIAL_CHARS_REGEX = "[^a-zA-Z0-9._-]"
OPTION_VERSION = "--version"
OPTION_VERSION_SORT = "-v"
OPTION_COLLABORATE = "--collaborate"
OPTION_COLLABORATE_SORT = "-co"
OPTION_BUILD = "--build"
OPTION_BUILD_SORT = "-b"
OPTION_HELP = "--help"
OPTION_HELP_SORT = "-h"
)

var PACKAGEMANAGERS = []string{NPM, YARN, PNPM /* BUN */}

var INSTALLATION_COMMANDS = map[string]string{
NPM: "install",
YARN: "add",
PNPM: "add",
/* BUN: "add", */
}

var LINT_STAGED_CONFIG = map[string]string{
NPM: "npx lint-staged",
YARN: "yarn dlx lint-staged",
PNPM: "pnpm dlx lint-staged",
/* BUN: "bunx lint-staged", */
}

var COMMITLINT_CONFIG = map[string]string{
"npm": "#!/bin/sh\n. \"$(dirname \"$0\")/_/husky.sh\"\nnpx --no-install commitlint --edit \"$1\"\n",
"yarn": "#!/bin/sh\n. \"$(dirname \"$0\")/_/husky.sh\"\nyarn commitlint --edit \"$1\"\n",
}
46 changes: 46 additions & 0 deletions internal/handlers/handlers_options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package handlers

import (
"os"
"time"

"github.com/toqueteos/webbrowser"
"github.com/RaulCatalinas/HuskyBC/internal/constants"
userinput "github.com/RaulCatalinas/HuskyBC/internal/user-input"
"github.com/RaulCatalinas/HuskyBC/internal/utils"
)

func HandlerOptionCollaborate() {
utils.WriteMessage("info", "Opening the GitHub repository...")
time.Sleep(5 * time.Millisecond)
err := webbrowser.Open(constants.REPOSITORY)
if err != nil {
utils.WriteMessage("error", utils.GetErrorMessage("Open webbrowser"))
os.Exit(1)
}
}

func HandlerOptionBuild() {
utils.CheckinFolderOrFile(constants.PATH_PACKAGE_JSON, false)

packageManagerToUse := userinput.GetPackageManager()
shouldPublishToNpm := userinput.ShouldPublishToNPM()
useCommitlint := userinput.AddCommitlint()

utils.GenerateHuskyConfig(
utils.Props{
PackageManagerToUse: packageManagerToUse,
PackageJsonPath: constants.PATH_PACKAGE_JSON,
UseCommitlint: useCommitlint,
ShouldPublishToNpm: shouldPublishToNpm,
})
if useCommitlint {
utils.GenerateCommitlintConfig(
utils.CommitlintProps{
PackageManagerToUse: packageManagerToUse,
PackageJsonPath: constants.PATH_PACKAGE_JSON,
ShouldPublishToNpm: shouldPublishToNpm,
})
}
utils.WriteMessage("success", "All tasks were completed")
}
5 changes: 5 additions & 0 deletions internal/user-input/add-commitlint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package userinput

func AddCommitlint() bool {
return ConfirmationHandler("Do you wanna add commitlint?:(y,n) ")
}
46 changes: 46 additions & 0 deletions internal/user-input/package-managers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package userinput

import (
"fmt"
"log"

"github.com/RaulCatalinas/HuskyBC/internal/constants"
)

func PrintListPackageManeger() {
for index, packageManager := range constants.PACKAGEMANAGERS {
if _, err := fmt.Printf("%d. %s\n", index, packageManager); err != nil {
log.Fatalln(err)
}
}
}

func GetPackageManager() string {
var selectedPackageManagerNumber int

if _, err := fmt.Println("Which package manager do you wanna use?"); err != nil {
log.Fatalln(err)
}

PrintListPackageManeger()

if _, err := fmt.Print("Answer: "); err != nil {
log.Fatalln(err)
}

if _, err := fmt.Scan(&selectedPackageManagerNumber); err != nil {
log.Fatalln(err)
}

if len(constants.PACKAGEMANAGERS) <= selectedPackageManagerNumber {
if _, err := fmt.Println(">> Please enter a valid index"); err != nil {
log.Fatalln(err)
}

return GetPackageManager()
}

selectedPackageManager := constants.PACKAGEMANAGERS[selectedPackageManagerNumber]

return selectedPackageManager
}
5 changes: 5 additions & 0 deletions internal/user-input/publishToNpm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package userinput

func ShouldPublishToNPM() bool {
return ConfirmationHandler("Will you publish it on npm?:(y,n) ")
}
84 changes: 84 additions & 0 deletions internal/user-input/userinput_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package userinput_test

import (
"bytes"
"os"
"testing"

"github.com/RaulCatalinas/HuskyBC/internal/constants"
userinput "github.com/RaulCatalinas/HuskyBC/internal/user-input"
)

// TestPrintListPackageManeger prueba la función PrintListPackageManeger
func TestPrintListPackageManeger(t *testing.T) {
// Guardamos la salida original de os.Stdout
oldStdout := os.Stdout

// Creamos un pipe para capturar la salida
r, w, _ := os.Pipe()
os.Stdout = w

// Llamamos a la función que queremos probar
userinput.PrintListPackageManeger()

// Cerramos el writer y restauramos os.Stdout
w.Close()
os.Stdout = oldStdout

// Leemos la salida capturada
var buf bytes.Buffer
buf.ReadFrom(r)

// Comprobamos que la salida es la esperada
expectedOutput := "0. npm\n1. yarn\n2. pnpm\n3. bun\n"
if buf.String() != expectedOutput {
t.Errorf("Expected output %q, but got %q", expectedOutput, buf.String())
}
// Imprimimos la salida del código principal para referencia
t.Logf("Output of PrintListPackageManeger: %q", buf.String())
}

// TestGetPackageManager prueba la función GetPackageManager
func TestGetPackageManager(t *testing.T) {
// Guardamos la salida original de os.Stdout y la entrada original de os.Stdin
oldStdout := os.Stdout
oldStdin := os.Stdin

// Creamos un pipe para capturar la salida
rOut, wOut, _ := os.Pipe()
os.Stdout = wOut

// Creamos un pipe para simular la entrada del usuario
rIn, wIn, _ := os.Pipe()
os.Stdin = rIn

// Escribimos la entrada simulada
wIn.WriteString("2\n")
wIn.Close()

// Llamamos a la función que queremos probar
selectedPackageManager := userinput.GetPackageManager()

// Cerramos el writer de salida y restauramos os.Stdout y os.Stdin
wOut.Close()
os.Stdout = oldStdout
os.Stdin = oldStdin

// Leemos la salida capturada
var bufOut bytes.Buffer
bufOut.ReadFrom(rOut)

// Comparamos la salida con la salida esperada
expectedOutput := "Which package manager do you wanna use?\n0. npm\n1. yarn\n2. pnpm\n3. bun\n"
if bufOut.String() != expectedOutput {
t.Errorf("Expected output %q, but got %q", expectedOutput, bufOut.String())
}

// Imprimimos la salida del código principal para referencia
t.Logf("Output of GetPackageManager: %q", bufOut.String())

expectedPackageManager := constants.PNPM
if selectedPackageManager != expectedPackageManager {
t.Errorf("Expected package manager %q, but got %q", expectedPackageManager, selectedPackageManager)
}
}
29 changes: 29 additions & 0 deletions internal/user-input/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package userinput

import (
"fmt"
"log"
)

func ConfirmationHandler(message string) bool {
var response string

if _, err := fmt.Print(message); err != nil {
log.Fatalln(err)
}

if _, err := fmt.Scan(&response); err != nil {
log.Fatalln(err)
}

if response != "y" && response != "n" {
fmt.Println(">> Please enter a valid option")
return ConfirmationHandler(message)
}

if response == "y" {
return true
}

return false
}
81 changes: 81 additions & 0 deletions internal/utils/commitlint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package utils

import (
"os"
"sync"

"github.com/RaulCatalinas/HuskyBC/internal/constants"
)

type CommitlintProps struct {
PackageManagerToUse string
PackageJsonPath string
ShouldPublishToNpm bool
}

func GenerateCommitlintConfig(commitlintProps CommitlintProps) {
defer func() {
if r := recover(); r != nil {
WriteMessage("error", GetErrorMessage("Commitlint"))
os.Exit(1)
}
}()

WriteMessage("config", "Configuring commitlint...")

InstallDependencies(InstallProps{PackageManagerToUse: commitlintProps.PackageManagerToUse, PackagesToInstall: []string{
"lint-staged",
"@commitlint/cli",
"@commitlint/config-conventional",
}})

addScript(addScriptProps{PackageJsonPath: commitlintProps.PackageJsonPath, ScriptsToAdd: []packageJsonScript{
{Key: "lint", Value: "eslint src"},
{Key: "lint:fix", Value: "eslint src --fix"},
{Key: "format", Value: "prettier src --check"},
{Key: "format:write", Value: "prettier src --write"},
}})

createCommitlintConfigFiles(commitlintProps.PackageManagerToUse)

if commitlintProps.ShouldPublishToNpm {
modifyNpmIgnore([]string{".lintstagedrc", "commitlint.config.js"})
}

WriteMessage("success", "commitlint's configuration generated successfully")
}

func createCommitlintConfigFiles(packageManagerToUse string) {
WriteMessage("info", "Creating configuration files...")

var wg sync.WaitGroup

wg.Add(1)
go func() {
defer wg.Done()
writeFile(".husky/commit-msg", []byte(constants.COMMITLINT_CONFIG[packageManagerToUse]))
}()

wg.Add(1)
go func() {
defer wg.Done()
content := "export default { extends: ['@commitlint/config-conventional'] }"
writeFile("commitlint.config.js", []byte(content))
}()

wg.Add(1)
go func() {
defer wg.Done()
content := `{
"src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}": [
"prettier src --check",
"eslint src --max-warnings 0"
]
}`
writeFile(".lintstagedrc", []byte(content))
}()

wg.Wait()

WriteMessage("success", "Configuration files (commit-msg, commitlint.config.js and .lintstagedrc) created successfully")
}
Loading

0 comments on commit 107a6a1

Please sign in to comment.