detectLanguage.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "bufio"
  4. "strings"
  5. )
  6. var checks map[string][]string
  7. func init() {
  8. checks = make(map[string][]string)
  9. checks["c"] = []string{"printf(", "malloc(", "realloc(", "free(", "#include", "#define", "sizeof", "typeof"}
  10. checks["go"] = []string{"fmt.", "package ", ":= range", "make(map[", "if err != nil"}
  11. checks["csharp"] = []string{"using", "namespace", ".Where(", ".Select(", "public ", "private ", "readonly ", "List<", " async ", "await "}
  12. }
  13. func removeString(array []string, index int) []string {
  14. return append(array[:index], array[index+1:]...)
  15. }
  16. func check(content string, keywords []string) float64 {
  17. keywordsToCheck := make([]string, len(keywords))
  18. copy(keywordsToCheck, keywords)
  19. certainty := 0.0
  20. scanner := bufio.NewScanner(strings.NewReader(content))
  21. for scanner.Scan() {
  22. if certainty >= 1.0 || len(keywordsToCheck) == 0 {
  23. break
  24. }
  25. line := scanner.Text()
  26. for index, keyword := range keywordsToCheck {
  27. if strings.Contains(line, keyword) {
  28. certainty += 0.1
  29. keywordsToCheck = removeString(keywordsToCheck, index)
  30. }
  31. }
  32. }
  33. return certainty
  34. }
  35. func detectLanguage(content string) string {
  36. currentLanguage := ""
  37. currentBest := 0.0
  38. for key, value := range checks {
  39. result := check(content, value)
  40. if result > currentBest {
  41. currentLanguage = key
  42. currentBest = result
  43. }
  44. }
  45. return currentLanguage
  46. }