cmd_update.v

2.8 KB · raw

1//! `koh update` — put a newer published koh in place of this one (§12).2//!3//! Nothing is installed without being asked, and nothing is removed: the new4//! binary replaces the running one by rename, which is the step that makes the5//! change visible.67module cli89import json210import src.build11import src.update1213// cmd_update installs a newer koh when one is published. `--check` only reports, and exits 1 when there14// is an update; --json needs --yes when it would install.15pub fn cmd_update(raw []string) int {16	args := parse('update', raw, Options{17		flags: ['check', 'json', 'yes']18	}) or { return usage_error(err.msg()) }19	if args.positional.len > 0 {20		return usage_error('update takes no arguments, not "${args.positional_at(0)}"')21	}22	if args.json() && !args.flag('yes') && !args.flag('check') {23		// The question cannot be asked inside a JSON document, so an install asked24		// for in JSON has to be asked for with --yes as well. That is a mistake in25		// the command line, not a refusal of the work.26		return usage_error('--json needs --yes when it would install')27	}28	current := version29	platform := build.this_machine() or { return refuse(args.json(), err.msg()) }30	checked := update.check(current, platform) or { return refuse(args.json(), err.msg()) }31	latest := if checked.update {32		checked.available33	} else {34		if args.json() {35			emit_json(json2.encode(UpdateJson{36				current:   current37				latest:    current38				available: false39			}))40		} else {41			ok('koh ${current} is the newest — nothing to do')42		}43		return 044	}45	if args.flag('check') {46		if args.json() {47			emit_json(json2.encode(UpdateJson{48				current:   current49				latest:    latest.version50				available: true51				notes:     latest.notes52			}))53		} else {54			ok('koh ${latest.version} is available — you have ${current}')55			if latest.notes != '' {56				note(latest.notes)57			}58			note('run "koh update" to install it')59		}60		// `--check` reports and says so with its exit code, so a script can ask.61		return 162	}63	if !args.json() {64		note('${current} → ${latest.version}')65		if latest.notes != '' {66			note(latest.notes)67		}68	}69	// A "no" at the question is a refusal, not a reason to carry on.70	approved := confirm(args.flag('yes')) or { return refuse(args.json(), err.msg()) }71	if !approved {72		return refuse(args.json(), 'not updating, then')73	}74	working('downloading koh ${latest.version}')75	target := update.install(latest) or { return refuse(args.json(), err.msg()) }76	if args.json() {77		emit_json(json2.encode(UpdateJson{78			current:   current79			latest:    latest.version80			available: true81			installed: target82		}))83		return 084	}85	ok('installed koh ${latest.version} as ${target}')86	return 087}8889struct UpdateJson {90	current   string91	latest    string92	available bool93	installed string94	notes     string95}