detectLanguage.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. checks["html"] = []string{"html>", "head>", "body>", "title>", "script>", "div>"}
  13. }
  14. func removeString(array []string, index int) []string {
  15. return append(array[:index], array[index+1:]...)
  16. }
  17. func check(content string, keywords []string) float64 {
  18. keywordsToCheck := make([]string, len(keywords))
  19. copy(keywordsToCheck, keywords)
  20. certainty := 0.0
  21. scanner := bufio.NewScanner(strings.NewReader(content))
  22. for scanner.Scan() {
  23. if certainty >= 1.0 || len(keywordsToCheck) == 0 {
  24. break
  25. }
  26. line := scanner.Text()
  27. for index, keyword := range keywordsToCheck {
  28. if strings.Contains(line, keyword) {
  29. certainty += 0.1
  30. keywordsToCheck = removeString(keywordsToCheck, index)
  31. }
  32. }
  33. }
  34. return certainty
  35. }
  36. func detectLanguage(content string) string {
  37. currentLanguage := ""
  38. currentBest := 0.0
  39. for key, value := range checks {
  40. result := check(content, value)
  41. if result > currentBest {
  42. currentLanguage = key
  43. currentBest = result
  44. }
  45. }
  46. return currentLanguage
  47. }