Skip to content

Commit

Permalink
Code quality refactor (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
KonradIT authored Feb 14, 2023
1 parent 77ced37 commit 72912a4
Show file tree
Hide file tree
Showing 26 changed files with 411 additions and 506 deletions.
10 changes: 10 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ linters:
- nestif
- goconst
- asasalint
- bodyclose
- dupl
- durationcheck
- errname
- goconst
- godox
- gofumpt
- importas
- unconvert
- unparam
linter-settings:
nestif:
min-complexity: 20
Expand Down
1 change: 0 additions & 1 deletion cmd/apply_lut.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ var applyLutCmd = &cobra.Command{
}
color.Green(">> Successfully applied LUT to: %s", input)
}

},
}

Expand Down
8 changes: 4 additions & 4 deletions cmd/calendar.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func pad(d time.Weekday) int {
return int(d)
}

func SplitSliceInChunks(a []string, chuckSize int) [][]string {
func splitSliceInChunks(a []string, chuckSize int) [][]string {
chunks := [][]string{}
for chuckSize < len(a) {
a, chunks = a[chuckSize:], append(chunks, a[0:chuckSize:chuckSize])
Expand All @@ -37,7 +37,7 @@ func SplitSliceInChunks(a []string, chuckSize int) [][]string {
}

func getModDates(input string) ([]time.Time, error) {
var modificationDates = []time.Time{}
modificationDates := []time.Time{}
items, err := ioutil.ReadDir(input)
if err != nil {
return nil, err
Expand Down Expand Up @@ -69,7 +69,7 @@ var calendarView = &cobra.Command{
cui.Error(err.Error())
}

var modificationDates = []time.Time{}
modificationDates := []time.Time{}

switch connectionType {
case utils.Connect:
Expand Down Expand Up @@ -127,7 +127,7 @@ var calendarView = &cobra.Command{
data = append(data, color.YellowString(strconv.Itoa(i)))
}
}
prepared := SplitSliceInChunks(data, 7)
prepared := splitSliceInChunks(data, 7)
for _, v := range prepared {
table.Append(v)
}
Expand Down
14 changes: 7 additions & 7 deletions cmd/export_tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func tagAsDuration(tag int, increase bool) string {
return fmt.Sprintf("01:00:%d:%03d", seconds, 0)
}

func exportCSV(name string, tags gopro.HiLights, output string) error {
func exportCSV(tags gopro.HiLights, output string) error {
csvFile, err := os.Create(output)
if err != nil {
return err
Expand All @@ -43,12 +43,12 @@ func exportCSV(name string, tags gopro.HiLights, output string) error {
return writer.Error()
}

func exportJSON(name string, tags gopro.HiLights, output string) error {
func exportJSON(tags gopro.HiLights, output string) error {
b, err := json.MarshalIndent(tags, "", "\t")
if err != nil {
return err
}
return os.WriteFile(output, b, 0600)
return os.WriteFile(output, b, 0o600)
}

func exportEDL(name string, tags gopro.HiLights, output string) error {
Expand All @@ -58,7 +58,7 @@ FCM: NON-DROP FRAME
for index, tag := range tags.Timestamps {
content = fmt.Sprintf("%s\n%03d AX V C %s %s %s %s\n* FROM CLIP NAME: %s\n", content, index, "00:00:00:00", "00:00:00:01", tagAsDuration(tag, false), tagAsDuration(tag, true), name)
}
return os.WriteFile(output, []byte(content), 0600)
return os.WriteFile(output, []byte(content), 0o600)
}

func extractIndividual(input, output, format string) (int, error) {
Expand All @@ -72,12 +72,12 @@ func extractIndividual(input, output, format string) (int, error) {
if output == "" {
output = strings.Replace(input, filepath.Ext(input), ".csv", -1)
}
err = exportCSV(filepath.Base(input), *hilights, output)
err = exportCSV(*hilights, output)
case "json":
if output == "" {
output = strings.Replace(input, filepath.Ext(input), ".json", -1)
}
err = exportJSON(filepath.Base(input), *hilights, output)
err = exportJSON(*hilights, output)
case "edl":
if output == "" {
output = strings.Replace(input, filepath.Ext(input), ".edl", -1)
Expand All @@ -88,7 +88,7 @@ func extractIndividual(input, output, format string) (int, error) {
}

var exportTags = &cobra.Command{
Use: "export_tags",
Use: "export-tags",
Short: "Export HiLight/other tags in video",
Run: func(cmd *cobra.Command, args []string) {
input := getFlagString(cmd, "input")
Expand Down
126 changes: 91 additions & 35 deletions cmd/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package cmd

import (
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"time"

"github.com/erdaltsksn/cui"
"github.com/fatih/color"
Expand All @@ -16,6 +18,7 @@ import (
"github.com/konradit/mmt/pkg/utils"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"golang.org/x/exp/slices"
)

var importCmd = &cobra.Command{
Expand All @@ -30,7 +33,7 @@ var importCmd = &cobra.Command{
if projectName != "" {
_, err := os.Stat(filepath.Join(output, projectName))
if os.IsNotExist(err) {
err := os.Mkdir(filepath.Join(output, projectName), 0755)
err := os.Mkdir(filepath.Join(output, projectName), 0o755)
if err != nil {
cui.Error("Something went wrong creating project dir", err)
}
Expand All @@ -41,25 +44,34 @@ var importCmd = &cobra.Command{
bufferSize := getFlagInt(cmd, "buffer", "1000")
prefix := getFlagString(cmd, "prefix")
dateRange := getFlagSlice(cmd, "range")
cameraName := getFlagString(cmd, "camera_name")

customCameraOpts := make(map[string]interface{})
cameraName := getFlagString(cmd, "camera-name")
connection := utils.ConnectionType(getFlagString(cmd, "connection"))
skipAuxFiles := getFlagBool(cmd, "skip-aux", "true")
sortBy := getFlagSlice(cmd, "sort-by")
if len(sortBy) == 0 {
sortBy = []string{"camera", "location"}
}
sortOptions := utils.SortOptions{
ByLocation: slices.Contains(sortBy, "location"),
ByCamera: slices.Contains(sortBy, "camera"),
}
tagNames := getFlagSlice(cmd, "tag-names")

if useGoPro, err := cmd.Flags().GetBool("use_gopro"); err == nil && useGoPro {
if useGoPro, err := cmd.Flags().GetBool("use-gopro"); err == nil && useGoPro {
detectedGoPro, connectionType, err := gopro.Detect()
if err != nil {
cui.Error(err.Error())
}
input = detectedGoPro
customCameraOpts["connection"] = string(connectionType)
connection = connectionType
camera = "gopro"
} else if useInsta360, err := cmd.Flags().GetBool("use_insta360"); err == nil && useInsta360 {
} else if useInsta360, err := cmd.Flags().GetBool("use-insta360"); err == nil && useInsta360 {
detectedInsta360, connectionType, err := insta360.Detect()
if err != nil {
cui.Error(err.Error())
}
input = detectedInsta360
customCameraOpts["connection"] = string(connectionType)
connection = connectionType
camera = "insta360"
}

Expand All @@ -69,29 +81,31 @@ var importCmd = &cobra.Command{
cui.Error("Something went wrong", err)
}

skipAuxFiles := getFlagBool(cmd, "skip_aux", "true")
customCameraOpts["skip_aux"] = skipAuxFiles
sortBy := getFlagSlice(cmd, "sort_by")
if len(sortBy) == 0 {
customCameraOpts["sort_by"] = []string{"camera", "location"}
} else {
customCameraOpts["sort_by"] = sortBy
}
switch c {
case utils.GoPro:
if customCameraOpts["connection"] == "" {
connection := getFlagString(cmd, "connection")
if connection == "" {
connection = "sd_card"
}
customCameraOpts["connection"] = connection
if connection == "" {
connection = utils.SDCard
}
customCameraOpts["tag_names"] = getFlagSlice(cmd, "tag_names")
}
r, err := importFromCamera(c, input, filepath.Join(output, projectName), dateFormat, bufferSize, prefix, dateRange, cameraName, customCameraOpts)

params := utils.ImportParams{
Input: input,
Output: output,
CameraName: cameraName,
SkipAuxiliaryFiles: skipAuxFiles,
DateFormat: dateFormat,
BufferSize: bufferSize,
Prefix: prefix,
DateRange: parseDateRange(dateRange, dateFormat),
TagNames: tagNames,
Connection: connection,
Sort: sortOptions,
}
r, err := importFromCamera(c, params)
if err != nil {
cui.Error("Something went wrong", err)
}

data := [][]string{
{strconv.Itoa(r.FilesImported), strconv.Itoa(len(r.FilesNotImported)), strconv.Itoa(len(r.Errors))},
}
Expand Down Expand Up @@ -128,26 +142,68 @@ func init() {
importCmd.Flags().StringP("prefix", "p", "", "Prefix for each file, pass `cameraname` to prepend the camera name (eg: Hero9 Black)")
importCmd.Flags().StringSlice("range", []string{}, "A date range, eg: 01-05-2020,05-05-2020 -- also accepted: `today`, `yesterday`, `week`")
importCmd.Flags().StringP("connection", "x", "", "Connexion type: `sd_card`, `connect` (GoPro-specific)")
importCmd.Flags().StringSlice("sort_by", []string{}, "Sort files by: `camera`, `location`")
importCmd.Flags().StringSlice("tag_names", []string{}, "Tag names for number of HiLight tags in last 10s of video, each position being the amount, eg: 'marked 1,good stuff,important' => num of tags: 1,2,3")
importCmd.Flags().StringP("skip_aux", "s", "true", "Skip auxiliary files (GoPro: THM, LRV. DJI: SRT)")
importCmd.Flags().String("camera_name", "", "Override camera name detection with specified string")
importCmd.Flags().StringSlice("sort-by", []string{}, "Sort files by: `camera`, `location`")
importCmd.Flags().StringSlice("tag-names", []string{}, "Tag names for number of HiLight tags in last 10s of video, each position being the amount, eg: 'marked 1,good stuff,important' => num of tags: 1,2,3")
importCmd.Flags().StringP("skip-aux", "s", "true", "Skip auxiliary files (GoPro: THM, LRV. DJI: SRT)")
importCmd.Flags().String("camera-name", "", "Override camera name detection with specified string")

// Camera helpers
importCmd.Flags().Bool("use_gopro", false, "Detect GoPro camera attached")
importCmd.Flags().Bool("use_insta360", false, "Detect Insta360 camera attached")
importCmd.Flags().Bool("use-gopro", false, "Detect GoPro camera attached")
importCmd.Flags().Bool("use-insta360", false, "Detect Insta360 camera attached")
}

func parseDateRange(dateRange []string, dateFormat string) []time.Time {
dateStart := time.Date(0o000, time.Month(1), 1, 0, 0, 0, 0, time.UTC)
dateEnd := time.Now()

if len(dateRange) == 1 {
today := time.Date(dateEnd.Year(), dateEnd.Month(), dateEnd.Day(), 0, 0, 0, 0, dateEnd.Location())
switch dateRange[0] {
case "today":
dateStart = today
case "yesterday":
dateStart = today.Add(-24 * time.Hour)
case "week":
dateStart = today.Add(-24 * time.Duration((int(dateEnd.Weekday()) - 1)) * time.Hour)
case "week-back":
dateStart = today.Add((-24 * 7) * time.Hour)
}
}

if len(dateRange) == 2 {
start, err := time.Parse(utils.DateFormatReplacer.Replace(dateFormat), dateRange[0])
if err != nil {
log.Fatal(err.Error())
}
if err == nil {
dateStart = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, start.Location())
}
end, err := time.Parse(utils.DateFormatReplacer.Replace(dateFormat), dateRange[1])
if err != nil {
log.Fatal(err.Error())
}
if err == nil {
dateEnd = time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, end.Location())
}
}

return []time.Time{dateStart, dateEnd}
}

func callImport(cameraIf utils.Import, params utils.ImportParams) (*utils.Result, error) {
return cameraIf.Import(params)
}

func importFromCamera(c utils.Camera, input string, output string, dateFormat string, bufferSize int, prefix string, dateRange []string, cameraName string, camOpts map[string]interface{}) (*utils.Result, error) {
func importFromCamera(c utils.Camera, params utils.ImportParams) (*utils.Result, error) {
switch c {
case utils.GoPro:
return gopro.Import(input, output, dateFormat, bufferSize, prefix, dateRange, cameraName, camOpts)
return callImport(gopro.Entrypoint{}, params)
case utils.DJI:
return dji.Import(input, output, dateFormat, bufferSize, prefix, dateRange, cameraName, camOpts)
return callImport(dji.Entrypoint{}, params)
case utils.Insta360:
return insta360.Import(input, output, dateFormat, bufferSize, prefix, dateRange, cameraName, camOpts)
return callImport(insta360.Entrypoint{}, params)
case utils.Android:
return android.Import(input, output, dateFormat, bufferSize, prefix, dateRange, cameraName, camOpts)
return callImport(android.Entrypoint{}, params)
}
return nil, mErrors.ErrUnsupportedCamera("")
}
1 change: 0 additions & 1 deletion cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ var updateCmd = &cobra.Command{
cui.Error("Something went wrong", err)
}
}

},
}

Expand Down
Loading

0 comments on commit 72912a4

Please sign in to comment.