2022-01-04 10:46:14 +11:00
package cheatsheet
import (
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"regexp"
"github.com/pmezard/go-difflib/difflib"
)
func Check ( ) {
2022-10-15 13:47:55 -03:00
dir := GetKeybindingsDir ( )
2022-01-04 10:46:14 +11:00
tmpDir := filepath . Join ( os . TempDir ( ) , "lazygit_cheatsheet" )
err := os . RemoveAll ( tmpDir )
if err != nil {
2022-04-03 15:19:15 -05:00
log . Fatalf ( "Error occurred while checking if cheatsheets are up to date: %v" , err )
2022-01-04 10:46:14 +11:00
}
2022-03-19 09:38:49 +11:00
err = os . Mkdir ( tmpDir , 0 o700 )
2022-01-04 10:46:14 +11:00
if err != nil {
2022-04-03 15:19:15 -05:00
log . Fatalf ( "Error occurred while checking if cheatsheets are up to date: %v" , err )
2022-01-04 10:46:14 +11:00
}
generateAtDir ( tmpDir )
defer os . RemoveAll ( tmpDir )
actualContent := obtainContent ( dir )
expectedContent := obtainContent ( tmpDir )
if expectedContent == "" {
log . Fatal ( "empty expected content" )
}
if actualContent != expectedContent {
err := difflib . WriteUnifiedDiff ( os . Stdout , difflib . UnifiedDiff {
A : difflib . SplitLines ( expectedContent ) ,
B : difflib . SplitLines ( actualContent ) ,
FromFile : "Expected" ,
FromDate : "" ,
ToFile : "Actual" ,
ToDate : "" ,
Context : 1 ,
} )
if err != nil {
2022-04-03 15:19:15 -05:00
log . Fatalf ( "Error occurred while checking if cheatsheets are up to date: %v" , err )
2022-01-04 10:46:14 +11:00
}
2022-05-08 13:31:13 +10:00
fmt . Printf ( "\nCheatsheets are out of date. Please run `%s` at the project root and commit the changes. If you run the script and no keybindings files are updated as a result, try rebasing onto master and trying again.\n" , CommandToRun ( ) )
2022-01-04 10:46:14 +11:00
os . Exit ( 1 )
}
fmt . Println ( "\nCheatsheets are up to date" )
}
func obtainContent ( dir string ) string {
re := regexp . MustCompile ( ` Keybindings_\w+\.md$ ` )
content := ""
err := filepath . WalkDir ( dir , func ( path string , d fs . DirEntry , err error ) error {
if re . MatchString ( path ) {
2022-09-13 18:11:03 +08:00
bytes , err := os . ReadFile ( path )
2022-01-04 10:46:14 +11:00
if err != nil {
2022-04-03 15:19:15 -05:00
log . Fatalf ( "Error occurred while checking if cheatsheets are up to date: %v" , err )
2022-01-04 10:46:14 +11:00
}
content += fmt . Sprintf ( "\n%s\n\n" , filepath . Base ( path ) )
content += string ( bytes )
}
return nil
} )
if err != nil {
2022-04-03 15:19:15 -05:00
log . Fatalf ( "Error occurred while checking if cheatsheets are up to date: %v" , err )
2022-01-04 10:46:14 +11:00
}
return content
}