← back to jeduden__mdsmith

Function bodies 497 total

All specs Real LLM only Function bodies
main.run function · go · L76-L113 (38 LOC)
cmd/mdsmith/main.go
func run() int {
	// Handle no arguments: print usage, exit 0.
	if len(os.Args) < 2 {
		fmt.Fprint(os.Stderr, usageText)
		return 0
	}

	// Handle global flags before subcommand dispatch.
	first := os.Args[1]

	switch first {
	case "--help", "-h":
		fmt.Fprint(os.Stderr, usageText)
		return 0
	}

	// Dispatch to subcommand.
	switch first {
	case "check":
		return runCheck(os.Args[2:])
	case "fix":
		return runFix(os.Args[2:])
	case "help":
		return runHelp(os.Args[2:])
	case "metrics":
		return runMetrics(os.Args[2:])
	case "merge-driver":
		return runMergeDriver(os.Args[2:])
	case "init":
		return runInit(os.Args[2:])
	case "version":
		printVersion()
		return 0
	default:
		fmt.Fprintf(os.Stderr, "mdsmith: unknown command %q\n\n%s", first, usageText)
		return 2
	}
}
main.printVersion function · go · L115-L121 (7 LOC)
cmd/mdsmith/main.go
func printVersion() {
	version := "(devel)"
	if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "" {
		version = info.Main.Version
	}
	fmt.Printf("mdsmith %s\n", version)
}
main.runCheck function · go · L124-L178 (55 LOC)
cmd/mdsmith/main.go
func runCheck(args []string) int {
	fs := flag.NewFlagSet("check", flag.ContinueOnError)
	var (
		configPath       string
		format           string
		noColor          bool
		quiet            bool
		verbose          bool
		noGitignore      bool
		noFollowSymlinks bool
	)

	fs.StringVarP(&configPath, "config", "c", "", "Override config file path")
	fs.StringVarP(&format, "format", "f", "text", "Output format: text, json")
	fs.BoolVar(&noColor, "no-color", false, "Disable ANSI colors")
	fs.BoolVarP(&quiet, "quiet", "q", false, "Suppress non-error output")
	fs.BoolVarP(&verbose, "verbose", "v", false, "Show config, files, and rules on stderr")
	fs.BoolVar(&noGitignore, "no-gitignore", false, "Disable .gitignore filtering when walking directories")
	fs.BoolVar(&noFollowSymlinks, "no-follow-symlinks", false, "Skip symbolic links when walking directories")

	fs.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: mdsmith check [flags] [files...]\n\n"+
			"Lint Markdown files for style issues.\n\
main.runFix function · go · L181-L236 (56 LOC)
cmd/mdsmith/main.go
func runFix(args []string) int {
	fs := flag.NewFlagSet("fix", flag.ContinueOnError)
	var (
		configPath       string
		format           string
		noColor          bool
		quiet            bool
		verbose          bool
		noGitignore      bool
		noFollowSymlinks bool
	)

	fs.StringVarP(&configPath, "config", "c", "", "Override config file path")
	fs.StringVarP(&format, "format", "f", "text", "Output format: text, json")
	fs.BoolVar(&noColor, "no-color", false, "Disable ANSI colors")
	fs.BoolVarP(&quiet, "quiet", "q", false, "Suppress non-error output")
	fs.BoolVarP(&verbose, "verbose", "v", false, "Show config, files, and rules on stderr")
	fs.BoolVar(&noGitignore, "no-gitignore", false, "Disable .gitignore filtering when walking directories")
	fs.BoolVar(&noFollowSymlinks, "no-follow-symlinks", false, "Skip symbolic links when walking directories")

	fs.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: mdsmith fix [flags] [files...]\n\n"+
			"Auto-fix lint issues in Markdown files.\n\n"+
main.runInit function · go · L239-L283 (45 LOC)
cmd/mdsmith/main.go
func runInit(args []string) int {
	fs := flag.NewFlagSet("init", flag.ContinueOnError)

	fs.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: mdsmith init\n\n"+
			"Generate a default .mdsmith.yml config file in the current directory.\n")
	}

	if err := fs.Parse(args); err != nil {
		return 2
	}

	if fs.NArg() > 0 {
		fmt.Fprintf(os.Stderr, "mdsmith: init takes no arguments\n")
		return 2
	}

	const configFile = ".mdsmith.yml"

	// Check if config file already exists.
	if _, err := os.Stat(configFile); err == nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %s already exists\n", configFile)
		return 2
	}

	cfg := config.DumpDefaults()

	// Set front-matter: true as default.
	fm := true
	cfg.FrontMatter = &fm

	data, err := yaml.Marshal(cfg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: marshalling config: %v\n", err)
		return 2
	}

	if err := os.WriteFile(configFile, data, 0644); err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: writing %s: %v\n", configFile, err)
		return 2
	}

	fmt.Fprin
