Skip to content

Commit 079bb3c

Browse files
committed
♻️ Use github.com/ewen-lbh/label-logger-go for logging & progress bar
1 parent c29f2d4 commit 079bb3c

22 files changed

+175
-406
lines changed

add.go

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111

1212
"github.com/anaskhan96/soup"
1313
"github.com/charmbracelet/huh"
14+
ll "github.com/ewen-lbh/label-logger-go"
1415
"golang.org/x/text/cases"
1516
"golang.org/x/text/language"
1617

@@ -176,7 +177,7 @@ func (ctx *RunContext) CreateDescriptionFile(workId string, metadataItems []stri
176177
if fileExists(readmePath) {
177178
readmeTitle, readmeBody, err := fromReadme(readmePath)
178179
if err != nil {
179-
DisplayWarning("couldn't extract info from README.md", err)
180+
ll.WarnDisplay("couldn't extract info from README.md", err)
180181
} else {
181182
if readmeTitle != "" {
182183
defaultProjectTitle = readmeTitle
@@ -188,10 +189,10 @@ func (ctx *RunContext) CreateDescriptionFile(workId string, metadataItems []stri
188189
detectedStartDate, err := DetectStartDate(ctx.PathToWorkFolder(workId))
189190
defaultStartedAt := ""
190191
if err != nil {
191-
DisplayWarning("while detecting start date of %s", err, workId)
192+
ll.WarnDisplay("while detecting start date of %s", err, workId)
192193
} else {
193194
defaultStartedAt = detectedStartDate.Format("2006-01-02")
194-
LogCustom("Detected", "cyan", "start date to be [bold][blue]%s[reset]", defaultStartedAt)
195+
ll.Log("Detected", "cyan", "start date to be [bold][blue]%s[reset]", defaultStartedAt)
195196
}
196197

197198
startedAtPlaceholder := "YYYY-MM-DD"
@@ -207,27 +208,27 @@ func (ctx *RunContext) CreateDescriptionFile(workId string, metadataItems []stri
207208

208209
autodetectedTechs, err := ctx.DetectTechnologies(workId)
209210
if err != nil {
210-
LogWarning(formatErrors(fmt.Errorf("while autodetecting technologies for %s: %w", workId, err)))
211+
ll.Warn(ll.FormatErrors(fmt.Errorf("while autodetecting technologies for %s: %w", workId, err)))
211212
} else {
212213
displayTags := make([]string, 0, len(autodetectedTechs))
213214
for _, tech := range autodetectedTechs {
214215
metadata.MadeWith = append(metadata.MadeWith, tech.Slug)
215216
displayTags = append(displayTags, tech.String())
216217
}
217218
if len(metadata.MadeWith) > 0 {
218-
LogCustom("Detected", "cyan", "technologies to be %s", formatList(displayTags, "[bold][blue]%s[reset]", ", "))
219+
ll.Log("Detected", "cyan", "technologies to be %s", ll.List(displayTags, "[bold][blue]%s[reset]", ", "))
219220
}
220221
}
221222

222223
autodetectedTags, err := ctx.DetectTags(workId, autodetectedTechs)
223224
if err != nil {
224-
DisplayWarning("while autodetecting tags for %s", err, workId)
225+
ll.WarnDisplay("while autodetecting tags for %s", err, workId)
225226
} else {
226227
for _, tag := range autodetectedTags {
227228
metadata.Tags = append(metadata.Tags, tag.String())
228229
}
229230
if len(metadata.Tags) > 0 {
230-
LogCustom("Detected", "cyan", "tags to be %s", formatList(metadata.Tags, "[bold][blue]%s[reset]", ", "))
231+
ll.Log("Detected", "cyan", "tags to be %s", ll.List(metadata.Tags, "[bold][blue]%s[reset]", ", "))
231232
}
232233
}
233234

@@ -248,7 +249,7 @@ func (ctx *RunContext) CreateDescriptionFile(workId string, metadataItems []stri
248249
Value(&metadata.MadeWith).
249250
Options(allTechsOptions...).
250251
Validate(func(s []string) error {
251-
LogDebug("Selected %v", s)
252+
ll.Debug("Selected %v", s)
252253
return nil
253254
}).
254255
Height(2+6),
@@ -276,7 +277,7 @@ func (ctx *RunContext) CreateDescriptionFile(workId string, metadataItems []stri
276277
defaultFinishedAt := time.Now().Format("2006-01-02")
277278
if finishedAtFromGit, err := LastGitCommitDate(ctx.PathToWorkFolder(workId)); err == nil {
278279
defaultFinishedAt = finishedAtFromGit.Format("2006-01-02")
279-
LogCustom("Detected", "cyan", "finish date to be [bold][blue]%s[reset]", defaultFinishedAt)
280+
ll.Log("Detected", "cyan", "finish date to be [bold][blue]%s[reset]", defaultFinishedAt)
280281
}
281282

282283
err = huh.NewForm(
@@ -330,6 +331,6 @@ func (ctx *RunContext) CreateDescriptionFile(workId string, metadataItems []stri
330331

331332
os.MkdirAll(filepath.Dir(outputPath), 0o755)
332333
os.WriteFile(outputPath, []byte(output), 0o644)
333-
LogCustom("Created", "green", "description.md file at [bold]%s[reset]", outputPath)
334+
ll.Log("Created", "green", "description.md file at [bold]%s[reset]", outputPath)
334335
return outputPath, nil
335336
}

build.go

Lines changed: 36 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919

2020
"path"
2121

22+
ll "github.com/ewen-lbh/label-logger-go"
2223
jsoniter "github.com/json-iterator/go"
2324
)
2425

@@ -227,7 +228,7 @@ func AcquireBuildLock(outputFilename string) error {
227228
func ReleaseBuildLock(outputFilename string) error {
228229
err := os.Remove(BuildLockFilepath(outputFilename))
229230
if err != nil {
230-
DisplayError("could not release build lockfile %s", err, BuildLockFilepath(outputFilename))
231+
ll.ErrorDisplay("could not release build lockfile %s", err, BuildLockFilepath(outputFilename))
231232
}
232233
return err
233234
}
@@ -248,19 +249,19 @@ func PrepareBuild(databaseDirectory string, outputFilename string, flags Flags,
248249
thumbnailSizesCount := len(ctx.Config.MakeThumbnails.Sizes)
249250

250251
if thumbnailSizesCount/2 > flags.WorkersCount {
251-
LogDebug("ThumbnailSizesCount/2 (%d) > flags.WorkersCount (%d). Using 2 thumbnailers per work.", thumbnailSizesCount/2, flags.WorkersCount)
252+
ll.Debug("ThumbnailSizesCount/2 (%d) > flags.WorkersCount (%d). Using 2 thumbnailers per work.", thumbnailSizesCount/2, flags.WorkersCount)
252253
ctx.thumbnailersPerWork = 2
253254
} else {
254-
LogDebug("Configuration asks for %d thumbnail sizes. setting thumbnail workers count per work to half of that.", thumbnailSizesCount)
255+
ll.Debug("Configuration asks for %d thumbnail sizes. setting thumbnail workers count per work to half of that.", thumbnailSizesCount)
255256
ctx.thumbnailersPerWork = thumbnailSizesCount / 2
256257
}
257258

258-
LogDebug("Using %d thumbnailers threads per work", ctx.thumbnailersPerWork)
259+
ll.Debug("Using %d thumbnailers threads per work", ctx.thumbnailersPerWork)
259260

260261
if ctx.ProgressInfoFile != "" {
261-
LogDebug("Removing progress info file %s", ctx.ProgressInfoFile)
262+
ll.Debug("Removing progress info file %s", ctx.ProgressInfoFile)
262263
if err := os.Remove(ctx.ProgressInfoFile); err != nil {
263-
LogDebug("Could not remove progress info file %s: %s", ctx.ProgressInfoFile, err.Error())
264+
ll.Debug("Could not remove progress info file %s: %s", ctx.ProgressInfoFile, err.Error())
264265
}
265266
}
266267

@@ -278,24 +279,24 @@ func PrepareBuild(databaseDirectory string, outputFilename string, flags Flags,
278279
ctx.Exporters = append(ctx.Exporters, exporter)
279280
}
280281

281-
LogDebug("Running with configuration %#v", &config)
282+
ll.Debug("Running with configuration %#v", &config)
282283

283284
previousBuiltDatabaseRaw, err := os.ReadFile(outputFilename)
284285
if err != nil {
285286
if !os.IsNotExist(err) {
286-
DisplayError("No previously built database file %s to use", err, outputFilename)
287+
ll.ErrorDisplay("No previously built database file %s to use", err, outputFilename)
287288
}
288289
} else {
289290
previousDb := Database{}
290291
err = json.Unmarshal(previousBuiltDatabaseRaw, &previousDb)
291292
if err != nil {
292-
DisplayError("Couldn't use previous built database file %s", err, outputFilename)
293+
ll.ErrorDisplay("Couldn't use previous built database file %s", err, outputFilename)
293294
}
294295
ctx.previousBuiltDatabase = PreviouslyBuiltDatabase{Database: previousDb}
295296
}
296297

297298
if ctx.Config.IsDefault {
298-
LogInfo("No configuration file found. The default configuration was used.")
299+
ll.Info("No configuration file found. The default configuration was used.")
299300
}
300301

301302
err = os.MkdirAll(config.Media.At, 0o755)
@@ -312,7 +313,7 @@ func PrepareBuild(databaseDirectory string, outputFilename string, flags Flags,
312313
return &ctx, err
313314
}
314315

315-
LogCustom("Using", "magenta", "exporter [bold]%s[reset]\n[dim]%s", exporter.Name(), exporter.Description())
316+
ll.Log("Using", "magenta", "exporter [bold]%s[reset]\n[dim]%s", exporter.Name(), exporter.Description())
316317
err = exporter.Before(&ctx, options)
317318
if err != nil {
318319
return &ctx, fmt.Errorf("while running exporter %s before hook: %w", exporter.Name(), err)
@@ -348,7 +349,7 @@ func directoriesLeftToBuild(all []string, built []string) []string {
348349
func (ctx *RunContext) RunExporters(work *Work) error {
349350
for _, exporter := range ctx.Exporters {
350351
if debugging {
351-
LogCustom("Exporting", "magenta", "%s to %s", work.ID, exporter.Name())
352+
ll.Log("Exporting", "magenta", "%s to %s", work.ID, exporter.Name())
352353
}
353354
options := ctx.Config.Exporters[exporter.Name()]
354355
err := exporter.Export(ctx, options, work)
@@ -371,7 +372,7 @@ func (ctx *RunContext) BuildSome(include string, databaseDirectory string, outpu
371372

372373
// Initialize stuff
373374
works := ctx.PreviouslyBuiltDatabase()
374-
// LogDebug("initialized works@%p from previous@%p", works, ctx.previousBuiltDatabase.Database)
375+
// ll.Debug("initialized works@%p from previous@%p", works, ctx.previousBuiltDatabase.Database)
375376
workDirectories, err := ctx.ComputeProgressTotal()
376377
if err != nil {
377378
return Database{}, fmt.Errorf("while computing total number of works to build: %w", err)
@@ -391,20 +392,20 @@ func (ctx *RunContext) BuildSome(include string, databaseDirectory string, outpu
391392
ctx.StartProgressBar(len(workDirectories))
392393

393394
if flags.WorkersCount < ctx.thumbnailersPerWork {
394-
LogWarning("Number of workers (%d) is less than the number of thumbnailers per work (%d). Setting number of workers to %d", ctx.Flags.WorkersCount, ctx.thumbnailersPerWork, ctx.thumbnailersPerWork)
395+
ll.Warn("Number of workers (%d) is less than the number of thumbnailers per work (%d). Setting number of workers to %d", ctx.Flags.WorkersCount, ctx.thumbnailersPerWork, ctx.thumbnailersPerWork)
395396
flags.WorkersCount = ctx.thumbnailersPerWork
396397
}
397398

398399
// Build works in parallel
399400
for i := 0; i < flags.WorkersCount/ctx.thumbnailersPerWork; i++ {
400401
i := i
401-
LogDebug("worker #%d: starting", i)
402+
ll.Debug("worker #%d: starting", i)
402403
go func() {
403-
LogDebug("worker #%d: starting", i)
404+
ll.Debug("worker #%d: starting", i)
404405
for {
405406
dirEntry := <-workDirectoriesChannel
406407
workID := dirEntry.Name()
407-
LogDebug("worker #%d: starting with work %s", i, workID)
408+
ll.Debug("worker #%d: starting with work %s", i, workID)
408409
_, presentBefore := ctx.PreviouslyBuiltWork(workID)
409410
var included bool
410411
if include == "*" {
@@ -430,7 +431,7 @@ func (ctx *RunContext) BuildSome(include string, databaseDirectory string, outpu
430431
ctx.Status(workID, PhaseBuilding)
431432
newWork, usedCache, err := ctx.Build(string(descriptionRaw), outputFilename, workID)
432433
if err != nil {
433-
DisplayError("while building %s", err, workID)
434+
ll.ErrorDisplay("while building %s", err, workID)
434435
builtChannel <- builtItem{err: fmt.Errorf("while building %s (%s): %w", workID, ctx.DescriptionFilename(databaseDirectory, workID), err)}
435436
continue
436437
}
@@ -443,55 +444,55 @@ func (ctx *RunContext) BuildSome(include string, databaseDirectory string, outpu
443444
}
444445

445446
// Update in database
446-
LogDebug("worker #%d: sending freshly built work %s", i, workID)
447+
ll.Debug("worker #%d: sending freshly built work %s", i, workID)
447448
builtChannel <- builtItem{work: newWork, workID: workID}
448449
continue
449450
// }
450451
} else if presentBefore {
451452
// Nothing to do, old work will be kept as-is.
452-
LogDebug("worker #%d: nothing to do for work %s", i, workID)
453+
ll.Debug("worker #%d: nothing to do for work %s", i, workID)
453454
ctx.Status(workID, PhaseUnchanged)
454455
} else {
455-
LogDebug("worker #%d: Build skipped: not included by %s, not present in previous database file.", i, include)
456+
ll.Debug("worker #%d: Build skipped: not included by %s, not present in previous database file.", i, include)
456457
}
457-
LogDebug("worker #%d: reusing old work %s", i, workID)
458+
ll.Debug("worker #%d: reusing old work %s", i, workID)
458459
builtChannel <- builtItem{reuseOld: true, workID: workID}
459460
}
460461
}()
461462
}
462463

463-
LogDebug("main: filling work directories")
464+
ll.Debug("main: filling work directories")
464465
for _, workDirectory := range workDirectories {
465466
workDirectoriesChannel <- workDirectory
466467
}
467468

468469
// Collect all newly-built works
469-
LogDebug("main: collecting results")
470+
ll.Debug("main: collecting results")
470471
for len(builtDirectories) < len(workDirectories) {
471472
result := <-builtChannel
472-
LogDebug("main: got result %v", result)
473+
ll.Debug("main: got result %v", result)
473474
if result.err != nil {
474-
LogDebug("main: got error, returning early")
475+
ll.Debug("main: got error, returning early")
475476
return Database{}, result.err
476477
}
477478
if !result.reuseOld {
478-
LogDebug("main: updating work %s", result.workID)
479+
ll.Debug("main: updating work %s", result.workID)
479480
ctx.previousBuiltDatabase.mu.Lock()
480481
works[result.workID] = result.work
481482
ctx.previousBuiltDatabase.mu.Unlock()
482483
}
483484
ctx.WriteDatabase(works, flags, outputFilename, true)
484485
builtDirectories = append(builtDirectories, result.workID)
485-
LogDebug("main: built dirs: %d out of %d", len(builtDirectories), len(workDirectories))
486-
LogDebug("main: left to build: %v", directoriesLeftToBuild(workDirectoriesNames, builtDirectories))
486+
ll.Debug("main: built dirs: %d out of %d", len(builtDirectories), len(workDirectories))
487+
ll.Debug("main: left to build: %v", directoriesLeftToBuild(workDirectoriesNames, builtDirectories))
487488
}
488489

489490
for _, exporter := range ctx.Exporters {
490491
options := ctx.Config.Exporters[exporter.Name()]
491-
LogDebug("Running exporter %s's after hook with options %#v", exporter.Name(), options)
492+
ll.Debug("Running exporter %s's after hook with options %#v", exporter.Name(), options)
492493
err := exporter.After(ctx, options, &works)
493494
if err != nil {
494-
DisplayError("while running exporter %s's after hook: %s", err, exporter.Name())
495+
ll.ErrorDisplay("while running exporter %s's after hook: %s", err, exporter.Name())
495496
}
496497

497498
}
@@ -500,7 +501,7 @@ func (ctx *RunContext) BuildSome(include string, databaseDirectory string, outpu
500501
}
501502

502503
func (ctx *RunContext) WriteDatabase(works Database, flags Flags, outputFilename string, partial bool) {
503-
LogDebug("Writing database (partial=%v) to %s", partial, outputFilename)
504+
ll.Debug("Writing database (partial=%v) to %s", partial, outputFilename)
504505
worksWithDatabaseMetadata := make(Database, 0)
505506
for id, work := range works {
506507
work.Metadata.DatabaseMetadata = DatabaseMeta{Partial: partial}
@@ -559,7 +560,7 @@ func (ctx *RunContext) ComputeProgressTotal() (workDirectories []fs.DirEntry, er
559560
}
560561
// If it's not there, this directory is not a project worth scanning.
561562
if _, err := os.Stat(descriptionFilename); os.IsNotExist(err) {
562-
LogDebug("skipping %s as it has no description file: %s does not exist", dirEntry.Name(), descriptionFilename)
563+
ll.Debug("skipping %s as it has no description file: %s does not exist", dirEntry.Name(), descriptionFilename)
563564
continue
564565
}
565566

@@ -594,7 +595,7 @@ func (ctx *RunContext) Build(descriptionRaw string, outputFilename string, workI
594595
newDescriptionHash := base64.StdEncoding.EncodeToString(hash[:])
595596

596597
if oldWork, found := ctx.PreviouslyBuiltWork(workID); found && oldWork.DescriptionHash == newDescriptionHash && !ctx.Flags.NoCache {
597-
LogDebug("parsing description for %s: using cached work", workID)
598+
ll.Debug("parsing description for %s: using cached work", workID)
598599
work = oldWork
599600
usedCache = true
600601
} else {
@@ -613,7 +614,7 @@ func (ctx *RunContext) Build(descriptionRaw string, outputFilename string, workI
613614
if block.Type != "media" {
614615
continue
615616
}
616-
LogDebug("Handling media %#v", block.Media)
617+
ll.Debug("Handling media %#v", block.Media)
617618
analyzed, anchor, usedCacheForMedia, err := ctx.HandleMedia(workID, block.ID, block.Media, lang)
618619
if err != nil {
619620
return Work{}, false, err

cmd/add.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88

99
"github.com/MakeNowJust/heredoc"
1010
ortfodb "github.com/ortfo/db"
11+
ll "github.com/ewen-lbh/label-logger-go"
1112
"github.com/spf13/cobra"
1213
)
1314

@@ -69,7 +70,7 @@ var addCmd = &cobra.Command{
6970

7071
editor := os.Getenv("EDITOR")
7172
if editor != "" {
72-
ortfodb.LogCustom("Opening", "cyan", "%s in %s", descriptionFilepath, editor)
73+
ll.Log("Opening", "cyan", "%s in %s", descriptionFilepath, editor)
7374
editorPath, err := exec.LookPath(editor)
7475
if err != nil {
7576
handleError(fmt.Errorf("while getting path to %s: %w", editor, err))

cmd/exporters.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
ortfodb "github.com/ortfo/db"
1414
"github.com/spf13/cobra"
1515
"github.com/spf13/pflag"
16+
ll "github.com/ewen-lbh/label-logger-go"
1617
)
1718

1819
var exportersCmd = &cobra.Command{
@@ -53,7 +54,7 @@ var exportersInitCmd = &cobra.Command{
5354
" "),
5455
),
5556
0644)
56-
ortfodb.LogCustom("Created", "green", fmt.Sprintf("example exporter at [bold]%s.yaml[reset]", args[0]))
57+
ll.Log("Created", "green", fmt.Sprintf("example exporter at [bold]%s.yaml[reset]", args[0]))
5758
},
5859
}
5960

cmd/ui.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010

1111
"github.com/MakeNowJust/heredoc"
1212
"github.com/mitchellh/colorstring"
13-
ortfodb "github.com/ortfo/db"
13+
ll "github.com/ewen-lbh/label-logger-go"
1414
"github.com/spf13/cobra"
1515
"github.com/spf13/pflag"
1616
"golang.org/x/term"
@@ -176,7 +176,7 @@ func customFlagsUsage(f *pflag.FlagSet) string {
176176
}
177177

178178
s := buf.String()
179-
if !ortfodb.ShowingColors() {
179+
if !ll.ShowingColors() {
180180
s = regexp.MustCompile(`\x1b\[[0-9;]*[a-zA-Z]`).ReplaceAllString(s, "")
181181
}
182182
return s

0 commit comments

Comments
 (0)