123456789module apply1011import src.snapshot1213pub struct Plan {14pub mut:15 files []snapshot.FileEntry 16 applied []string 17 conflict string 18}1920pub fn conflicts(plan Plan) bool {21 return plan.conflict != ''22}23242526272829pub fn three_way(current []snapshot.FileEntry, base []snapshot.FileEntry, target []snapshot.FileEntry, filters []string, exclude []string) Plan {30 base_map := snapshot.index_files(base)31 target_map := snapshot.index_files(target)32 current_map := snapshot.index_files(current)3334 mut paths := []string{}35 for path in base_map.keys() {36 if in_scope(path, filters) && !excluded(path, exclude) {37 paths << path38 }39 }40 for path in target_map.keys() {41 if in_scope(path, filters) && !excluded(path, exclude) && path !in base_map {42 paths << path43 }44 }45 paths.sort()4647 mut plan := Plan{48 applied: []string{}49 }50 mut edits := []Edit{cap: paths.len}51 for path in paths {52 from := base_map[path] or {53 snapshot.FileEntry{54 path: path55 }56 }57 to := target_map[path] or {58 snapshot.FileEntry{59 path: path60 }61 }62 if same_entry(from, to) {63 continue64 }65 here := current_map[path] or {66 snapshot.FileEntry{67 path: path68 }69 }70 if same_entry(here, from) {71 plan.applied << path72 edits << Edit{73 path: path74 entry: to75 keep: path in target_map76 }77 continue78 }79 if same_entry(here, to) {80 81 continue82 }83 plan.conflict = path84 plan.files = with_edits(current, edits)85 return plan86 }87 plan.files = with_edits(current, edits)88 return plan89}9091pub fn in_scope(path string, filters []string) bool {92 if filters.len == 0 {93 return true94 }95 for raw in filters {96 filter := raw.trim_right('/')97 if path == filter || path.starts_with('${filter}/') {98 return true99 }100 }101 return false102}103104fn excluded(path string, exclude []string) bool {105 for name in exclude {106 if path == name {107 return true108 }109 }110 return false111}112113114115fn same_entry(a snapshot.FileEntry, b snapshot.FileEntry) bool {116 if a.hash == '' && b.hash == '' {117 return true118 }119 return a.hash == b.hash && a.executable == b.executable120}121122123struct Edit {124 path string125 entry snapshot.FileEntry126 keep bool127}128129130131132133134fn with_edits(files []snapshot.FileEntry, edits []Edit) []snapshot.FileEntry {135 mut sorted := files.clone()136 sorted.sort(a.path < b.path)137 mut out := []snapshot.FileEntry{cap: sorted.len + edits.len}138 mut at := 0139 for file in sorted {140 141 for at < edits.len && edits[at].path < file.path {142 if edits[at].keep {143 out << edits[at].entry144 }145 at++146 }147 if at < edits.len && edits[at].path == file.path {148 if edits[at].keep {149 out << edits[at].entry150 }151 at++152 continue153 }154 out << file155 }156 for at < edits.len {157 if edits[at].keep {158 out << edits[at].entry159 }160 at++161 }162 return out163}