Skip to content

Commit 4f6e0a4

Browse files
Tanq16Tanq16
andauthored
Fixes (#21)
* init * om fix * pause for gdrive token oauth * gdrive rename fix * gdrive rename fix * gdrive rename fix * gdrive fix --------- Co-authored-by: Tanq16 <[email protected]>
1 parent 4ed9067 commit 4f6e0a4

File tree

5 files changed

+123
-24
lines changed

5 files changed

+123
-24
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
danzo
22
download.yaml
3-
.danzo-temp
3+
.danzo-temp
4+
.danzo-token.json
5+
danzo-gdrive.json

downloaders/gdrive/auth.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"os"
99
"path/filepath"
1010

11+
"github.com/tanq16/danzo/utils"
1112
"golang.org/x/oauth2"
1213
"golang.org/x/oauth2/google"
1314
)
@@ -63,7 +64,9 @@ func getOAuthToken(config *oauth2.Config, tokenFile string) (*oauth2.Token, erro
6364
return token, nil
6465
}
6566
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
66-
fmt.Printf("\nVisit the URL to authenticate:\n%s\n\nEnter the authorization code here and press return\n", authURL)
67+
utils.PrintDetail("\nVisit this URL to get the authorization code:\n")
68+
fmt.Printf("%s\n", authURL)
69+
utils.PrintDetail("\nAfter authorizing, enter the authorization code:")
6770
var authCode string
6871
if _, err := fmt.Scan(&authCode); err != nil {
6972
return nil, fmt.Errorf("unable to read authorization code: %v", err)
@@ -74,7 +77,9 @@ func getOAuthToken(config *oauth2.Config, tokenFile string) (*oauth2.Token, erro
7477
}
7578
if err := saveToken(tokenFile, token); err != nil {
7679
}
77-
fmt.Printf("\033[%dA\033[J", 6)
80+
clearLength := 6
81+
clearLength += len(authURL)/utils.GetTerminalWidth() + 1
82+
fmt.Printf("\033[%dA\033[J", clearLength)
7883
return token, nil
7984
}
8085

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ require (
1212
github.com/google/uuid v1.6.0
1313
github.com/spf13/cobra v1.9.1
1414
golang.org/x/oauth2 v0.28.0
15+
golang.org/x/term v0.29.0
1516
gopkg.in/yaml.v3 v3.0.1
1617
)
1718