main.formatDiagnostics function · go · L287-L300 (14 LOC)
cmd/mdsmith/main.go
func formatDiagnostics(diags []lint.Diagnostic, format string, noColor bool) int {
	var formatter output.Formatter
	switch format {
	case "json":
		formatter = &output.JSONFormatter{}
	default:
		formatter = &output.TextFormatter{Color: !noColor}
	}
	if err := formatter.Format(os.Stderr, diags); err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: error writing output: %v\n", err)
		return 2
	}
	return 0
}
main.printRunStats function · go · L316-L328 (13 LOC)
cmd/mdsmith/main.go
func printRunStats(format string, quiet bool, stats runStats) {
	if quiet || format == "json" {
		return
	}
	fmt.Fprintf(
		os.Stderr,
		"stats: checked=%d fixed=%d failures=%d unfixed=%d\n",
		stats.Checked,
		stats.Fixed,
		stats.Failures,
		stats.Unfixed,
	)
}
Repobility's GitHub App fixes findings like these · https://github.com/apps/repobility-bot
main.checkFiles function · go · L331-L385 (55 LOC)
cmd/mdsmith/main.go
func checkFiles(
	fileArgs []string, configPath, format string,
	noColor, quiet, verbose, noGitignore, noFollowSymlinks bool,
) int {
	logger := &vlog.Logger{Enabled: verbose, W: os.Stderr}

	cfg, cfgPath, err := loadConfig(configPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	if cfgPath != "" {
		logger.Printf("config: %s", cfgPath)
	}

	opts := resolveOpts(cfg, noGitignore, noFollowSymlinks)
	files, err := lint.ResolveFilesWithOpts(fileArgs, opts)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	if len(files) == 0 {
		return 0
	}

	runner := &engine.Runner{
		Config:           cfg,
		Rules:            rule.All(),
		StripFrontMatter: frontMatterEnabled(cfg),
		Logger:           logger,
	}
	result := runner.Run(files)
	printErrors(result.Errors)

	if !quiet && len(result.Diagnostics) > 0 {
		if code := formatDiagnostics(result.Diagnostics, format, noColor); code != 0 {
			return code
		}
	}
	printRunStats(format, quiet,
main.fixFiles function · go · L388-L442 (55 LOC)
cmd/mdsmith/main.go
func fixFiles(
	fileArgs []string, configPath, format string,
	noColor, quiet, verbose, noGitignore, noFollowSymlinks bool,
) int {
	logger := &vlog.Logger{Enabled: verbose, W: os.Stderr}

	cfg, cfgPath, err := loadConfig(configPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	if cfgPath != "" {
		logger.Printf("config: %s", cfgPath)
	}

	opts := resolveOpts(cfg, noGitignore, noFollowSymlinks)
	files, err := lint.ResolveFilesWithOpts(fileArgs, opts)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	if len(files) == 0 {
		return 0
	}

	fixer := &fixpkg.Fixer{
		Config:           cfg,
		Rules:            rule.All(),
		StripFrontMatter: frontMatterEnabled(cfg),
		Logger:           logger,
	}
	fixResult := fixer.Fix(files)
	printErrors(fixResult.Errors)

	if !quiet && len(fixResult.Diagnostics) > 0 {
		if code := formatDiagnostics(fixResult.Diagnostics, format, noColor); code != 0 {
			return code
		}
	}
	printRunStats(format,
main.checkStdin function · go · L446-L493 (48 LOC)
cmd/mdsmith/main.go
func checkStdin(format string, noColor, quiet, verbose bool, configPath string) int {
	logger := &vlog.Logger{Enabled: verbose, W: os.Stderr}

	source, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: reading stdin: %v\n", err)
		return 2
	}

	cfg, cfgPath, err := loadConfig(configPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	if cfgPath != "" {
		logger.Printf("config: %s", cfgPath)
	}

	runner := &engine.Runner{
		Config:           cfg,
		Rules:            rule.All(),
		StripFrontMatter: frontMatterEnabled(cfg),
		Logger:           logger,
	}
	result := runner.RunSource("<stdin>", source)
	printErrors(result.Errors)

	if !quiet && len(result.Diagnostics) > 0 {
		if code := formatDiagnostics(result.Diagnostics, format, noColor); code != 0 {
			return code
		}
	}
	printRunStats(format, quiet, runStats{
		Checked:  result.FilesChecked,
		Fixed:    0,
		Failures: len(result.Diagnostics),
		Unfixed:  len(result.Diagnosti
main.splitStdinArg function · go · L497-L506 (10 LOC)
cmd/mdsmith/main.go
func splitStdinArg(args []string) (hasStdin bool, fileArgs []string) {
	for _, a := range args {
		if a == "-" {
			hasStdin = true
		} else {
			fileArgs = append(fileArgs, a)
		}
	}
	return hasStdin, fileArgs
}
main.checkDiscovered function · go · L510-L566 (57 LOC)
cmd/mdsmith/main.go
func checkDiscovered(
	configPath, format string,
	noColor, quiet, verbose, noGitignore, noFollowSymlinks bool,
) int {
	logger := &vlog.Logger{Enabled: verbose, W: os.Stderr}

	cfg, cfgPath, err := loadConfig(configPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	if cfgPath != "" {
		logger.Printf("config: %s", cfgPath)
	}

	// Discover files using config patterns.
	if len(cfg.Files) == 0 {
		return 0
	}

	files, err := discovery.Discover(discovery.Options{
		Patterns:         cfg.Files,
		UseGitignore:     !noGitignore,
		NoFollowSymlinks: resolveOpts(cfg, noGitignore, noFollowSymlinks).NoFollowSymlinks,
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: discovering files: %v\n", err)
		return 2
	}
	if len(files) == 0 {
		return 0
	}

	runner := &engine.Runner{
		Config:           cfg,
		Rules:            rule.All(),
		StripFrontMatter: frontMatterEnabled(cfg),
		Logger:           logger,
	}
	result := runner.Run(files)
	printErrors(result.Err
main.fixDiscovered function · go · L570-L626 (57 LOC)
cmd/mdsmith/main.go
func fixDiscovered(
	configPath, format string,
	noColor, quiet, verbose, noGitignore, noFollowSymlinks bool,
) int {
	logger := &vlog.Logger{Enabled: verbose, W: os.Stderr}

	cfg, cfgPath, err := loadConfig(configPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	if cfgPath != "" {
		logger.Printf("config: %s", cfgPath)
	}

	// Discover files using config patterns.
	if len(cfg.Files) == 0 {
		return 0
	}

	files, err := discovery.Discover(discovery.Options{
		Patterns:         cfg.Files,
		UseGitignore:     !noGitignore,
		NoFollowSymlinks: resolveOpts(cfg, noGitignore, noFollowSymlinks).NoFollowSymlinks,
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: discovering files: %v\n", err)
		return 2
	}
	if len(files) == 0 {
		return 0
	}

	fixer := &fixpkg.Fixer{
		Config:           cfg,
		Rules:            rule.All(),
		StripFrontMatter: frontMatterEnabled(cfg),
		Logger:           logger,
	}
	fixResult := fixer.Fix(files)
	printErrors(fixResult.Er
main.resolveOpts function · go · L633-L643 (11 LOC)
cmd/mdsmith/main.go
func resolveOpts(cfg *config.Config, noGitignore, noFollowSymlinks bool) lint.ResolveOpts {
	useGitignore := !noGitignore
	opts := lint.ResolveOpts{
		UseGitignore:     &useGitignore,
		NoFollowSymlinks: cfg.NoFollowSymlinks,
	}
	if noFollowSymlinks {
		opts.NoFollowSymlinks = []string{"**"}
	}
	return opts
}
main.frontMatterEnabled function · go · L645-L650 (6 LOC)
cmd/mdsmith/main.go
func frontMatterEnabled(cfg *config.Config) bool {
	if cfg.FrontMatter != nil {
		return *cfg.FrontMatter
	}
	return true
}
Generated by Repobility's multi-pass static-analysis pipeline (https://repobility.com)
main.loadConfig function · go · L656-L688 (33 LOC)
cmd/mdsmith/main.go
func loadConfig(configPath string) (*config.Config, string, error) {
	defaults := config.Defaults()

	if configPath != "" {
		loaded, err := config.Load(configPath)
		if err != nil {
			return nil, "", err
		}
		return config.Merge(defaults, loaded), configPath, nil
	}

	// Try to discover a config file.
	cwd, err := os.Getwd()
	if err != nil {
		return config.Merge(defaults, nil), "", nil
	}

	discovered, err := config.Discover(cwd)
	if err != nil {
		return config.Merge(defaults, nil), "", nil
	}

	if discovered == "" {
		return config.Merge(defaults, nil), "", nil
	}

	loaded, err := config.Load(discovered)
	if err != nil {
		return nil, "", err
	}

	return config.Merge(defaults, loaded), discovered, nil
}
main.runHelp function · go · L698-L713 (16 LOC)
cmd/mdsmith/main.go
func runHelp(args []string) int {
	if len(args) == 0 {
		fmt.Fprint(os.Stderr, helpUsageText)
		return 0
	}

	switch args[0] {
	case "rule":
		return runHelpRule(args[1:])
	case "metrics":
		return runHelpMetrics(args[1:])
	default:
		fmt.Fprintf(os.Stderr, "mdsmith: help: unknown topic %q\n", args[0])
		return 2
	}
}
main.runHelpRule function · go · L716-L721 (6 LOC)
cmd/mdsmith/main.go
func runHelpRule(args []string) int {
	if len(args) == 0 {
		return listAllRules()
	}
	return showRule(args[0])
}
main.listAllRules function · go · L723-L734 (12 LOC)
cmd/mdsmith/main.go
func listAllRules() int {
	rules, err := ruledocs.ListRules()
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}

	for _, r := range rules {
		fmt.Printf("%-6s %-40s %-10s %s\n", r.ID, r.Name, r.Status, r.Description)
	}
	return 0
}
main.showRule function · go · L736-L744 (9 LOC)
cmd/mdsmith/main.go
func showRule(query string) int {
	content, err := ruledocs.LookupRule(query)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	fmt.Print(content)
	return 0
}
main.runMergeDriver function · go · L35-L55 (21 LOC)
cmd/mdsmith/mergedriver.go
func runMergeDriver(args []string) int {
	if len(args) == 0 {
		fmt.Fprint(os.Stderr, mergeDriverUsage)
		return 0
	}

	switch args[0] {
	case "--help", "-h":
		fmt.Fprint(os.Stderr, mergeDriverUsage)
		return 0
	case "run":
		return runMergeDriverRun(args[1:])
	case "install":
		return runMergeDriverInstall(args[1:])
	default:
		fmt.Fprintf(os.Stderr,
			"mdsmith: merge-driver: unknown subcommand %q\n\n%s",
			args[0], mergeDriverUsage)
		return 2
	}
}
main.runMergeDriverRun function · go · L65-L123 (59 LOC)
cmd/mdsmith/mergedriver.go
func runMergeDriverRun(args []string) int {
	if len(args) > 0 && (args[0] == "--help" || args[0] == "-h") {
		fmt.Fprint(os.Stderr, mergeDriverUsage)
		return 0
	}

	if len(args) < 4 {
		fmt.Fprintf(os.Stderr,
			"mdsmith: merge-driver run requires 4 arguments: "+
				"base ours theirs pathname\n")
		return 2
	}

	base, ours, theirs, pathname := args[0], args[1], args[2], args[3]

	// Step 1: standard 3-way merge into ours.
	mergeCmd := exec.Command("git", "merge-file", ours, base, theirs)
	mergeCmd.Stderr = os.Stderr
	mergeErr := mergeCmd.Run()

	// git merge-file exits 1 for conflicts, 2+ for fatal errors.
	// Non-ExitError (e.g. git not found) is also fatal.
	if mergeErr != nil {
		if exitErr, ok := mergeErr.(*exec.ExitError); !ok || exitErr.ExitCode() != 1 {
			fmt.Fprintf(os.Stderr, "mdsmith: git merge-file failed: %v\n", mergeErr)
			return 2
		}
	}

	// Step 2: strip conflict markers inside regenerable sections.
	content, err := os.ReadFile(ours)
	if err != nil {
		fmt.Fprintf(o
main.fixAtRealPath function · go · L127-L178 (52 LOC)
cmd/mdsmith/mergedriver.go
func fixAtRealPath(cleaned []byte, ours, pathname string) ([]byte, int) {
	// Capture the original file mode so we can preserve permissions.
	fileMode := os.FileMode(0644)
	if info, err := os.Stat(pathname); err == nil {
		fileMode = info.Mode()
	}

	backup, backupErr := os.ReadFile(pathname)
	if backupErr != nil && !os.IsNotExist(backupErr) {
		fmt.Fprintf(os.Stderr, "mdsmith: reading %s for backup: %v\n", pathname, backupErr)
		return nil, 2
	}
	if err := os.WriteFile(pathname, cleaned, fileMode); err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: writing to %s: %v\n", pathname, err)
		return nil, 2
	}

	fixErr := fixFileInPlace(pathname)

	// Restore the original working tree file before checking
	// fixErr, so the working tree is always left clean.
	fixed, err := os.ReadFile(pathname)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: reading fixed file: %v\n", err)
		return nil, 2
	}

	var restoreErr error
	if backupErr == nil {
		restoreErr = os.WriteFile(pathname, backup, fileMode
Want fix-PRs on findings? Install Repobility's GitHub App · github.com/apps/repobility-bot
main.fixFileInPlace function · go · L181-L199 (19 LOC)
cmd/mdsmith/mergedriver.go
func fixFileInPlace(path string) error {
	cfg, _, err := loadConfig("")
	if err != nil {
		return fmt.Errorf("loading config: %w", err)
	}

	fixer := &fixpkg.Fixer{
		Config:           cfg,
		Rules:            rule.All(),
		StripFrontMatter: frontMatterEnabled(cfg),
		Logger:           &vlog.Logger{},
	}

	result := fixer.Fix([]string{path})
	if len(result.Errors) > 0 {
		return result.Errors[0]
	}
	return nil
}
main.isRegenSectionStart function · go · L210-L217 (8 LOC)
cmd/mdsmith/mergedriver.go
func isRegenSectionStart(line []byte) bool {
	for _, name := range regenSectionNames {
		if bytes.HasPrefix(line, []byte("<!-- "+name)) {
			return true
		}
	}
	return false
}
main.isRegenSectionEnd function · go · L221-L228 (8 LOC)
cmd/mdsmith/mergedriver.go
func isRegenSectionEnd(line []byte) bool {
	for _, name := range regenSectionNames {
		if bytes.Equal(line, []byte("<!-- /"+name+" -->")) {
			return true
		}
	}
	return false
}
main.stripSectionConflicts function · go · L237-L273 (37 LOC)
cmd/mdsmith/mergedriver.go
func stripSectionConflicts(content []byte) []byte {
	lines := bytes.Split(content, []byte("\n"))
	var out [][]byte
	inSection := false
	inConflict := false

	for _, line := range lines {
		trimmed := bytes.TrimSpace(line)

		if isRegenSectionStart(trimmed) {
			inSection = true
		}

		if inSection {
			if isConflictOpen(trimmed) {
				inConflict = true
				continue
			}
			if inConflict && isConflictClose(trimmed) {
				inConflict = false
				continue
			}
			if inConflict && isConflictSeparator(trimmed) {
				continue
			}
		}

		out = append(out, line)

		if isRegenSectionEnd(trimmed) {
			inSection = false
			inConflict = false
		}
	}

	return bytes.Join(out, []byte("\n"))
}
main.hasConflictMarkers function · go · L298-L306 (9 LOC)
cmd/mdsmith/mergedriver.go
func hasConflictMarkers(content []byte) bool {
	for _, line := range bytes.Split(content, []byte("\n")) {
		trimmed := bytes.TrimSpace(line)
		if isConflictOpen(trimmed) || isConflictClose(trimmed) {
			return true
		}
	}
	return false
}
main.runMergeDriverInstall function · go · L314-L351 (38 LOC)
cmd/mdsmith/mergedriver.go
func runMergeDriverInstall(args []string) int {
	if len(args) > 0 && (args[0] == "--help" || args[0] == "-h") {
		fmt.Fprint(os.Stderr, mergeDriverUsage)
		return 0
	}

	// Verify we're in a git repo.
	cmd := exec.Command("git", "rev-parse", "--show-toplevel")
	out, err := cmd.Output()
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: not in a git repository\n")
		return 2
	}
	repoRoot := strings.TrimSpace(string(out))

	if err := registerMergeDriver(); err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}

	// Determine file list: use args if given, else defaults.
	files := defaultMergeDriverFiles
	if len(args) > 0 {
		files = args
	}

	attrPath := filepath.Join(repoRoot, ".gitattributes")
	if err := ensureGitattributes(attrPath, files); err != nil {
		fmt.Fprintf(os.Stderr,
			"mdsmith: updating .gitattributes: %v\n", err)
		return 2
	}

	fmt.Fprintf(os.Stderr, "mdsmith: merge driver 'mdsmith' installed\n")
	fmt.Fprintf(os.Stderr, "  git config: merge.mdsmith.dr
main.registerMergeDriver function · go · L355-L368 (14 LOC)
cmd/mdsmith/mergedriver.go
func registerMergeDriver() error {
	driver := "mdsmith merge-driver run %O %A %B %P"
	cmds := [][]string{
		{"git", "config", "merge.mdsmith.name",
			"mdsmith section-aware Markdown merge"},
		{"git", "config", "merge.mdsmith.driver", driver},
	}
	for _, c := range cmds {
		if err := exec.Command(c[0], c[1:]...).Run(); err != nil {
			return fmt.Errorf("git config failed: %w", err)
		}
	}
	return nil
}
main.ensureGitattributes function · go · L372-L414 (43 LOC)
cmd/mdsmith/mergedriver.go
func ensureGitattributes(path string, files []string) error {
	existing, err := os.ReadFile(path)
	if err != nil && !os.IsNotExist(err) {
		return fmt.Errorf("reading %s: %w", path, err)
	}
	content := string(existing)

	// Build entries from file list.
	entries := make([]string, len(files))
	for i, f := range files {
		entries[i] = f + " merge=mdsmith"
	}

	// Build a set of normalized existing lines to avoid substring
	// matches against comments or whitespace differences.
	existingSet := make(map[string]struct{})
	for _, line := range strings.Split(content, "\n") {
		norm := strings.Join(strings.Fields(line), " ")
		if norm != "" {
			existingSet[norm] = struct{}{}
		}
	}

	var missing []string
	for _, entry := range entries {
		norm := strings.Join(strings.Fields(entry), " ")
		if _, ok := existingSet[norm]; !ok {
			missing = append(missing, entry)
		}
	}

	if len(missing) == 0 {
		return nil
	}

	// Ensure trailing newline before appending.
	if len(content) > 0 && !strings.HasSuf
Repobility · open methodology · https://repobility.com/research/
main.runMetrics function · go · L23-L38 (16 LOC)
cmd/mdsmith/metrics.go
func runMetrics(args []string) int {
	if len(args) == 0 {
		fmt.Fprint(os.Stderr, metricsUsageText)
		return 0
	}

	switch args[0] {
	case "list":
		return runMetricsList(args[1:])
	case "rank":
		return runMetricsRank(args[1:])
	default:
		fmt.Fprintf(os.Stderr, "mdsmith: metrics: unknown command %q\n", args[0])
		return 2
	}
}
main.runMetricsList function · go · L40-L91 (52 LOC)
cmd/mdsmith/metrics.go
func runMetricsList(args []string) int {
	fs := flag.NewFlagSet("metrics list", flag.ContinueOnError)
	var (
		scopeRaw string
		format   string
	)

	fs.StringVar(&scopeRaw, "scope", "file", "Metric scope: file")
	fs.StringVarP(&format, "format", "f", "text", "Output format: text, json")
	fs.Usage = func() {
		fmt.Fprintf(
			os.Stderr,
			"Usage: mdsmith metrics list [flags]\n\n"+
				"List available metrics in the shared registry.\n\n"+
				"Flags:\n",
		)
		fs.PrintDefaults()
	}

	if err := fs.Parse(args); err != nil {
		return 2
	}
	if fs.NArg() > 0 {
		fmt.Fprintf(os.Stderr, "mdsmith: metrics list takes no file arguments\n")
		return 2
	}

	scope, err := metricspkg.ParseScope(scopeRaw)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}

	defs := metricspkg.ForScope(scope)
	switch format {
	case "text":
		if err := writeMetricsListText(defs); err != nil {
			fmt.Fprintf(os.Stderr, "mdsmith: writing output: %v\n", err)
			return 2
		}
	case "json":
		if er
main.runMetricsRank function · go · L104-L111 (8 LOC)
cmd/mdsmith/metrics.go
func runMetricsRank(args []string) int {
	opts, fileArgs, err := parseMetricsRankOptions(args)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	return executeMetricsRank(opts, fileArgs)
}
main.parseMetricsRankOptions function · go · L113-L150 (38 LOC)
cmd/mdsmith/metrics.go
func parseMetricsRankOptions(args []string) (metricsRankOptions, []string, error) {
	fs := flag.NewFlagSet("metrics rank", flag.ContinueOnError)
	var opts metricsRankOptions

	fs.StringVarP(&opts.configPath, "config", "c", "", "Override config file path")
	fs.StringVar(&opts.metricsRaw, "metrics", "", "Comma-separated metrics (defaults to registry defaults)")
	fs.StringVar(&opts.byRaw, "by", "", "Metric to sort by")
	fs.StringVar(&opts.orderRaw, "order", "", "Sort order: asc or desc (defaults by metric)")
	fs.IntVar(&opts.top, "top", 0, "Limit results to top N files (0 = all)")
	fs.StringVarP(&opts.format, "format", "f", "text", "Output format: text, json")
	fs.BoolVar(&opts.noGitignore, "no-gitignore", false, "Disable .gitignore filtering when walking directories")
	fs.BoolVar(&opts.noFollowSymlinks, "no-follow-symlinks", false, "Skip symbolic links when walking directories")

	fs.Usage = func() {
		fmt.Fprintf(
			os.Stderr,
			"Usage: mdsmith metrics rank [flags] [files...]\n\n"+
		
main.executeMetricsRank function · go · L152-L183 (32 LOC)
cmd/mdsmith/metrics.go
func executeMetricsRank(opts metricsRankOptions, fileArgs []string) int {
	defs, byDef, order, err := resolveRankSelection(opts)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}

	files, err := resolveRankFiles(opts, fileArgs)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}

	rows, err := metricspkg.Collect(files, defs)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	metricspkg.SortRows(rows, byDef, order)
	rows = metricspkg.LimitRows(rows, opts.top)

	if err := writeRankOutput(opts.format, rows, defs); err != nil {
		if strings.Contains(err.Error(), "unknown format") {
			fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
			return 2
		}
		fmt.Fprintf(os.Stderr, "mdsmith: writing output: %v\n", err)
		return 2
	}

	return 0
}
main.resolveRankSelection function · go · L185-L227 (43 LOC)
cmd/mdsmith/metrics.go
func resolveRankSelection(
	opts metricsRankOptions,
) ([]metricspkg.Definition, metricspkg.Definition, metricspkg.Order, error) {
	scope := metricspkg.ScopeFile
	selectedNames := metricspkg.SplitList(opts.metricsRaw)
	defs, err := metricspkg.Resolve(scope, selectedNames)
	if err != nil {
		return nil, metricspkg.Definition{}, "", err
	}

	var byDef metricspkg.Definition
	if strings.TrimSpace(opts.byRaw) == "" {
		byDef = defs[0]
	} else {
		byDefs, err := metricspkg.Resolve(scope, []string{opts.byRaw})
		if err != nil {
			return nil, metricspkg.Definition{}, "", err
		}
		byDef = byDefs[0]
	}

	// Ensure the sort metric is always computed.
	if !containsMetric(defs, byDef.ID) {
		if len(selectedNames) > 0 {
			return nil, metricspkg.Definition{}, "", fmt.Errorf(
				"--by metric %q must be included in --metrics",
				byDef.Name,
			)
		}
		defs = append(defs, byDef)
	}

	order := byDef.DefaultOrder
	if strings.TrimSpace(opts.orderRaw) != "" {
		parsed, err := metricspkg.ParseOrder(opt
main.resolveRankFiles function · go · L229-L237 (9 LOC)
cmd/mdsmith/metrics.go
func resolveRankFiles(opts metricsRankOptions, fileArgs []string) ([]string, error) {
	cfg, _, err := loadConfig(opts.configPath)
	if err != nil {
		return nil, err
	}

	resolveOptions := resolveOpts(cfg, opts.noGitignore, opts.noFollowSymlinks)
	return lint.ResolveFilesWithOpts(fileArgs, resolveOptions)
}
main.writeRankOutput function · go · L239-L252 (14 LOC)
cmd/mdsmith/metrics.go
func writeRankOutput(
	format string,
	rows []metricspkg.Row,
	defs []metricspkg.Definition,
) error {
	switch format {
	case "text":
		return writeMetricsRankText(rows, defs)
	case "json":
		return writeMetricsRankJSON(rows, defs)
	default:
		return fmt.Errorf("unknown format %q (supported: text, json)", format)
	}
}
Repobility's GitHub App fixes findings like these · https://github.com/apps/repobility-bot
main.containsMetric function · go · L254-L261 (8 LOC)
cmd/mdsmith/metrics.go
func containsMetric(defs []metricspkg.Definition, id string) bool {
	for _, def := range defs {
		if def.ID == id {
			return true
		}
	}
	return false
}
main.writeMetricsListText function · go · L263-L283 (21 LOC)
cmd/mdsmith/metrics.go
func writeMetricsListText(defs []metricspkg.Definition) error {
	tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
	if _, err := fmt.Fprintln(tw, "ID\tNAME\tSCOPE\tORDER\tDEFAULT\tDESCRIPTION"); err != nil {
		return err
	}
	for _, def := range defs {
		if _, err := fmt.Fprintf(
			tw,
			"%s\t%s\t%s\t%s\t%t\t%s\n",
			def.ID,
			def.Name,
			def.Scope,
			def.DefaultOrder,
			def.Default,
			def.Description,
		); err != nil {
			return err
		}
	}
	return tw.Flush()
}
main.writeMetricsListJSON function · go · L285-L300 (16 LOC)
cmd/mdsmith/metrics.go
func writeMetricsListJSON(defs []metricspkg.Definition) error {
	items := make([]map[string]any, 0, len(defs))
	for _, def := range defs {
		items = append(items, map[string]any{
			"id":            def.ID,
			"name":          def.Name,
			"description":   def.Description,
			"scope":         def.Scope,
			"default":       def.Default,
			"default_order": def.DefaultOrder,
		})
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	return enc.Encode(items)
}
main.writeMetricsRankText function · go · L302-L326 (25 LOC)
cmd/mdsmith/metrics.go
func writeMetricsRankText(rows []metricspkg.Row, defs []metricspkg.Definition) error {
	tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)

	var headers []string
	for _, def := range defs {
		headers = append(headers, strings.ToUpper(def.Name))
	}
	headers = append(headers, "PATH")
	if _, err := fmt.Fprintln(tw, strings.Join(headers, "\t")); err != nil {
		return err
	}

	for _, row := range rows {
		cols := make([]string, 0, len(defs)+1)
		for _, def := range defs {
			cols = append(cols, metricspkg.FormatValue(def, row.Metrics[def.Name]))
		}
		cols = append(cols, row.Path)
		if _, err := fmt.Fprintln(tw, strings.Join(cols, "\t")); err != nil {
			return err
		}
	}

	return tw.Flush()
}
main.writeMetricsRankJSON function · go · L328-L342 (15 LOC)
cmd/mdsmith/metrics.go
func writeMetricsRankJSON(rows []metricspkg.Row, defs []metricspkg.Definition) error {
	items := make([]map[string]any, 0, len(rows))
	for _, row := range rows {
		item := map[string]any{
			"path": row.Path,
		}
		for _, def := range defs {
			item[def.Name] = metricspkg.JSONValue(def, row.Metrics[def.Name])
		}
		items = append(items, item)
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	return enc.Encode(items)
}
main.runHelpMetrics function · go · L344-L349 (6 LOC)
cmd/mdsmith/metrics.go
func runHelpMetrics(args []string) int {
	if len(args) == 0 {
		return listAllMetrics()
	}
	return showMetric(args[0])
}
main.listAllMetrics function · go · L351-L362 (12 LOC)
cmd/mdsmith/metrics.go
func listAllMetrics() int {
	metrics, err := metricspkg.ListDocs()
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}

	for _, m := range metrics {
		fmt.Printf("%-6s %-20s %s\n", m.ID, m.Name, m.Description)
	}
	return 0
}
main.showMetric function · go · L364-L372 (9 LOC)
cmd/mdsmith/metrics.go
func showMetric(query string) int {
	content, err := metricspkg.LookupDoc(query)
	if err != nil {
		fmt.Fprintf(os.Stderr, "mdsmith: %v\n", err)
		return 2
	}
	fmt.Print(content)
	return 0
}
Generated by Repobility's multi-pass static-analysis pipeline (https://repobility.com)
gensection.NewEngine function · go · L17-L23 (7 LOC)
internal/archetype/gensection/engine.go
func NewEngine(d Directive) *Engine {
	return &Engine{
		directive:   d,
		startPrefix: "<!-- " + d.Name(),
		endMarker:   "<!-- /" + d.Name() + " -->",
	}
}
gensection.Engine.Check method · go · L26-L36 (11 LOC)
internal/archetype/gensection/engine.go
func (e *Engine) Check(f *lint.File) []lint.Diagnostic {
	pairs, diags := FindMarkerPairs(
		f, e.startPrefix, e.endMarker,
		e.directive.RuleID(), e.directive.RuleName(),
	)
	for _, mp := range pairs {
		pairDiags := e.checkPair(f, mp)
		diags = append(diags, pairDiags...)
	}
	return diags
}
gensection.Engine.Fix method · go · L39-L58 (20 LOC)
internal/archetype/gensection/engine.go
func (e *Engine) Fix(f *lint.File) []byte {
	pairs, _ := FindMarkerPairs(
		f, e.startPrefix, e.endMarker,
		e.directive.RuleID(), e.directive.RuleName(),
	)

	// Work backwards to preserve line numbers.
	for i := len(pairs) - 1; i >= 0; i-- {
		mp := pairs[i]
		expected, ok := e.generateContent(f, mp)
		if !ok {
			continue
		}

		f.Source = ReplaceContent(f, mp, expected)
		f.Lines = SplitLines(f.Source)
	}

	return f.Source
}
page 1 / 10next ›