Guest User

Untitled

a guest
Aug 10th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. def e_sh(str)
  4. str.to_s.gsub(/(?=[^a-zA-Z0-9_.\/\-\x7F-\xFF\n])/n, '\\').gsub(/\n/, "'\n'").sub(/^$/, "''")
  5. end
  6.  
  7. def find_headers(lines)
  8. in_headers = false
  9. lines.each_with_index {|line, i|
  10. if line =~ /^\S[^\:]+\:( .*?)?$/
  11. in_headers = true
  12. elsif in_headers === true
  13. return i
  14. else
  15. return false
  16. end
  17. }
  18. end
  19.  
  20. input = ARGF.read
  21.  
  22. links = input.scan(/\((https?:\/\/([^\)]+))\)/)
  23. refs = input.scan(/^\[([^\]]+)\]: (\S+)$/)
  24. lines = input.split("\n")
  25.  
  26. bottom = lines[0..-1].join("\n").gsub(/^\[([^\]]+)\]: (\S+)\n?/,'')
  27.  
  28. norepeat = []
  29. norepeatlinks = []
  30. output = []
  31.  
  32. refs.each {|ref|
  33. name = ref[0]
  34. next if norepeatlinks.include? ref[1]
  35. while norepeat.include? name
  36. if name =~ / ?[0-9]$/
  37. name.next!
  38. else
  39. name = name + " 2"
  40. end
  41. end
  42. output << {'orig' => ref[0], 'title' => name, 'link' => ref[1]}
  43. norepeat.push name
  44. norepeatlinks.push ref[1]
  45. }
  46.  
  47. links.each {|url|
  48. next if norepeatlinks.include? url[0]
  49. domain = url[0].match(/https?:\/\/([^\/]+)/)
  50. parts = domain[1].split('.')
  51. name = case parts.length
  52. when 1 then parts[0]
  53. when 2 then parts[0]
  54. else parts[1]
  55. end
  56. while norepeat.include? name
  57. if name =~ / ?[0-9]$/
  58. name.next!
  59. else
  60. name = name + " 2"
  61. end
  62. end
  63. output << {'orig' => url[0], 'title' => name, 'link' => url[0] }
  64. norepeat.push name
  65. norepeatlinks.push url[0]
  66. }
  67. output = output.sort {|a,b| a['title'] <=> b['title']}
  68. o = []
  69.  
  70. output.each_with_index { |x,i|
  71. o.push("[#{x['title']}]: #{x['link']}")
  72. bottom = bottom.gsub(/\((#{e_sh x['orig']}|#{e_sh x['link']})\)/,"[#{x['title']}]").gsub(/\[#{e_sh x['orig']}\]/,"[#{x['title']}]")
  73. }
  74. puts bottom + "\n\n#{o.join("\n")}\n"
Add Comment
Please, Sign In to add comment