Class: NeocitiesRed::Services::SiteDifference

Inherits:
Object
  • Object
show all
Defined in:
lib/neocities_red/services/site_difference.rb

Instance Method Summary collapse

Constructor Details

#initialize(client, path: ".", detail: false, ignore_dotfiles: false, exclude: []) ⇒ SiteDifference

Returns a new instance of SiteDifference.



9
10
11
12
13
14
15
16
# File 'lib/neocities_red/services/site_difference.rb', line 9

def initialize(client, path: ".", detail: false, ignore_dotfiles: false, exclude: [])
  @client = client
  @path = path
  @detail = detail || false
  @ignore_dotfiles = ignore_dotfiles || false
  @exclude = exclude || []
  @pastel = Pastel.new(eachline: "\n")
end

Instance Method Details

#showObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/neocities_red/services/site_difference.rb', line 18

def show
  server_files = Services::FileList.new(@client, nil, @detail)
                                   .show

  root_path = Pathname(@path)

  added_paths = []
  removed_paths = []
  modified_paths = []

  Dir.chdir(root_path) do
    paths = Dir.glob(File.join("**", "*"), File::FNM_DOTMATCH)

    local_paths = paths.reject { |path| path.start_with?(".") }
    local_files = local_paths.select { |path| File.file?(path) }.map do |path|
      {
        path: path,
        sha1_hash: Digest::SHA1.file(path).hexdigest
      }
    end
    server_paths = server_files.map { |n| n[:path] }

    server_file_map = server_files.to_h do |file|
      [file[:path], file[:sha1_hash]]
    end

    if @ignore_dotfiles
      server_paths = server_paths.reject { |path| path.start_with?(".") }
      local_paths = local_paths.reject { |path| path.start_with?(".") }
    end

    if @exclude.any?
      server_paths -= @exclude
      local_paths -= @exclude
    end

    removed_paths = server_paths - local_paths
    removed_paths.map! { |file| @pastel.red(file) }

    added_paths = local_paths - server_paths
    added_paths.map! { |file| @pastel.green(file) }

    modified_paths = local_files.select do |file|
      server_hash = server_file_map[file[:path]]
      server_hash && server_hash != file[:sha1_hash]
    end
    modified_paths.map! { |file| @pastel.yellow(file[:path]) }
  end

  [
    added_paths,
    modified_paths,
    removed_paths
  ]
end