internal/downloader.go

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ func BatchDownload(entries []utils.DownloadEntry, numLinks, connectionsPerLink i
119119

120120
if err == utils.ErrRangeRequestsNotSupported {
121121
outputMgr.SetStatus(entryFunctionId, "warning")
122-
outputMgr.SetMessage(entryFunctionId, fmt.Sprintf("Downloading %s with single connection (range requests not supported)", entry.OutputPath))
122+
outputMgr.SetMessage(entryFunctionId, fmt.Sprintf("Downloading %s with 1 connection (range requests unsupported)", entry.OutputPath))
123123
} else if err != nil {
124124
outputMgr.ReportError(entryFunctionId, fmt.Errorf("error getting file size for %s: %v", entry.OutputPath, err))
125125
outputMgr.SetMessage(entryFunctionId, fmt.Sprintf("Error getting file size for %s", entry.OutputPath))
@@ -438,7 +438,9 @@ func BatchDownload(entries []utils.DownloadEntry, numLinks, connectionsPerLink i
438438
// =================================================================================================================
439439
case "gdrive":
440440
simpleClient := utils.CreateHTTPClient(httpClientConfig, false)
441+
outputMgr.Pause()
441442
apiKey, err := danzogdrive.GetAuthToken()
443+
outputMgr.Resume()
442444
if err != nil {
443445
outputMgr.ReportError(entryFunctionId, fmt.Errorf("error getting API key: %v", err))
444446
outputMgr.SetMessage(entryFunctionId, "Error getting API key")
@@ -451,16 +453,15 @@ func BatchDownload(entries []utils.DownloadEntry, numLinks, connectionsPerLink i
451453
continue
452454
}
453455
if config.OutputPath == "" {
454-
inferredFileName := utils.RenewOutputPath(metadata["name"].(string))
455-
config.OutputPath = inferredFileName
456-
entry.OutputPath = inferredFileName
456+
config.OutputPath = metadata["name"].(string)
457+
if existingFile, _ := os.Stat(config.OutputPath); existingFile != nil {
458+
config.OutputPath = utils.RenewOutputPath(config.OutputPath)
459+
}
460+
entry.OutputPath = config.OutputPath
457461
}
458-
outputMgr.SetMessage(entryFunctionId, fmt.Sprintf("Downloading Google Drive file %s", entry.OutputPath))
462+
outputMgr.SetMessage(entryFunctionId, fmt.Sprintf("Downloading GDrive file %s", entry.OutputPath))
459463
fileSize := metadata["size"].(string)
460-
fileSizeInt, err := strconv.ParseInt(fileSize, 10, 64)
461-
if err != nil {
462-
} else {
463-
}
464+
fileSizeInt, _ := strconv.ParseInt(fileSize, 10, 64)
464465

465466
var progressWg sync.WaitGroup
466467
progressWg.Add(1)
@@ -476,10 +477,10 @@ func BatchDownload(entries []utils.DownloadEntry, numLinks, connectionsPerLink i
476477

477478
err = danzogdrive.PerformGDriveDownload(config, apiKey, fileID, simpleClient, progressCh)
478479
if err != nil {
479-
outputMgr.ReportError(entryFunctionId, fmt.Errorf("error downloading Google Drive file %s: %v", entry.OutputPath, err))
480-
outputMgr.SetMessage(entryFunctionId, fmt.Sprintf("Error downloading Google Drive file %s", entry.OutputPath))
480+
outputMgr.ReportError(entryFunctionId, fmt.Errorf("error downloading GDrive file %s: %v", entry.OutputPath, err))
481+
outputMgr.SetMessage(entryFunctionId, fmt.Sprintf("Error downloading GDrive file %s", entry.OutputPath))
481482
} else {
482-
outputMgr.Complete(entryFunctionId, fmt.Sprintf("Completed Google Drive download - %s", entry.OutputPath))
483+
outputMgr.Complete(entryFunctionId, fmt.Sprintf("Completed GDrive download - %s", entry.OutputPath))
483484
}
484485
close(progressCh)
485486
progressWg.Wait()

utils/output-manager.go

Lines changed: 99 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ import (
77
"strings"
88
"sync"
99
"time"
10+
"unicode/utf8"
1011

1112
"github.com/charmbracelet/lipgloss"
1213
"github.com/charmbracelet/lipgloss/table"
14+
"golang.org/x/term"
1315
)
1416

1517
var (
@@ -68,6 +70,33 @@ func PrintStream(text string) {
6870
func PrintHeader(text string) {
6971
fmt.Println(headerStyle.Render(text))
7072
}
73+
func FSuccess(text string) string {
74+
return successStyle.Render(text)
75+
}
76+
func FSuccess2(text string) string {
77+
return success2Style.Render(text)
78+
}
79+
func FError(text string) string {
80+
return errorStyle.Render(text)
81+
}
82+
func FWarning(text string) string {
83+
return warningStyle.Render(text)
84+
}
85+
func FInfo(text string) string {
86+
return infoStyle.Render(text)
87+
}
88+
func FDebug(text string) string {
89+
return debugStyle.Render(text)
90+
}
91+
func FDetail(text string) string {
92+
return detailStyle.Render(text)
93+
}
94+
func FStream(text string) string {
95+
return streamStyle.Render(text)
96+
}
97+
func FHeader(text string) string {
98+
return headerStyle.Render(text)
99+
}
71100

72101
// ======================================== =================
73102
// ======================================== Table Definitions
@@ -85,6 +114,12 @@ func NewTable(headers []string) *Table {
85114
Rows: [][]string{},
86115
}
87116
t.table = table.New().Headers(headers...)
117+
t.table = t.table.StyleFunc(func(row, col int) lipgloss.Style {
118+
if row == table.HeaderRow {
119+
return lipgloss.NewStyle().Bold(true).Align(lipgloss.Center).Padding(0, 1)
120+
}
121+
return lipgloss.NewStyle().Padding(0, 1)
122+
})
88123
return t
89124
}
90125

@@ -106,7 +141,7 @@ func (t *Table) FormatTable(useMarkdown bool) string {
106141
}
107142

108143
func (t *Table) PrintTable(useMarkdown bool) {
109-
os.Stdout.WriteString(t.FormatTable(useMarkdown))
144+
fmt.Println(t.FormatTable(useMarkdown))
110145
}
111146

112147
func (t *Table) WriteMarkdownTableToFile(outputPath string) error {
@@ -303,26 +338,81 @@ func (m *Manager) AddStreamLine(name string, line string) {
303338
m.mutex.Lock()
304339
defer m.mutex.Unlock()
305340
if info, exists := m.outputs[name]; exists {
306-
if m.unlimitedOutput { // just append
307-
info.StreamLines = append(info.StreamLines, line)
341+
// Wrap the line with indentation
342+
wrappedLines := wrapText(line, basePadding+4)
343+
if m.unlimitedOutput { // just append all wrapped lines
344+
info.StreamLines = append(info.StreamLines, wrappedLines...)
308345
} else { // enforce size limit
309346
currentLen := len(info.StreamLines)
310-
if currentLen+1 > m.maxStreams {
311-
info.StreamLines = append(info.StreamLines[1:], line)
347+
totalNewLines := len(wrappedLines)
348+
if currentLen+totalNewLines > m.maxStreams {
349+
startIndex := currentLen + totalNewLines - m.maxStreams
350+
if startIndex > currentLen {
351+
startIndex = 0
352+
existingToKeep := m.maxStreams - totalNewLines
353+
if existingToKeep > 0 {
354+
info.StreamLines = info.StreamLines[currentLen-existingToKeep:]
355+
} else {
356+
info.StreamLines = []string{} // All existing lines will be dropped
357+
}
358+
} else {
359+
info.StreamLines = info.StreamLines[startIndex:]
360+
}
361+
info.StreamLines = append(info.StreamLines, wrappedLines...)
312362
} else {
313-
info.StreamLines = append(info.StreamLines, line)
363+
info.StreamLines = append(info.StreamLines, wrappedLines...)
364+
}
365+
if len(info.StreamLines) > m.maxStreams {
366+
info.StreamLines = info.StreamLines[len(info.StreamLines)-m.maxStreams:]
314367
}
315368
}
316369
info.LastUpdated = time.Now()
317370
}
318371
}
319372

373+
func GetTerminalWidth() int {
374+
width, _, err := term.GetSize(int(os.Stdout.Fd()))
375+
if err != nil || width <= 0 {
376+
return 80 // Default fallback width if terminal width can't be determined
377+
}
378+
return width
379+
}
380+
381+
func wrapText(text string, indent int) []string {
382+
termWidth := GetTerminalWidth()
383+
maxWidth := termWidth - indent - 2 // Account for indentation
384+
if maxWidth <= 10 {
385+
maxWidth = 80
386+
}
387+
if utf8.RuneCountInString(text) <= maxWidth {
388+
return []string{text}
389+
}
390+
var lines []string
391+
currentLine := ""
392+
currentWidth := 0
393+
for _, r := range text {
394+
runeWidth := 1
395+
// If adding this rune would exceed max width, flush the line
396+
if currentWidth+runeWidth > maxWidth {
397+
lines = append(lines, currentLine)
398+
currentLine = string(r)
399+
currentWidth = runeWidth
400+
} else {
401+
currentLine += string(r)
402+
currentWidth += runeWidth
403+
}
404+
}
405+
if currentLine != "" {
406+
lines = append(lines, currentLine)
407+
}
408+
return lines
409+
}
410+
320411
func (m *Manager) AddProgressBarToStream(name string, outof, final int64, text string) {
321412
m.mutex.Lock()
322413
defer m.mutex.Unlock()
323414
if info, exists := m.outputs[name]; exists {
324-
// percentage = max(0, min(percentage, 100))
325-
progressBar := PrintProgressBar(outof, final, 30)
415+
progressBar := PrintProgressBar(max(0, outof), final, 30)
326416
display := progressBar + debugStyle.Render(text)
327417
info.StreamLines = []string{display} // Set as only stream so nothing else is displayed
328418
info.LastUpdated = time.Now()
@@ -348,7 +438,7 @@ func (m *Manager) ClearLines(n int) {
348438
if n <= 0 {
349439
return
350440
}
351-
fmt.Printf("\033[%dA\033[J", n)
441+
fmt.Printf("\033[%dA\033[J", min(m.numLines, n))
352442
m.numLines = max(m.numLines-n, 0)
353443
}
354444

0 commit comments

Comments
 (0)