Best K6 code snippet using fsext.Remove
archive.go
Source:archive.go
1/*2 *3 * k6 - a next-generation load testing tool4 * Copyright (C) 2016 Load Impact5 *6 * This program is free software: you can redistribute it and/or modify7 * it under the terms of the GNU Affero General Public License as8 * published by the Free Software Foundation, either version 3 of the9 * License, or (at your option) any later version.10 *11 * This program is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14 * GNU Affero General Public License for more details.15 *16 * You should have received a copy of the GNU Affero General Public License17 * along with this program. If not, see <http://www.gnu.org/licenses/>.18 *19 */20package lib21import (22 "archive/tar"23 "bytes"24 "encoding/json"25 "fmt"26 "io"27 "io/ioutil"28 "net/url"29 "os"30 "path"31 "path/filepath"32 "regexp"33 "sort"34 "strings"35 "time"36 "github.com/spf13/afero"37 "go.k6.io/k6/lib/fsext"38 "go.k6.io/k6/loader"39)40//nolint: gochecknoglobals, lll41var (42 volumeRE = regexp.MustCompile(`^[/\\]?([a-zA-Z]):(.*)`)43 sharedRE = regexp.MustCompile(`^\\\\([^\\]+)`) // matches a shared folder in Windows before backslack replacement. i.e \\VMBOXSVR\k6\script.js44 homeDirRE = regexp.MustCompile(`(?i)^(/[a-zA-Z])?/(Users|home|Documents and Settings)/(?:[^/]+)`)45)46// NormalizeAndAnonymizePath Normalizes (to use a / path separator) and anonymizes a file path, by scrubbing usernames from home directories.47func NormalizeAndAnonymizePath(path string) string {48 path = filepath.Clean(path)49 p := volumeRE.ReplaceAllString(path, `/$1$2`)50 p = sharedRE.ReplaceAllString(p, `/nobody`)51 p = strings.Replace(p, "\\", "/", -1)52 return homeDirRE.ReplaceAllString(p, `$1/$2/nobody`)53}54func newNormalizedFs(fs afero.Fs) afero.Fs {55 return fsext.NewChangePathFs(fs, fsext.ChangePathFunc(func(name string) (string, error) {56 return NormalizeAndAnonymizePath(name), nil57 }))58}59// An Archive is a rollup of all resources and options needed to reproduce a test identically elsewhere.60type Archive struct {61 // The runner to use, eg. "js".62 Type string `json:"type"`63 // Options to use.64 Options Options `json:"options"`65 // TODO: rewrite the encoding, decoding of json to use another type with only the fields it66 // needs in order to remove Filename and Pwd from this67 // Filename and contents of the main file being executed.68 Filename string `json:"filename"` // only for json69 FilenameURL *url.URL `json:"-"`70 Data []byte `json:"-"`71 // Working directory for resolving relative paths.72 Pwd string `json:"pwd"` // only for json73 PwdURL *url.URL `json:"-"`74 Filesystems map[string]afero.Fs `json:"-"`75 // Environment variables76 Env map[string]string `json:"env"`77 CompatibilityMode string `json:"compatibilityMode"`78 K6Version string `json:"k6version"`79 Goos string `json:"goos"`80}81func (arc *Archive) getFs(name string) afero.Fs {82 fs, ok := arc.Filesystems[name]83 if !ok {84 fs = afero.NewMemMapFs()85 if name == "file" {86 fs = newNormalizedFs(fs)87 }88 arc.Filesystems[name] = fs89 }90 return fs91}92func (arc *Archive) loadMetadataJSON(data []byte) (err error) {93 if err = json.Unmarshal(data, &arc); err != nil {94 return err95 }96 // Path separator normalization for older archives (<=0.20.0)97 if arc.K6Version == "" {98 arc.Filename = NormalizeAndAnonymizePath(arc.Filename)99 arc.Pwd = NormalizeAndAnonymizePath(arc.Pwd)100 }101 arc.PwdURL, err = loader.Resolve(&url.URL{Scheme: "file", Path: "/"}, arc.Pwd)102 if err != nil {103 return err104 }105 arc.FilenameURL, err = loader.Resolve(&url.URL{Scheme: "file", Path: "/"}, arc.Filename)106 if err != nil {107 return err108 }109 return nil110}111// ReadArchive reads an archive created by Archive.Write from a reader.112func ReadArchive(in io.Reader) (*Archive, error) {113 r := tar.NewReader(in)114 arc := &Archive{Filesystems: make(map[string]afero.Fs, 2)}115 // initialize both fses116 _ = arc.getFs("https")117 _ = arc.getFs("file")118 for {119 hdr, err := r.Next()120 if err != nil {121 if err == io.EOF {122 break123 }124 return nil, err125 }126 if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA {127 continue128 }129 data, err := ioutil.ReadAll(r)130 if err != nil {131 return nil, err132 }133 switch hdr.Name {134 case "metadata.json":135 if err = arc.loadMetadataJSON(data); err != nil {136 return nil, err137 }138 continue139 case "data":140 arc.Data = data141 continue142 }143 // Path separator normalization for older archives (<=0.20.0)144 normPath := NormalizeAndAnonymizePath(hdr.Name)145 idx := strings.IndexRune(normPath, '/')146 if idx == -1 {147 continue148 }149 pfx := normPath[:idx]150 name := normPath[idx:]151 switch pfx {152 case "files", "scripts": // old archives153 // in old archives (pre 0.25.0) names without "_" at the beginning were https, the ones with "_" are local files154 pfx = "https"155 if len(name) >= 2 && name[0:2] == "/_" {156 pfx = "file"157 name = name[2:]158 }159 fallthrough160 case "https", "file":161 fs := arc.getFs(pfx)162 name = filepath.FromSlash(name)163 err = afero.WriteFile(fs, name, data, os.FileMode(hdr.Mode))164 if err != nil {165 return nil, err166 }167 err = fs.Chtimes(name, hdr.AccessTime, hdr.ModTime)168 if err != nil {169 return nil, err170 }171 default:172 return nil, fmt.Errorf("unknown file prefix `%s` for file `%s`", pfx, normPath)173 }174 }175 scheme, pathOnFs := getURLPathOnFs(arc.FilenameURL)176 var err error177 pathOnFs, err = url.PathUnescape(pathOnFs)178 if err != nil {179 return nil, err180 }181 err = afero.WriteFile(arc.getFs(scheme), pathOnFs, arc.Data, 0o644) // TODO fix the mode ?182 if err != nil {183 return nil, err184 }185 return arc, nil186}187func normalizeAndAnonymizeURL(u *url.URL) {188 if u.Scheme == "file" {189 u.Path = NormalizeAndAnonymizePath(u.Path)190 }191}192func getURLPathOnFs(u *url.URL) (scheme string, pathOnFs string) {193 scheme = "https"194 switch {195 case u.Opaque != "":196 return scheme, "/" + u.Opaque197 case u.Scheme == "":198 return scheme, path.Clean(u.String()[len("//"):])199 default:200 scheme = u.Scheme201 }202 return scheme, path.Clean(u.String()[len(u.Scheme)+len(":/"):])203}204func getURLtoString(u *url.URL) string {205 if u.Opaque == "" && u.Scheme == "" {206 return u.String()[len("//"):] // https url without a scheme207 }208 return u.String()209}210// Write serialises the archive to a writer.211//212// The format should be treated as opaque; currently it is simply a TAR rollup, but this may213// change. If it does change, ReadArchive must be able to handle all previous formats as well as214// the current one.215func (arc *Archive) Write(out io.Writer) error {216 w := tar.NewWriter(out)217 now := time.Now()218 metaArc := *arc219 normalizeAndAnonymizeURL(metaArc.FilenameURL)220 normalizeAndAnonymizeURL(metaArc.PwdURL)221 metaArc.Filename = getURLtoString(metaArc.FilenameURL)222 metaArc.Pwd = getURLtoString(metaArc.PwdURL)223 actualDataPath, err := url.PathUnescape(path.Join(getURLPathOnFs(metaArc.FilenameURL)))224 if err != nil {225 return err226 }227 var madeLinkToData bool228 metadata, err := metaArc.json()229 if err != nil {230 return err231 }232 _ = w.WriteHeader(&tar.Header{233 Name: "metadata.json",234 Mode: 0o644,235 Size: int64(len(metadata)),236 ModTime: now,237 Typeflag: tar.TypeReg,238 })239 if _, err = w.Write(metadata); err != nil {240 return err241 }242 _ = w.WriteHeader(&tar.Header{243 Name: "data",244 Mode: 0o644,245 Size: int64(len(arc.Data)),246 ModTime: now,247 Typeflag: tar.TypeReg,248 })249 if _, err = w.Write(arc.Data); err != nil {250 return err251 }252 for _, name := range [...]string{"file", "https"} {253 filesystem, ok := arc.Filesystems[name]254 if !ok {255 continue256 }257 if cachedfs, ok := filesystem.(fsext.CacheLayerGetter); ok {258 filesystem = cachedfs.GetCachingFs()259 }260 // A couple of things going on here:261 // - You can't just create file entries, you need to create directory entries too.262 // Figure out which directories are in use here.263 // - We want archives to be comparable by hash, which means the entries need to be written264 // in the same order every time. Go maps are shuffled, so we need to sort lists of keys.265 // - We don't want to leak private information (eg. usernames) in archives, so make sure to266 // anonymize paths before stuffing them in a shareable archive.267 foundDirs := make(map[string]bool)268 paths := make([]string, 0, 10)269 infos := make(map[string]os.FileInfo) // ... fix this ?270 files := make(map[string][]byte)271 walkFunc := filepath.WalkFunc(func(filePath string, info os.FileInfo, err error) error {272 if err != nil {273 return err274 }275 normalizedPath := NormalizeAndAnonymizePath(filePath)276 infos[normalizedPath] = info277 if info.IsDir() {278 foundDirs[normalizedPath] = true279 return nil280 }281 paths = append(paths, normalizedPath)282 files[normalizedPath], err = afero.ReadFile(filesystem, filePath)283 return err284 })285 if err = fsext.Walk(filesystem, afero.FilePathSeparator, walkFunc); err != nil {286 return err287 }288 if len(files) == 0 {289 continue // we don't need to write anything for this fs, if this is not done the root will be written290 }291 dirs := make([]string, 0, len(foundDirs))292 for dirpath := range foundDirs {293 dirs = append(dirs, dirpath)294 }295 sort.Strings(paths)296 sort.Strings(dirs)297 for _, dirPath := range dirs {298 _ = w.WriteHeader(&tar.Header{299 Name: path.Clean(path.Join(name, dirPath)),300 Mode: 0o755, // MemMapFs is buggy301 AccessTime: now, // MemMapFs is buggy302 ChangeTime: now, // MemMapFs is buggy303 ModTime: now, // MemMapFs is buggy304 Typeflag: tar.TypeDir,305 })306 }307 for _, filePath := range paths {308 fullFilePath := path.Clean(path.Join(name, filePath))309 // we either have opaque310 if fullFilePath == actualDataPath {311 madeLinkToData = true312 err = w.WriteHeader(&tar.Header{313 Name: fullFilePath,314 Size: 0,315 Typeflag: tar.TypeLink,316 Linkname: "data",317 })318 } else {319 err = w.WriteHeader(&tar.Header{320 Name: fullFilePath,321 Mode: 0o644, // MemMapFs is buggy322 Size: int64(len(files[filePath])),323 AccessTime: infos[filePath].ModTime(),324 ChangeTime: infos[filePath].ModTime(),325 ModTime: infos[filePath].ModTime(),326 Typeflag: tar.TypeReg,327 })328 if err == nil {329 _, err = w.Write(files[filePath])330 }331 }332 if err != nil {333 return err334 }335 }336 }337 if !madeLinkToData {338 // This should never happen we should always link to `data` from inside the file/https directories339 return fmt.Errorf("archive creation failed because the main script wasn't present in the cached filesystem")340 }341 return w.Close()342}343func (arc *Archive) json() ([]byte, error) {344 buffer := &bytes.Buffer{}345 encoder := json.NewEncoder(buffer)346 // this prevents <, >, and & from being escaped in JSON strings347 encoder.SetEscapeHTML(false)348 encoder.SetIndent("", " ")349 if err := encoder.Encode(arc); err != nil {350 return nil, err351 }352 return buffer.Bytes(), nil353}...
Remove
Using AI Code Generation
1import (2func main() {3 fsrc, err := fs.NewFs("local:./")4 if err != nil {5 fmt.Println(err)6 }7 fsext.Remove(fsrc, "test.txt")8}9import (10func main() {11 fsrc, err := fs.NewFs("local:./")12 if err != nil {13 fmt.Println(err)14 }15 fsext.Put(fsrc, "test.txt", "test.txt")16}17import (18func main() {19 fsrc, err := fs.NewFs("local:./")20 if err != nil {21 fmt.Println(err)22 }23 fsext.PutStream(fsrc, "test.txt", "test.txt")24}25import (26func main() {27 fsrc, err := fs.NewFs("local:./")28 if err != nil {29 fmt.Println(err)30 }31 fsext.PutStreamUpdate(fsrc, "test.txt", "test.txt")32}33import (34func main() {35 fsrc, err := fs.NewFs("local:./")36 if err != nil {37 fmt.Println(err)38 }39 fsext.Purge(fsrc, "test.txt")40}
Remove
Using AI Code Generation
1import (2func main() {3 if err := copy.Copy(testdata.Path("copy"), "/tmp/copy"); err != nil {4 panic(err)5 }6 if err := copy.Copy("/tmp/copy", "/tmp/paste"); err != nil {7 panic(err)8 }9 if err := copy.Copy("/tmp/paste", "/tmp/overwrite"); err != nil {10 panic(err)11 }12 if err := copy.Copy("/tmp/overwrite", "/tmp/overwrite"); err != nil {13 panic(err)14 }15 if err := copy.Copy("/tmp/overwrite", "/tmp/overwrite"); err != nil {16 panic(err)17 }18 if err := copy.Copy("/tmp/overwrite", "/tmp/overwrite"); err != nil {19 panic(err)20 }21 if err := copy.Copy("/tmp/overwrite", "/tmp/overwrite"); err != nil {22 panic(err)23 }24 if err := copy.Copy("/tmp/overwrite", "/tmp/overwrite"); err != nil {25 panic(err)26 }27 if err := copy.Copy("/tmp/overwrite", "/tmp/overwrite"); err != nil {28 panic(err)29 }30 if err := copy.Copy("/tmp/overwrite", "/tmp/overwrite"); err != nil {31 panic(err)32 }33 if err := copy.Copy("/tmp/overwrite", "/tmp/overwrite"); err != nil {
Remove
Using AI Code Generation
1import (2func main() {3 db, err := leveldb.OpenFile("db", nil)4 if err != nil {5 fmt.Println("Error in creating a new database", err)6 }7 u, err := uuid.NewV4()8 if err != nil {9 fmt.Println("Error in creating a new uuid", err)10 }11 u1, err := uuid.NewV4()12 if err != nil {13 fmt.Println("Error in creating a new uuid", err)14 }15 u2, err := uuid.NewV4()16 if err != nil {17 fmt.Println("Error in creating a new uuid", err)18 }19 u3, err := uuid.NewV4()20 if err != nil {21 fmt.Println("Error in creating a new uuid", err)22 }23 u4, err := uuid.NewV4()24 if err != nil {25 fmt.Println("Error in creating a new uuid", err)26 }27 u5, err := uuid.NewV4()28 if err != nil {29 fmt.Println("Error in creating a new uuid", err)30 }31 u6, err := uuid.NewV4()32 if err != nil {33 fmt.Println("Error in creating a new uuid", err)34 }35 u7, err := uuid.NewV4()36 if err != nil {37 fmt.Println("Error in creating a new uuid", err)38 }39 u8, err := uuid.NewV4()40 if err != nil {41 fmt.Println("Error in creating a new uuid", err)42 }43 u9, err := uuid.NewV4()44 if err != nil {45 fmt.Println("Error in creating a new uuid", err)46 }47 u10, err := uuid.NewV4()
Remove
Using AI Code Generation
1import (2func main() {3 fmt.Println("Enter the path of the file to be removed")4 reader := bufio.NewReader(os.Stdin)5 path, _ = reader.ReadString('6 path = filepath.Clean(path)7 err := os.Remove(path)8 if err != nil {9 fmt.Println(err)10 }11 fmt.Println("File Removed")12}13GoLang os.Rename() Method14Rename(oldname, newname string) error15import (16func main() {17 fmt.Println("Enter the path of the file to be renamed")18 reader := bufio.NewReader(os.Stdin)19 old, _ = reader.ReadString('20 fmt.Println("Enter the new name of the file")21 new, _ = reader.ReadString('22 err := os.Rename(old, new)23 if err != nil {24 fmt.Println(err)25 }26 fmt.Println("File Renamed")27}28GoLang os.Stat() Method29Stat(name string) (FileInfo, error)
Remove
Using AI Code Generation
1import (2func main() {3 lock, err := lockfile.New(filepath.Join(os.TempDir(), "test.lock"))4 if err != nil {5 fmt.Println("Error in creating lock file")6 }7 err = lock.TryLock()8 if err != nil {9 fmt.Println("Error in locking file")10 }11 defer lock.Unlock()12 f, err := os.Create("test.txt")13 if err != nil {14 fmt.Println("Error in creating file")15 }16 defer f.Close()17 f.WriteString("Hello World")18 err = os.Remove("test.txt")19 if err != nil {20 fmt.Println("Error in removing file")21 }22}
Remove
Using AI Code Generation
1import (2func main() {3 f, err := lockfile.New("/tmp/lockfile")4 if err != nil {5 log.Fatal(err)6 }7 err = f.TryLock()8 if err != nil {9 log.Fatal(err)10 }11 fmt.Println("Lock acquired. Hit enter to release")12 os.Stdin.Read([]byte{0})13 f.Unlock()14}
Remove
Using AI Code Generation
1import (2func main() {3 err := os.Remove(path)4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println("File removed")8}
Remove
Using AI Code Generation
1import (2func main() {3 fsext := fsext.New()4 err := fsext.Remove("test")5 if err != nil {6 fmt.Println("error removing directory")7 }8}9import (10func main() {11 fsext := fsext.New()12 err := fsext.RemoveAll("test")13 if err != nil {14 fmt.Println("error removing directory")15 }16}17import (18func main() {19 fsext := fsext.New()20 err := fsext.RemoveAll("test")21 if err != nil {22 fmt.Println("error removing directory")23 }24}25import (26func main() {27 fsext := fsext.New()28 err := fsext.RemoveAll("test")29 if err != nil {30 fmt.Println("error removing directory")31 }32}33import (34func main() {35 fsext := fsext.New()36 err := fsext.RemoveAll("test")37 if err != nil {38 fmt.Println("error removing directory")39 }40}41import (42func main() {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!