Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(DEV-2781): Notify Not Running in a Git Repo #990

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 46 additions & 8 deletions cmd/cmd_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func processCustomCommands(
if _, exist := existingTopLevelCommands[commandConfig.Name]; exist && topLevel {
command = existingTopLevelCommands[commandConfig.Name]
} else {
var customCommand = &cobra.Command{
customCommand := &cobra.Command{
Use: commandConfig.Name,
Short: commandConfig.Description,
Long: commandConfig.Description,
Expand Down Expand Up @@ -132,7 +132,7 @@ func processCommandAliases(
aliasCmd := strings.TrimSpace(v)
aliasFor := fmt.Sprintf("alias for '%s'", aliasCmd)

var aliasCommand = &cobra.Command{
aliasCommand := &cobra.Command{
Use: alias,
Short: aliasFor,
Long: aliasFor,
Expand Down Expand Up @@ -170,7 +170,7 @@ func preCustomCommand(
) {
var sb strings.Builder

//checking for zero arguments in config
// checking for zero arguments in config
if len(commandConfig.Arguments) == 0 {
if len(commandConfig.Steps) > 0 {
// do nothing here; let the code proceed
Expand All @@ -193,7 +193,7 @@ func preCustomCommand(
}
}

//Check on many arguments required and have no default value
// Check on many arguments required and have no default value
requiredNoDefaultCount := 0
for _, arg := range commandConfig.Arguments {
if arg.Required && arg.Default == "" {
Expand Down Expand Up @@ -310,7 +310,7 @@ func executeCustomCommand(
}

// Prepare template data
var data = map[string]any{
data := map[string]any{
"Arguments": argumentsData,
"Flags": flagsData,
}
Expand Down Expand Up @@ -458,6 +458,9 @@ func printMessageForMissingAtmosConfig(atmosConfig schema.AtmosConfiguration) {
u.LogErrorAndExit(atmosConfig, err)
}

// Check if we're at the root of a git repo. Warn if not.
verifyInsideGitRepo()

if atmosConfig.Default {
// If Atmos did not find an `atmos.yaml` config file and is using the default config
u.PrintMessageInColor("atmos.yaml", c1)
Expand Down Expand Up @@ -536,7 +539,6 @@ func CheckForAtmosUpdateAndPrintMessage(atmosConfig schema.AtmosConfiguration) {
cacheCfg.LastChecked = time.Now().Unix()
if saveErr := cfg.SaveCache(cacheCfg); saveErr != nil {
u.LogWarning(atmosConfig, fmt.Sprintf("Unable to save cache: %s", saveErr))

}
}

Expand All @@ -554,7 +556,6 @@ func handleHelpRequest(cmd *cobra.Command, args []string) {
}

func showUsageAndExit(cmd *cobra.Command, args []string) {

var suggestions []string
unknownCommand := fmt.Sprintf("Error: Unknown command: %q\n\n", cmd.CommandPath())

Expand Down Expand Up @@ -593,7 +594,7 @@ func getConfigAndStacksInfo(commandName string, cmd *cobra.Command, args []strin
checkAtmosConfig()

var argsAfterDoubleDash []string
var finalArgs = args
finalArgs := args

doubleDashIndex := lo.IndexOf(args, "--")
if doubleDashIndex > 0 {
Expand All @@ -607,3 +608,40 @@ func getConfigAndStacksInfo(commandName string, cmd *cobra.Command, args []strin
}
return info
}

// isGitRepository checks if the current directory is the root of a git repository
func isGitRepository() bool {
// Get current working directory
currentDir, err := os.Getwd()
if err != nil {
u.LogTrace(atmosConfig, fmt.Sprintf("failed to get current directory: %v", err))
return false
}

// Check if .git directory exists directly in the current directory
_, err = os.Stat(filepath.Join(currentDir, ".git"))
if err != nil {
if !os.IsNotExist(err) {
u.LogTrace(atmosConfig, fmt.Sprintf("git check failed: %v", err))
}
return false
}

return true
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using go-git for more robust Git repository detection.

The current implementation only checks for a .git directory in the current path. Using go-git would provide more reliable Git repository detection and support finding the repository root from subdirectories.

Additionally, fix the LogTrace calls which have incorrect arguments:

-		u.LogTrace(atmosConfig, fmt.Sprintf("failed to get current directory: %v", err))
+		u.LogTrace(fmt.Sprintf("failed to get current directory: %v", err))
-			u.LogTrace(atmosConfig, fmt.Sprintf("git check failed: %v", err))
+			u.LogTrace(fmt.Sprintf("git check failed: %v", err))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// isGitRepository checks if the current directory is the root of a git repository
func isGitRepository() bool {
// Get current working directory
currentDir, err := os.Getwd()
if err != nil {
u.LogTrace(atmosConfig, fmt.Sprintf("failed to get current directory: %v", err))
return false
}
// Check if .git directory exists directly in the current directory
_, err = os.Stat(filepath.Join(currentDir, ".git"))
if err != nil {
if !os.IsNotExist(err) {
u.LogTrace(atmosConfig, fmt.Sprintf("git check failed: %v", err))
}
return false
}
return true
}
// isGitRepository checks if the current directory is the root of a git repository
func isGitRepository() bool {
// Get current working directory
currentDir, err := os.Getwd()
if err != nil {
u.LogTrace(fmt.Sprintf("failed to get current directory: %v", err))
return false
}
// Check if .git directory exists directly in the current directory
_, err = os.Stat(filepath.Join(currentDir, ".git"))
if err != nil {
if !os.IsNotExist(err) {
u.LogTrace(fmt.Sprintf("git check failed: %v", err))
}
return false
}
return true
}
🧰 Tools
🪛 GitHub Check: Build (macos-latest, macos)

[failure] 617-617:
too many arguments in call to u.LogTrace


[failure] 625-625:
too many arguments in call to u.LogTrace

🪛 GitHub Check: Build (ubuntu-latest, linux)

[failure] 617-617:
too many arguments in call to u.LogTrace


[failure] 625-625:
too many arguments in call to u.LogTrace


// verifyInsideGitRepo checks if we're at the root of a git repo, if required env vars are not set
func verifyInsideGitRepo() bool {
// Skip check if either env var is set
if os.Getenv("ATMOS_BASE_PATH") != "" || os.Getenv("ATMOS_CLI_CONFIG_PATH") != "" {
return true
}

// Check if we're at the root of a git repo
if !isGitRepository() {
u.LogWarning(atmosConfig, "You're not at the root of a git repository. Atmos feels lonely outside - bring it home!\n")
milldr marked this conversation as resolved.
Show resolved Hide resolved
return false
}
milldr marked this conversation as resolved.
Show resolved Hide resolved

return true
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix LogWarning call argument.

The LogWarning call has incorrect arguments. Remove the atmosConfig argument:

-		u.LogWarning(atmosConfig, "You're not at the root of a git repository. Atmos feels lonely outside - bring it home!\n")
+		u.LogWarning("You're not at the root of a git repository. Atmos feels lonely outside - bring it home!\n")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// verifyInsideGitRepo checks if we're at the root of a git repo, if required env vars are not set
func verifyInsideGitRepo() bool {
// Skip check if either env var is set
if os.Getenv("ATMOS_BASE_PATH") != "" || os.Getenv("ATMOS_CLI_CONFIG_PATH") != "" {
return true
}
// Check if we're at the root of a git repo
if !isGitRepository() {
u.LogWarning(atmosConfig, "You're not at the root of a git repository. Atmos feels lonely outside - bring it home!\n")
return false
}
return true
}
// verifyInsideGitRepo checks if we're at the root of a git repo, if required env vars are not set
func verifyInsideGitRepo() bool {
// Skip check if either env var is set
if os.Getenv("ATMOS_BASE_PATH") != "" || os.Getenv("ATMOS_CLI_CONFIG_PATH") != "" {
return true
}
// Check if we're at the root of a git repo
if !isGitRepository() {
u.LogWarning("You're not at the root of a git repository. Atmos feels lonely outside - bring it home!\n")
return false
}
return true
}
🧰 Tools
🪛 GitHub Check: Build (macos-latest, macos)

[failure] 642-642:
too many arguments in call to u.LogWarning

🪛 GitHub Check: Build (ubuntu-latest, linux)

[failure] 642-642:
too many arguments in call to u.LogWarning

2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ func Execute() error {
u.LogErrorAndExit(schema.AtmosConfiguration{}, initErr)
}
}

var err error
// If CLI configuration was found, process its custom commands and command aliases
if initErr == nil {
Expand Down Expand Up @@ -182,7 +183,6 @@ func initCobraConfig() {
return nil
})
RootCmd.SetHelpFunc(func(command *cobra.Command, args []string) {

if !(Contains(os.Args, "help") || Contains(os.Args, "--help") || Contains(os.Args, "-h")) {
arguments := os.Args[len(strings.Split(command.CommandPath(), " ")):]
if len(command.Flags().Args()) > 0 {
Expand Down
18 changes: 18 additions & 0 deletions tests/test-cases/empty-dir.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,21 @@ tests:
stderr:
- "^$"
exit_code: 0

- name: atmos warns if not in git repo
enabled: true
snapshot: true
description: "Test that atmos warns if not run inside of a git repo"
workdir: "fixtures/scenarios/empty-dir"
command: "atmos"
args:
- version
env:
ATMOS_LOGS_LEVEL: Warning
expect:
diff: []
stdout:
- "You're not at the root of a git repository. Atmos feels lonely outside - bring it home!"
stderr:
- "^$"
exit_code: 0
2 changes: 1 addition & 1 deletion tests/test-cases/log-level-validation.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,4 @@ tests:
- '^\n👽 Atmos (\d+\.\d+\.\d+|test) on [a-z]+/[a-z0-9_]+\n\n'
stderr:
- "^$"
exit_code: 0
exit_code: 0
Loading