package healthcheck import ( "bufio" "fmt" "os" "path/filepath" ) // fileExists checks if a file exists at the specified path. func fileExists(filePath string) bool { _, err := os.Stat(filePath) return !os.IsNotExist(err) } // filesMatch checks if two files are identical. func filesMatch(file1, file2 string) (bool, error) { f1, err := os.Open(file1) if err != nil { return false, err } defer f1.Close() f2, err := os.Open(file2) if err != nil { return false, err } defer f2.Close() scanner1 := bufio.NewScanner(f1) scanner2 := bufio.NewScanner(f2) for scanner1.Scan() && scanner2.Scan() { line1 := scanner1.Text() line2 := scanner2.Text() if line1 != line2 { return false, nil } } if scanner1.Scan() || scanner2.Scan() { // One file has more lines than the other return false, nil } return true, nil } // compareDirectories compares the contents of two directories. func compareDirectories(dir1, dir2 string, jsonOut *CheckStage) error { allMatch := true var message string err := filepath.Walk(dir1, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() { relPath, _ := filepath.Rel(dir1, path) file2 := filepath.Join(dir2, relPath) if !fileExists(file2) { // fmt.Printf("File %s in %s is missing in %s\n, please immediately revert your changes!\n", relPath, dir1, dir2) message += "File missing" allMatch = false jsonOut.StdOut += "Failed" jsonOut.ExitCode = 101 jsonOut.StdErr = message return nil } // fmt.Printf("Checking integrity of %s:\n", path) match, err := filesMatch(path, file2) if err != nil { return err } if !match { // fmt.Printf("File %s in %s is not identical to %s\nPlease revert your changes or contact the teaching team if you have a valid reason for adjusting them.\n", relPath, dir1, dir2) message += "File is not identical" allMatch = false jsonOut.StdOut += "Failed" jsonOut.ExitCode = 101 jsonOut.StdErr = message } } return nil }) if allMatch { jsonOut.StdOut += "OK!" } else { jsonOut.StdOut += "Failed!" } return err } // Verify checks if the contents of two directories are identical. func Verify(rootDir, compareDir string) CheckStage { jsonOut := CheckStage{ Name: "verifyFile", StdOut: "Checking files to be verified: ", ExitCode: 0, StdErr: "", } err := compareDirectories(rootDir, compareDir, &jsonOut) // fmt.Println("Comparison finished ") if err != nil { fmt.Println("Error:", err) } return jsonOut }