1234567module machine89import os1011pub const remote_file = 'remote'12pub const credentials_file = 'credentials'1314pub const kind_folder = 'folder'15pub const kind_s3 = 's3'1617pub struct RemoteSettings {18pub:19 kind string20 path string 21 endpoint string 22 bucket string23 region string24}2526pub struct Credentials {27pub:28 access_key string29 secret_key string30}3132pub fn save_remote(settings RemoteSettings) ! {33 os.mkdir_all(config_dir(), os.MkdirParams{})!34 mut text := '# written by koh remote — the remote for every repo on this machine\n'35 text += 'kind=${settings.kind}\n'36 if settings.kind == kind_folder {37 text += 'path=${settings.path}\n'38 } else {39 text += 'endpoint=${settings.endpoint}\n'40 text += 'bucket=${settings.bucket}\n'41 text += 'region=${settings.region}\n'42 }43 os.write_file(config_path(remote_file), text)!44}4546pub fn load_remote() !RemoteSettings {47 text := os.read_file(config_path(remote_file)) or {48 return error('this machine has no remote yet — run "koh remote"')49 }50 values := parse_config(text)51 settings := RemoteSettings{52 kind: values['kind'] or { '' }53 path: values['path'] or { '' }54 endpoint: values['endpoint'] or { '' }55 bucket: values['bucket'] or { '' }56 region: values['region'] or { '' }57 }58 if settings.kind !in [kind_folder, kind_s3] {59 return error('the remote setting in ${config_path(remote_file)} is not readable — run "koh remote" again')60 }61 return settings62}6364pub fn has_remote() bool {65 return os.is_file(config_path(remote_file))66}6768pub fn forget_remote() ! {69 if os.exists(config_path(remote_file)) {70 os.rm(config_path(remote_file))!71 }72}737475pub fn save_credentials(credentials Credentials) ! {76 os.mkdir_all(config_dir(), os.MkdirParams{})!77 mut text := '# written by koh remote — keep this file private\n'78 text += 'access_key=${credentials.access_key}\n'79 text += 'secret_key=${credentials.secret_key}\n'80 path := config_path(credentials_file)81 os.write_file(path, text)!82 os.chmod(path, 0o600)!83}8485pub fn load_credentials() !Credentials {86 text := os.read_file(config_path(credentials_file)) or {87 return error('this machine has no S3 keys yet — run "koh remote"')88 }89 values := parse_config(text)90 credentials := Credentials{91 access_key: values['access_key'] or { '' }92 secret_key: values['secret_key'] or { '' }93 }94 if credentials.access_key == '' || credentials.secret_key == '' {95 return error('the S3 keys in ${config_path(credentials_file)} are incomplete — run "koh remote" again')96 }97 return credentials98}99100fn parse_config(text string) map[string]string {101 mut values := map[string]string{}102 for line in text.split_into_lines() {103 trimmed := line.trim_space()104 if trimmed == '' || trimmed.starts_with('#') {105 continue106 }107 at := trimmed.index('=') or { continue }108 values[trimmed[..at].trim_space()] = trimmed[at + 1..].trim_space()109 }110 return values111}