github.com/goplus/llgo@v0.8.3/internal/build/clean.go (about)

     1  /*
     2   * Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package build
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"path"
    23  	"path/filepath"
    24  
    25  	"golang.org/x/tools/go/packages"
    26  )
    27  
    28  var (
    29  	// TODO(xsw): complete clean flags
    30  	cleanFlags = map[string]bool{
    31  		"-v": false, // -v: print the paths of packages as they are clean
    32  	}
    33  )
    34  
    35  func Clean(args []string, conf *Config) {
    36  	flags, patterns, verbose := ParseArgs(args, cleanFlags)
    37  	cfg := &packages.Config{
    38  		Mode:       loadSyntax | packages.NeedExportFile,
    39  		BuildFlags: flags,
    40  	}
    41  
    42  	if patterns == nil {
    43  		patterns = []string{"."}
    44  	}
    45  	initial, err := packages.Load(cfg, patterns...)
    46  	check(err)
    47  
    48  	cleanPkgs(initial, verbose)
    49  
    50  	for _, pkg := range initial {
    51  		if pkg.Name == "main" {
    52  			cleanMainPkg(pkg, conf, verbose)
    53  		}
    54  	}
    55  }
    56  
    57  func cleanMainPkg(pkg *packages.Package, conf *Config, verbose bool) {
    58  	pkgPath := pkg.PkgPath
    59  	name := path.Base(pkgPath)
    60  	fname := name + conf.AppExt
    61  	app := filepath.Join(conf.BinPath, fname)
    62  	removeFile(app, verbose)
    63  	if len(pkg.CompiledGoFiles) > 0 {
    64  		dir := filepath.Dir(pkg.CompiledGoFiles[0])
    65  		buildApp := filepath.Join(dir, fname)
    66  		removeFile(buildApp, verbose)
    67  	}
    68  }
    69  
    70  func cleanPkgs(initial []*packages.Package, verbose bool) {
    71  	packages.Visit(initial, nil, func(p *packages.Package) {
    72  		file := p.ExportFile + ".ll"
    73  		removeFile(file, verbose)
    74  	})
    75  }
    76  
    77  func removeFile(file string, verbose bool) {
    78  	if _, err := os.Stat(file); os.IsNotExist(err) {
    79  		return
    80  	}
    81  	if verbose {
    82  		fmt.Fprintln(os.Stderr, "Remove", file)
    83  	}
    84  	os.Remove(file)
    85  }