-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1141 lines (902 loc) · 27.1 KB
/
main.go
File metadata and controls
1141 lines (902 loc) · 27.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"fmt"
"net/smtp"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
bolt "go.etcd.io/bbolt"
)
// State keys for bbolt
const (
bucketName = "git_tutor_state"
stateKeyCurrentStep = "current_step"
stateKeyUsername = "git_username"
stateKeyEmail = "git_email"
stateKeyRepoPath = "repo_path"
stateKeyProgress = "progress"
stateKeyRepoCreated = "repo_created"
)
// Email configuration
const (
feedbackEmail = "contact@suvangs.tech" // Replace with your email
smtpHost = "smtp.suvangs.tech"
smtpPort = "587"
)
// Step definitions
type Step int
const (
StepWelcome Step = iota
StepCheckGit
StepSetupFolder
StepCreateFiles
StepConfigUser
StepInitRepo
StepStageFiles
StepFirstCommit
StepCheckBranch
StepAddRemote
StepPushOrigin
StepCreateBranch
StepCheckoutBranch
StepGitStatus
StepGitDiff
StepGitFetch
StepGitLog
StepCompletion
)
var stepNames = map[Step]string{
StepWelcome: "Welcome",
StepCheckGit: "Check Git Installation",
StepSetupFolder: "Create Project Folder",
StepCreateFiles: "Create Sample Files",
StepConfigUser: "Configure Git User",
StepInitRepo: "Initialize Repository",
StepStageFiles: "Stage Files",
StepFirstCommit: "Make First Commit",
StepCheckBranch: "Check Current Branch",
StepAddRemote: "Add Remote Repository",
StepPushOrigin: "Push to Origin",
StepCreateBranch: "Create New Branch",
StepCheckoutBranch: "Checkout Branch",
StepGitStatus: "Git Status",
StepGitDiff: "Git Diff",
StepGitFetch: "Git Fetch",
StepGitLog: "Git Log",
StepCompletion: "Completion & Feedback",
}
// Expected commands for each step
var expectedCommands = map[Step][]string{
StepCheckGit: {"git --version", "git version"},
StepSetupFolder: {"mkdir", "md"}, // Support both Unix and Windows
StepCreateFiles: {"touch", "echo", "skip"},
StepConfigUser: {"git config --global user.name", "git config --global user.email"},
StepInitRepo: {"git init"},
StepStageFiles: {"git add .", "git add -A", "git add --all"},
StepFirstCommit: {"git commit -m", "git commit"},
StepCheckBranch: {"git branch", "git status"},
StepAddRemote: {"git remote add"},
StepPushOrigin: {"git push -u origin", "git push origin", "git push --set-upstream"},
StepCreateBranch: {"git branch", "git checkout -b", "git switch -c"},
StepCheckoutBranch: {"git checkout", "git switch"},
StepGitStatus: {"git status"},
StepGitDiff: {"git diff"},
StepGitFetch: {"git fetch"},
StepGitLog: {"git log"},
}
// Styles
var (
titleStyle = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("#7D56F4")).
MarginTop(1).
MarginBottom(1)
successStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#04B575")).
Bold(true)
errorStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#FF0000")).
Bold(true)
infoStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#00BFFF"))
warningStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#FFA500")).
Bold(true)
boxStyle = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("#7D56F4")).
Padding(1, 2)
outputBoxStyle = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("#00BFFF")).
Padding(1, 2)
progressStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#FFD700"))
terminalStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#00FF00")).
Background(lipgloss.Color("#000000"))
promptStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#7D56F4")).
Bold(true)
)
// Feedback structure
type Feedback struct {
Rating string `json:"rating"`
Comments string `json:"comments"`
UserEmail string `json:"user_email"`
Username string `json:"username"`
Timestamp time.Time `json:"timestamp"`
}
// Model for Bubble Tea
type model struct {
currentStep Step
username string
email string
repoPath string
branchName string
logger *log.Logger
db *bolt.DB
quitting bool
message string
progress map[Step]bool
commandInput textinput.Model
outputViewport viewport.Model
gitOutput []string
lastCommand string
commandCorrect bool
width int
height int
ready bool
gitInstalled bool
repoCreated bool
}
func initialModel() model {
logger := log.NewWithOptions(os.Stderr, log.Options{
ReportTimestamp: true,
Prefix: "Git Tutor 🎓",
})
// Check if Git is installed at startup
gitInstalled := checkGitInstalled()
if !gitInstalled {
logger.Warn("Git is not installed on this system")
}
// Open bbolt database
home, _ := os.UserHomeDir()
dbPath := filepath.Join(home, ".git-tutor.db")
db, err := bolt.Open(dbPath, 0600, nil)
if err != nil {
logger.Error("Failed to open database", "error", err)
}
// Create bucket if it doesn't exist
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(bucketName))
return err
})
// Load saved state
currentStep := StepWelcome
progress := make(map[Step]bool)
username := ""
email := ""
repoPath := ""
repoCreated := false
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName))
if b == nil {
return nil
}
if v := b.Get([]byte(stateKeyCurrentStep)); v != nil {
var step int
fmt.Sscanf(string(v), "%d", &step)
currentStep = Step(step)
}
if v := b.Get([]byte(stateKeyUsername)); v != nil {
username = string(v)
}
if v := b.Get([]byte(stateKeyEmail)); v != nil {
email = string(v)
}
if v := b.Get([]byte(stateKeyRepoPath)); v != nil {
repoPath = string(v)
}
if v := b.Get([]byte(stateKeyRepoCreated)); v != nil {
repoCreated = string(v) == "true"
}
if v := b.Get([]byte(stateKeyProgress)); v != nil {
json.Unmarshal(v, &progress)
}
return nil
})
// Set default repo path if not set
if repoPath == "" {
repoPath = filepath.Join(home, "git-tutorial-project")
}
// Initialize text input for commands
ti := textinput.New()
ti.Placeholder = "Type your git command here..."
ti.Focus()
ti.CharLimit = 200
ti.Width = 50
// Initialize viewport for output
vp := viewport.New(50, 20)
initialOutput := []string{"Welcome to Git Tutor! 🎓"}
if !gitInstalled {
initialOutput = append(initialOutput, errorStyle.Render("⚠️ WARNING: Git is not installed!"))
initialOutput = append(initialOutput, infoStyle.Render("Please install Git first: https://git-scm.com/downloads"))
} else {
initialOutput = append(initialOutput, successStyle.Render("✓ Git is installed and ready!"))
}
vp.SetContent(strings.Join(initialOutput, "\n"))
return model{
currentStep: currentStep,
username: username,
email: email,
repoPath: repoPath,
logger: logger,
db: db,
progress: progress,
commandInput: ti,
outputViewport: vp,
gitOutput: initialOutput,
branchName: "feature-branch",
gitInstalled: gitInstalled,
repoCreated: repoCreated,
}
}
// Check if Git is installed
func checkGitInstalled() bool {
cmd := exec.Command("git", "--version")
err := cmd.Run()
return err == nil
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
// Update viewport dimensions
m.outputViewport.Width = msg.Width/2 - 6
m.outputViewport.Height = msg.Height - 15
if !m.ready {
m.ready = true
}
return m, nil
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c", "esc":
m.quitting = true
m.db.Close()
return m, tea.Quit
case "enter":
if m.currentStep == StepWelcome {
if !m.gitInstalled {
m.addOutput(errorStyle.Render("❌ Cannot proceed without Git installed!"))
m.addOutput(infoStyle.Render("Please install Git and restart the tutorial."))
return m, nil
}
m.currentStep++
m.saveState()
return m, nil
}
if m.currentStep == StepCompletion {
m.showCompletionForm()
m.quitting = true
return m, tea.Quit
}
// Get the entered command
command := strings.TrimSpace(m.commandInput.Value())
if command != "" {
m.lastCommand = command
m.executeCommand(command)
m.commandInput.Reset()
}
return m, nil
case "ctrl+n": // Next step (only if command was correct)
if m.commandCorrect && m.currentStep < StepCompletion {
m.currentStep++
m.commandCorrect = false
m.saveState()
m.addOutput("\n" + successStyle.Render("✓ Moving to next step...") + "\n")
} else if !m.commandCorrect {
m.addOutput(warningStyle.Render("⚠ Complete the current step correctly before proceeding!"))
}
return m, nil
case "ctrl+p": // Previous step
if m.currentStep > StepWelcome {
m.currentStep--
m.commandCorrect = false
m.saveState()
m.addOutput("\n" + infoStyle.Render("← Moving to previous step...") + "\n")
}
return m, nil
case "ctrl+h": // Show hint
m.showHint()
return m, nil
case "ctrl+s": // Skip step (for manual steps like file creation)
if m.canSkipStep() {
m.commandCorrect = true
m.handleSpecialSteps("skip")
m.addOutput(infoStyle.Render("⏭ Step marked as complete (manual action)"))
}
return m, nil
}
}
// Update command input
m.commandInput, cmd = m.commandInput.Update(msg)
return m, cmd
}
func (m model) View() string {
if m.quitting {
return successStyle.Render("Thanks for learning Git! Keep coding! 🚀\n")
}
if !m.ready {
return "Initializing..."
}
// Left panel - Tutorial content
leftContent := m.renderLeftPanel()
// Right panel - Git output
rightContent := m.renderRightPanel()
// Split layout
leftPanel := lipgloss.NewStyle().
Width(m.width/2 - 2).
Height(m.height - 2).
Render(leftContent)
rightPanel := lipgloss.NewStyle().
Width(m.width/2 - 2).
Height(m.height - 2).
Render(rightContent)
return lipgloss.JoinHorizontal(lipgloss.Top, leftPanel, rightPanel)
}
func (m model) renderLeftPanel() string {
var b strings.Builder
// Title
title := titleStyle.Render(fmt.Sprintf("🎓 Git Learning Tutorial - Step %d/%d", m.currentStep+1, len(stepNames)))
b.WriteString(title + "\n\n")
// Progress bar
progress := m.renderProgress()
b.WriteString(progress + "\n\n")
// Current step content
content := m.renderCurrentStep()
b.WriteString(boxStyle.Width(m.width/2-8).Render(content) + "\n\n")
// Command input (skip for welcome and completion)
if m.currentStep != StepWelcome && m.currentStep != StepCompletion {
b.WriteString(promptStyle.Render("$ ") + m.commandInput.View() + "\n\n")
// Status message
if m.commandCorrect {
b.WriteString(successStyle.Render("✓ Correct! Press Ctrl+N for next step") + "\n")
} else if m.lastCommand != "" {
b.WriteString(errorStyle.Render("✗ Try again or press Ctrl+H for hint") + "\n")
}
}
// Instructions
instructions := infoStyle.Render("Ctrl+N: Next • Ctrl+P: Previous • Ctrl+H: Hint • Ctrl+S: Skip • Esc: Quit")
b.WriteString("\n" + instructions)
return b.String()
}
func (m model) renderRightPanel() string {
var b strings.Builder
// Output panel title
outputTitle := titleStyle.Render("📟 Git Command Output")
b.WriteString(outputTitle + "\n\n")
// Viewport with git output
m.outputViewport.SetContent(strings.Join(m.gitOutput, "\n"))
outputBox := outputBoxStyle.
Width(m.width/2 - 8).
Height(m.height - 12).
Render(m.outputViewport.View())
b.WriteString(outputBox)
return b.String()
}
func (m model) renderProgress() string {
total := len(stepNames)
completed := int(m.currentStep)
percentage := (completed * 100) / total
bar := "["
for i := 0; i < 30; i++ {
if i < (completed*30)/total {
bar += "█"
} else {
bar += "░"
}
}
bar += "]"
return progressStyle.Render(fmt.Sprintf("%s %d%%", bar, percentage))
}
func (m model) renderCurrentStep() string {
stepName := stepNames[m.currentStep]
switch m.currentStep {
case StepWelcome:
welcomeText := fmt.Sprintf(`%s
Welcome to the Interactive Git Tutorial! 🎉
made by suvan gs
This tutorial will guide you through Git basics step-by-step.
You'll learn by DOING - type the actual Git commands yourself!
📚 Topics covered:
• Setting up Git
• Creating your first repository
• Making commits
• Working with branches
• Using remotes
• Essential Git commands
✨ Features:
• Real-time command verification
• Git output displayed on the right panel
• Hints available (Ctrl+H)
• Progress automatically saved`, successStyle.Render(stepName))
if !m.gitInstalled {
welcomeText += "\n\n" + errorStyle.Render("⚠️ Git is NOT installed!")
welcomeText += "\n" + infoStyle.Render("Install from: https://git-scm.com/downloads")
} else {
welcomeText += "\n\n" + successStyle.Render("✓ Git is installed - Press ENTER to begin!")
}
return welcomeText
case StepCheckGit:
return fmt.Sprintf(`%s
Let's verify Git is installed on your system.
📝 Task: Check your Git version
💡 Type the command to check Git version
Expected: git --version
This command shows your installed Git version.`, infoStyle.Render(stepName))
case StepSetupFolder:
return fmt.Sprintf(`%s
Create a project folder for this tutorial.
📝 Task: Create directory: %s
💡 Type one of:
mkdir %s
mkdir -p %s
Or press Ctrl+S to auto-create the folder.`,
infoStyle.Render(stepName),
m.repoPath,
m.repoPath,
m.repoPath)
case StepCreateFiles:
return fmt.Sprintf(`%s
Create sample files in your project.
📝 Task: Create these files:
• README.md
• main.go
• .gitignore
Working directory: %s
Press Ctrl+S to auto-create these files.`,
infoStyle.Render(stepName),
m.repoPath)
case StepConfigUser:
return fmt.Sprintf(`%s
Configure your Git identity.
Current config:
• Username: %s
• Email: %s
📝 Task: Set your Git username and email
💡 Commands:
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
Type both commands to complete this step.`,
infoStyle.Render(stepName),
m.getOrDefault(m.username, "Not set"),
m.getOrDefault(m.email, "Not set"))
case StepInitRepo:
return fmt.Sprintf(`%s
Initialize a Git repository.
📝 Task: Initialize Git in project folder
Working directory: %s
💡 Type: git init
This creates a .git directory to track changes.`,
infoStyle.Render(stepName),
m.repoPath)
case StepStageFiles:
return fmt.Sprintf(`%s
Stage your files for commit.
📝 Task: Add all files to staging area
💡 Type: git add .
This prepares all files to be committed.
The '.' means "all files in current directory".`, infoStyle.Render(stepName))
case StepFirstCommit:
return fmt.Sprintf(`%s
Make your first commit!
📝 Task: Commit staged files
💡 Type: git commit -m "Initial commit"
Commits are snapshots of your project.
The -m flag adds a commit message.`, infoStyle.Render(stepName))
case StepCheckBranch:
return fmt.Sprintf(`%s
Check your current branch.
📝 Task: List all branches
💡 Type: git branch
This shows all branches. The current one has a *.
Default branch is usually 'main' or 'master'.`, infoStyle.Render(stepName))
case StepAddRemote:
return fmt.Sprintf(`%s
Add a remote repository.
📝 Task: Add a remote called 'origin'
💡 Type: git remote add origin <url>
Replace <url> with your repository URL.
Example: https://github.com/username/repo.git
Or press Ctrl+S to skip if you don't have a remote yet.`, infoStyle.Render(stepName))
case StepPushOrigin:
return fmt.Sprintf(`%s
Push your code to the remote.
📝 Task: Push to origin
💡 Type: git push -u origin main
-u sets upstream tracking.
origin is the remote name.
main is the branch name.
Press Ctrl+S to skip if no remote configured.`, infoStyle.Render(stepName))
case StepCreateBranch:
return fmt.Sprintf(`%s
Create a new branch.
📝 Task: Create a feature branch
💡 Type one of:
• git branch feature-branch
• git checkout -b feature-branch
• git switch -c feature-branch
Branches let you work without affecting main.`, infoStyle.Render(stepName))
case StepCheckoutBranch:
return fmt.Sprintf(`%s
Switch to a different branch.
📝 Task: Checkout the feature branch
💡 Type one of:
• git checkout feature-branch
• git switch feature-branch
This changes your working directory to that branch.`, infoStyle.Render(stepName))
case StepGitStatus:
return fmt.Sprintf(`%s
Check repository status.
📝 Task: View the current status
💡 Type: git status
Shows:
• Modified files
• Staged changes
• Current branch
• Untracked files`, infoStyle.Render(stepName))
case StepGitDiff:
return fmt.Sprintf(`%s
View file changes.
📝 Task: See what changed
💡 Type: git diff
Shows line-by-line differences in modified files.
Great for reviewing before committing!`, infoStyle.Render(stepName))
case StepGitFetch:
return fmt.Sprintf(`%s
Fetch updates from remote.
📝 Task: Fetch from origin
💡 Type: git fetch origin
Downloads changes without merging.
Safe way to see what's new on remote.
Press Ctrl+S to skip if no remote configured.`, infoStyle.Render(stepName))
case StepGitLog:
return fmt.Sprintf(`%s
View commit history.
📝 Task: Display commit log
💡 Type one of:
• git log
• git log --oneline
Shows all commits in the repository.
--oneline gives a compact view.`, infoStyle.Render(stepName))
case StepCompletion:
return fmt.Sprintf(`%s
🎉 Congratulations! You've completed the Git tutorial!
You've learned:
✓ Git installation and configuration
✓ Repository initialization
✓ Staging and committing
✓ Branch management
✓ Remote operations
✓ Essential Git commands
You're now ready to use Git in real projects!
Press ENTER to complete feedback form.`, successStyle.Render("Tutorial Complete!"))
default:
return "Unknown step"
}
}
func (m *model) executeCommand(command string) {
m.addOutput(promptStyle.Render("$ ") + command)
// Validate command first
if !m.validateCommand(command) {
m.commandCorrect = false
m.addOutput(errorStyle.Render("✗ Incorrect command. Try again or press Ctrl+H for hint."))
return
}
m.commandCorrect = true
// Handle special steps before executing
m.handleSpecialSteps(command)
// Execute the actual command
output, err := m.runCommand(command)
if err != nil {
// Some errors are acceptable (e.g., empty git diff)
if output != "" {
m.addOutput(terminalStyle.Render(output))
} else {
m.addOutput(warningStyle.Render(fmt.Sprintf("Command executed with warning: %v", err)))
}
} else {
if output != "" {
m.addOutput(terminalStyle.Render(output))
}
}
m.addOutput(successStyle.Render("✓ Correct command!"))
}
func (m *model) validateCommand(command string) bool {
expected, exists := expectedCommands[m.currentStep]
if !exists {
return false
}
command = strings.TrimSpace(strings.ToLower(command))
// Check if command matches any expected variant
for _, exp := range expected {
if strings.HasPrefix(command, strings.ToLower(exp)) {
return true
}
}
return false
}
func (m *model) runCommand(command string) (string, error) {
// Parse command - handle quotes properly
command = strings.TrimSpace(command)
var cmd *exec.Cmd
var workDir string
// Determine working directory - ensure it exists
if m.repoCreated && m.currentStep >= StepInitRepo {
workDir = m.repoPath
// Double check directory exists
if _, err := os.Stat(workDir); os.IsNotExist(err) {
// Create it if it doesn't exist
os.MkdirAll(workDir, 0755)
}
} else {
workDir, _ = os.Getwd()
}
// Handle different command types
if runtime.GOOS == "windows" {
// Windows: use cmd.exe to execute commands
cmd = exec.Command("cmd", "/C", command)
} else {
// Unix-like: use sh
cmd = exec.Command("sh", "-c", command)
}
cmd.Dir = workDir
// Capture combined output
output, err := cmd.CombinedOutput()
return strings.TrimSpace(string(output)), err
}
func (m *model) handleSpecialSteps(command string) {
switch m.currentStep {
case StepSetupFolder:
// Ensure folder exists
if err := os.MkdirAll(m.repoPath, 0755); err != nil {
m.logger.Error("Failed to create directory", "path", m.repoPath, "error", err)
} else {
m.repoCreated = true
m.dbSet(stateKeyRepoPath, []byte(m.repoPath))
m.dbSet(stateKeyRepoCreated, []byte("true"))
m.addOutput(successStyle.Render(fmt.Sprintf("✓ Created directory: %s", m.repoPath)))
}
case StepCreateFiles:
m.createSampleFiles()
case StepConfigUser:
if strings.Contains(command, "user.name") {
// Extract username from command
parts := strings.SplitN(command, `"`, 3)
if len(parts) >= 2 {
m.username = strings.Trim(parts[1], `"`)
m.dbSet(stateKeyUsername, []byte(m.username))
}
}
if strings.Contains(command, "user.email") {
// Extract email from command
parts := strings.SplitN(command, `"`, 3)
if len(parts) >= 2 {
m.email = strings.Trim(parts[1], `"`)
m.dbSet(stateKeyEmail, []byte(m.email))
}
}
}
}
func (m *model) createSampleFiles() {
// Ensure directory exists first
if !m.repoCreated {
os.MkdirAll(m.repoPath, 0755)
m.repoCreated = true
m.dbSet(stateKeyRepoCreated, []byte("true"))
}
files := map[string]string{
"README.md": "# Git Tutorial Project\n\nLearning Git step by step!\n",
"main.go": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Hello, Git!\")\n}\n",
".gitignore": "*.log\n*.tmp\n.DS_Store\n",
}
for filename, content := range files {
path := filepath.Join(m.repoPath, filename)
err := os.WriteFile(path, []byte(content), 0644)
if err != nil {
m.logger.Error("Failed to create file", "file", filename, "error", err)
m.addOutput(errorStyle.Render(fmt.Sprintf("✗ Failed to create %s", filename)))
} else {
m.logger.Info("Created file", "file", filename)
m.addOutput(successStyle.Render(fmt.Sprintf("✓ Created %s", filename)))
}
}
}
func (m *model) addOutput(text string) {
m.gitOutput = append(m.gitOutput, text)
// Keep only last 100 lines
if len(m.gitOutput) > 100 {
m.gitOutput = m.gitOutput[len(m.gitOutput)-100:]
}
}
func (m *model) showHint() {
expected, exists := expectedCommands[m.currentStep]
if !exists || len(expected) == 0 {
m.addOutput(infoStyle.Render("💡 No specific command needed for this step."))
return
}
hint := infoStyle.Render(fmt.Sprintf("💡 Hint: Try typing: %s", expected[0]))
m.addOutput(hint)
}
func (m *model) canSkipStep() bool {
// Steps that can be manually completed
skipableSteps := []Step{StepSetupFolder, StepCreateFiles, StepAddRemote, StepPushOrigin, StepGitFetch}
for _, s := range skipableSteps {
if m.currentStep == s {
return true
}
}
return false
}
func (m *model) showCompletionForm() {
var feedbackText string
var rating string
var userEmail string
var sendEmail bool
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[string]().
Title("How would you rate this tutorial?").
Options(
huh.NewOption("⭐⭐⭐⭐⭐ Excellent", "5"),
huh.NewOption("⭐⭐⭐⭐ Good", "4"),
huh.NewOption("⭐⭐⭐ Average", "3"),
huh.NewOption("⭐⭐ Below Average", "2"),
huh.NewOption("⭐ Poor", "1"),
).
Value(&rating),
huh.NewText().
Title("Any feedback or suggestions?").
Value(&feedbackText).
Placeholder("Your thoughts..."),
huh.NewInput().
Title("Your email (optional - for follow-up)").
Value(&userEmail).
Placeholder("you@example.com"),
huh.NewConfirm().
Title("Send feedback to developer?").
Description("Help improve Git Tutor by sharing your feedback!").
Value(&sendEmail),
),
)
form.Run()