Best Syzkaller code snippet using vcs.Patch
vcs.go
Source:vcs.go
...85 return nil, err86 }87 return vcs, nil88}89// PatchVCS patches an instance of VCS.90func (s *Store) PatchVCS(ctx context.Context, patch *api.VCSPatch) (*api.VCS, error) {91 vcsRaw, err := s.patchVCSRaw(ctx, patch)92 if err != nil {93 return nil, errors.Wrapf(err, "failed to patch VCS with VCSPatch[%+v]", patch)94 }95 vcs, err := s.composeVCS(ctx, vcsRaw)96 if err != nil {97 return nil, errors.Wrapf(err, "failed to compose VCS with vcsRaw[%+v]", vcsRaw)98 }99 return vcs, nil100}101// DeleteVCS deletes an instance of VCS.102func (s *Store) DeleteVCS(ctx context.Context, delete *api.VCSDelete) error {103 if err := s.deleteVCSRaw(ctx, delete); err != nil {104 return errors.Wrapf(err, "failed to delete VCS with VCSDelete[%+v]", delete)105 }106 return nil107}108//109// private functions110//111func (s *Store) composeVCS(ctx context.Context, raw *vcsRaw) (*api.VCS, error) {112 vcs := raw.toVCS()113 creator, err := s.GetPrincipalByID(ctx, vcs.CreatorID)114 if err != nil {115 return nil, err116 }117 vcs.Creator = creator118 updater, err := s.GetPrincipalByID(ctx, vcs.UpdaterID)119 if err != nil {120 return nil, err121 }122 vcs.Updater = updater123 return vcs, nil124}125// createVCSRaw creates a new vcs.126func (s *Store) createVCSRaw(ctx context.Context, create *api.VCSCreate) (*vcsRaw, error) {127 tx, err := s.db.BeginTx(ctx, nil)128 if err != nil {129 return nil, FormatError(err)130 }131 defer tx.Rollback()132 vcs, err := createVCSImpl(ctx, tx, create)133 if err != nil {134 return nil, err135 }136 if err := tx.Commit(); err != nil {137 return nil, FormatError(err)138 }139 return vcs, nil140}141// findVCSRaw retrieves a list of VCSs based on find conditions.142func (s *Store) findVCSRaw(ctx context.Context, find *api.VCSFind) ([]*vcsRaw, error) {143 tx, err := s.db.BeginTx(ctx, nil)144 if err != nil {145 return nil, FormatError(err)146 }147 defer tx.Rollback()148 list, err := findVCSImpl(ctx, tx, find)149 if err != nil {150 return nil, err151 }152 return list, nil153}154// getVCSRaw retrieves a single vcs based on find.155// Returns ECONFLICT if finding more than 1 matching records.156func (s *Store) getVCSRaw(ctx context.Context, id int) (*vcsRaw, error) {157 tx, err := s.db.BeginTx(ctx, nil)158 if err != nil {159 return nil, FormatError(err)160 }161 defer tx.Rollback()162 find := &api.VCSFind{163 ID: &id,164 }165 list, err := findVCSImpl(ctx, tx, find)166 if err != nil {167 return nil, err168 }169 if len(list) == 0 {170 return nil, nil171 } else if len(list) > 1 {172 return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d VCSs with filter %+v, expect 1", len(list), find)}173 }174 return list[0], nil175}176// patchVCSRaw updates an existing vcs by ID.177// Returns ENOTFOUND if vcs does not exist.178func (s *Store) patchVCSRaw(ctx context.Context, patch *api.VCSPatch) (*vcsRaw, error) {179 tx, err := s.db.BeginTx(ctx, nil)180 if err != nil {181 return nil, FormatError(err)182 }183 defer tx.Rollback()184 vcs, err := patchVCSImpl(ctx, tx, patch)185 if err != nil {186 return nil, FormatError(err)187 }188 if err := tx.Commit(); err != nil {189 return nil, FormatError(err)190 }191 return vcs, nil192}193// deleteVCSRaw deletes an existing vcs by ID.194func (s *Store) deleteVCSRaw(ctx context.Context, delete *api.VCSDelete) error {195 tx, err := s.db.BeginTx(ctx, nil)196 if err != nil {197 return FormatError(err)198 }199 defer tx.Rollback()200 if err := s.deleteVCSImpl(ctx, tx, delete); err != nil {201 return FormatError(err)202 }203 if err := tx.Commit(); err != nil {204 return FormatError(err)205 }206 return nil207}208//209// database access implementations210//211// createVCSImpl creates a new vcs.212func createVCSImpl(ctx context.Context, tx *Tx, create *api.VCSCreate) (*vcsRaw, error) {213 // Insert row into database.214 query := `215 INSERT INTO vcs (216 creator_id,217 updater_id,218 name,219 type,220 instance_url,221 api_url,222 application_id,223 secret224 )225 VALUES ($1, $2, $3, $4, $5, $6, $7, $8)226 RETURNING id, creator_id, created_ts, updater_id, updated_ts, name, type, instance_url, api_url, application_id, secret227 `228 var vcs vcsRaw229 if err := tx.QueryRowContext(ctx, query,230 create.CreatorID,231 create.CreatorID,232 create.Name,233 create.Type,234 create.InstanceURL,235 create.APIURL,236 create.ApplicationID,237 create.Secret,238 ).Scan(239 &vcs.ID,240 &vcs.CreatorID,241 &vcs.CreatedTs,242 &vcs.UpdaterID,243 &vcs.UpdatedTs,244 &vcs.Name,245 &vcs.Type,246 &vcs.InstanceURL,247 &vcs.APIURL,248 &vcs.ApplicationID,249 &vcs.Secret,250 ); err != nil {251 if err == sql.ErrNoRows {252 return nil, common.FormatDBErrorEmptyRowWithQuery(query)253 }254 return nil, FormatError(err)255 }256 return &vcs, nil257}258func findVCSImpl(ctx context.Context, tx *Tx, find *api.VCSFind) ([]*vcsRaw, error) {259 // Build WHERE clause.260 where, args := []string{"1 = 1"}, []interface{}{}261 if v := find.ID; v != nil {262 where, args = append(where, "id = $1"), append(args, *v)263 }264 rows, err := tx.QueryContext(ctx, `265 SELECT266 id,267 creator_id,268 created_ts,269 updater_id,270 updated_ts,271 name,272 type,273 instance_url,274 api_url,275 application_id,276 secret277 FROM vcs278 WHERE `+strings.Join(where, " AND "),279 args...,280 )281 if err != nil {282 return nil, FormatError(err)283 }284 defer rows.Close()285 // Iterate over result set and deserialize rows into list.286 var list []*vcsRaw287 for rows.Next() {288 var vcs vcsRaw289 if err := rows.Scan(290 &vcs.ID,291 &vcs.CreatorID,292 &vcs.CreatedTs,293 &vcs.UpdaterID,294 &vcs.UpdatedTs,295 &vcs.Name,296 &vcs.Type,297 &vcs.InstanceURL,298 &vcs.APIURL,299 &vcs.ApplicationID,300 &vcs.Secret,301 ); err != nil {302 return nil, FormatError(err)303 }304 list = append(list, &vcs)305 }306 if err := rows.Err(); err != nil {307 return nil, FormatError(err)308 }309 return list, nil310}311// patchVCSImpl updates a vcs by ID. Returns the new state of the vcs after update.312func patchVCSImpl(ctx context.Context, tx *Tx, patch *api.VCSPatch) (*vcsRaw, error) {313 // Build UPDATE clause.314 set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}315 if v := patch.Name; v != nil {316 set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)317 }318 if v := patch.ApplicationID; v != nil {319 set, args = append(set, fmt.Sprintf("application_id = $%d", len(args)+1)), append(args, *v)320 }321 if v := patch.Secret; v != nil {322 set, args = append(set, fmt.Sprintf("secret = $%d", len(args)+1)), append(args, *v)323 }324 args = append(args, patch.ID)325 var vcs vcsRaw326 // Execute update query with RETURNING....
snapshots.go
Source:snapshots.go
...17 revertCommitHeadBase *[2]*string18 commitMessage string19}20type SnapshotOption func(*SnapshotOptions)21func WithPatchIDsFilter(patchIDs []string) SnapshotOption {22 return func(opts *SnapshotOptions) {23 if opts.patchIDsFilter == nil {24 opts.patchIDsFilter = new([]string)25 }26 *opts.patchIDsFilter = append(*opts.patchIDsFilter, patchIDs...)27 }28}29func WithRevert(head string, base *string) SnapshotOption {30 return func(opts *SnapshotOptions) {31 opts.revertCommitHeadBase = &[2]*string{&head, base}32 }33}34func WithCommitMessage(msg string) SnapshotOption {35 return func(opts *SnapshotOptions) {36 opts.commitMessage = msg37 }38}39func snapshotOptions(opts ...SnapshotOption) *SnapshotOptions {40 options := &SnapshotOptions{}41 for _, applyOption := range opts {42 applyOption(options)43 }44 return options45}46func snapshotPatchIDs(logger *zap.Logger, repo vcs.RepoGitReader, options *SnapshotOptions) ([]string, error) {47 if options.patchIDsFilter != nil {48 return *options.patchIDsFilter, nil49 }50 return allPatchIDs(logger, repo)51}52func allPatchIDs(logger *zap.Logger, repo vcs.RepoGitReader) ([]string, error) {53 diffs, err := repo.CurrentDiffNoIndex()54 if err != nil {55 return nil, fmt.Errorf("failed to get current diff: %w", err)56 }57 defer diffs.Free()58 differ := unidiff.NewUnidiff(unidiff.NewGitPatchReader(diffs), logger).WithExpandedHunks()59 fileDiffs, err := differ.Decorate()60 if err != nil {61 return nil, fmt.Errorf("failed to build diffs: %w", err)62 }63 var patchIDs []string64 for _, d := range fileDiffs {65 for _, h := range d.Hunks {66 patchIDs = append(patchIDs, h.ID)67 }68 }69 return patchIDs, nil70}71func SnapshotOnViewRepo(ctx context.Context, logger *zap.Logger, repo vcs.RepoReaderGitWriter, codebaseID codebases.ID, snapshotID snapshots.ID, signature git.Signature, opts ...SnapshotOption) (string, error) {72 start := time.Now()73 options := snapshotOptions(opts...)74 if snapshotID == "" {75 return "", errors.New("snapshotID is not set")76 }77 if options.revertCommitHeadBase != nil {78 return "", errors.New("expected revertCommitID to be nul, was set")79 }80 decoratedLogger := logger.With(81 zap.String("codebase_id", codebaseID.String()),82 zap.Stringer("snapshot_id", snapshotID),83 zap.String("repo_path", repo.Path()),84 )85 preCommit, err := repo.HeadCommit()86 if err != nil {87 return "", fmt.Errorf("failed to find current head: %w", err)88 }89 defer preCommit.Free()90 patchIDs, err := snapshotPatchIDs(decoratedLogger, repo, options)91 if err != nil {92 return "", err93 }94 var snapshotCommitID string95 decoratedLogger.Info("creating snapshot", zap.Int("patch_count", len(patchIDs)))96 commitMessage := fmt.Sprintf("snapshot-%d", time.Now().Unix())97 if options.commitMessage != "" {98 commitMessage = options.commitMessage99 }100 // If no patches are specified, create a snapshot of the entire view ("git add -a")101 if len(patchIDs) == 0 {102 snapshotCommitID, err = repo.AddAndCommitWithSignature(commitMessage, signature)103 } else {104 snapshotCommitID, err = vcs_change.CreateChangeFromPatchesOnRepo(ctx, decoratedLogger, repo, codebaseID, patchIDs, commitMessage, signature)105 }106 if err != nil {107 return "", fmt.Errorf("failed to make snapshot: %w", err)108 }109 decoratedLogger.Info("snapshot creation duration", zap.Duration("duration", time.Since(start)))110 err = repo.ResetMixed(preCommit.Id().String())111 if err != nil {112 return "", fmt.Errorf("failed to restore to workspace: %w", err)113 }114 // Push to upstream115 branchName := branchName(snapshotID)116 if err := repo.CreateNewBranchAt(branchName, snapshotCommitID); err != nil {117 return "", fmt.Errorf("failed to create branch at snapshot branchName=%s snapshotCommitID=%s: %w", branchName, snapshotCommitID, err)118 }119 if err := repo.Push(decoratedLogger, branchName); err != nil {120 return "", fmt.Errorf("failed to push snapshot branch branchName=%s snapshotCommitID=%s: %w", branchName, snapshotCommitID, err)121 }122 return snapshotCommitID, nil123}124func SnapshotOnViewRepoWithRevert(repo vcs.RepoWriter, logger *zap.Logger, snapshotID snapshots.ID, opts ...SnapshotOption) (string, error) {125 if snapshotID == "" {126 return "", errors.New("snapshotID is not set")127 }128 options := snapshotOptions(opts...)129 if options.revertCommitHeadBase == nil {130 return "", errors.New("expected revertCommitID to be set, got null")131 }132 hb := *options.revertCommitHeadBase133 // hb[0] is the "head" the change that's going to be the new base of the workspace134 // hb[1] is the "base" (the parent change of the "head") and is optional. If it's nil, diff against the root of the codebase.135 if hb[0] == nil {136 return "", errors.New("revertCommitHeadBase[0] (the head) is nil")137 }138 head := *hb[0]139 base := hb[1]140 if err := repo.CreateAndCheckoutBranchAtCommit(head, fmt.Sprintf("snapshot-pre-revert-%s", snapshotID)); err != nil {141 return "", fmt.Errorf("failed to create pre-revert branch: %w", err)142 }143 var diff *git.Diff144 var err error145 if base == nil {146 diff, err = repo.DiffRootToCommit(head)147 } else {148 diff, err = repo.DiffCommits(head, *base)149 }150 if err != nil {151 return "", fmt.Errorf("failed to create reversed diff: %w", err)152 }153 patches, err := unidiff.NewUnidiff(unidiff.NewGitPatchReader(diff), logger).PatchesBytes()154 if err != nil {155 return "", fmt.Errorf("failed to get patches: %w", err)156 }157 if err := repo.ApplyPatchesToWorkdir(patches); err != nil {158 return "", fmt.Errorf("failed to apply patches: %w", err)159 }160 snapshotCommitID, err := repo.AddAndCommit(fmt.Sprintf("snapshot-%d", time.Now().Unix()))161 if err != nil {162 return "", fmt.Errorf("failed to commit snapshot: %w", err)163 }164 err = repo.ResetMixed(*hb[0])165 if err != nil {166 return "", fmt.Errorf("failed to restore to workspace: %w", err)167 }168 branchName := branchName(snapshotID)169 // Push to upstream170 if err := repo.CreateNewBranchAt(branchName, snapshotCommitID); err != nil {171 return "", fmt.Errorf("failed to create branch at snapshot branchName=%s snapshotCommitID=%s: %w", branchName, snapshotCommitID, err)...
remove.go
Source:remove.go
...5 "getsturdy.com/api/pkg/unidiff/lfs"6 "getsturdy.com/api/vcs"7 "go.uber.org/zap"8)9func RemoveWithPatches(logger *zap.Logger, patches [][]byte, patchIDs ...string) func(vcs.RepoWriter) error {10 return func(r vcs.RepoWriter) error {11 return remove(r, logger, unidiff.NewBytesPatchReader(patches), patchIDs...)12 }13}14func Remove(logger *zap.Logger, patchIDs ...string) func(vcs.RepoWriter) error {15 return func(r vcs.RepoWriter) error {16 currentDiff, err := r.CurrentDiff()17 if err != nil {18 return err19 }20 defer currentDiff.Free()21 return remove(r, logger, unidiff.NewGitPatchReader(currentDiff), patchIDs...)22 }23}24func remove(r vcs.RepoWriter, logger *zap.Logger, patchReader unidiff.PatchReader, patchIDs ...string) error {25 lfsFilter, err := lfs.NewIgnoreLfsSmudgedFilter(r)26 if err != nil {27 return err28 }29 binaryDiffs, nonBinaryDiffs, err := unidiff.NewUnidiff(patchReader, logger).30 WithExpandedHunks().31 WithHunksFilter(patchIDs...).32 WithInverter().33 WithFilterFunc(lfsFilter).34 DecorateSeparateBinary()35 if err != nil {36 return err37 }38 var nonBinaryPatches [][]byte39 for _, diff := range nonBinaryDiffs {40 if diff.IsNew || diff.IsDeleted {41 binaryDiffs = append(binaryDiffs, diff)42 continue43 }44 for _, hunk := range diff.Hunks {45 nonBinaryPatches = append(nonBinaryPatches, []byte(hunk.Patch))46 }47 }48 if err := r.ApplyPatchesToWorkdir(nonBinaryPatches); err != nil {49 return fmt.Errorf("failed to add inverted patches: %w", err)50 }51 for _, binDiff := range binaryDiffs {52 // The status has been inverted from what the user is experiencing.53 switch {54 case binDiff.IsDeleted:55 if err := r.CheckoutFile(binDiff.OrigName); err != nil {56 return fmt.Errorf("failed to reset binary file (was deleted): %w", err)57 }58 case binDiff.IsNew:59 if err := r.DeleteFile(binDiff.NewName); err != nil {60 return fmt.Errorf("failed to delete binary file (was new): %w", err)61 }62 case !binDiff.IsNew && !binDiff.IsDeleted && binDiff.OrigName == binDiff.NewName: // modified in-place...
Patch
Using AI Code Generation
1import (2func main() {3 repoRoot, err := vcs.RepoRootForImportPath("code.google.com/p/go.tools", false)4 if err != nil {5 log.Fatal(err)6 }7 repo, err := vcs.NewRepoRoot(repoRoot)8 if err != nil {9 log.Fatal(err)10 }11 err = repo.Patch(os.Stdout, "go.tools", "9b9c7c1d2d01", "HEAD")12 if err != nil {13 log.Fatal(err)14 }15}16@@ -23,7 +23,7 @@ import (
Patch
Using AI Code Generation
1import (2func main() {3 r, err := git.PlainOpen("test")4 if err != nil {5 log.Fatal(err)6 }7 w, err := r.Worktree()8 if err != nil {9 log.Fatal(err)10 }11 err = w.Checkout(&git.CheckoutOptions{12 Hash: plumbing.NewHash("b8e471f58bcbca63b07bda20e428190409c2db47"),13 })14 if err != nil {15 log.Fatal(err)16 }17 patch, err := w.Patch("test.txt")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Println(patch)22}
Patch
Using AI Code Generation
1import (2func main() {3 wd, err := os.Getwd()4 if err != nil {5 log.Fatal(err)6 }7 if err != nil {8 log.Fatal(err)9 }10 if err != nil {11 log.Fatal(err)12 }13 relPath, err := filepath.Rel(repoRootPath, wd)14 if err != nil {15 log.Fatal(err)16 }17 if err != nil {18 log.Fatal(err)19 }20 if err != nil {21 log.Fatal(err)22 }23 if err != nil {24 log.Fatal(err)25 }26 fmt.Printf("Working directory: %s27 fmt.Printf("Working directory as a url: %s28 fmt.Printf("Working directory as a vcs repository: %s29 fmt.Printf("Root path of the repository: %s30 fmt.Printf("Relative path of the current working directory inside
Patch
Using AI Code Generation
1import (2func main() {3 v, err := vcs.NewVCS("git")4 if err != nil {5 fmt.Println(err)6 }7 patches, err := v.Patch("
Patch
Using AI Code Generation
1import (2func main() {3 v := vcs.NewVcs()4 f := vcs.NewFile("file1.txt", "Hello")5 v.AddFile(f)6 f = vcs.NewFile("file2.txt", "World")7 v.AddFile(f)8 f = vcs.NewFile("file3.txt", "!")9 v.AddFile(f)10 f = vcs.NewFile("file4.txt", "!")11 v.AddFile(f)12 f = vcs.NewFile("file5.txt", "!")13 v.AddFile(f)14 f = vcs.NewFile("file6.txt", "!")15 v.AddFile(f)16 f = vcs.NewFile("file7.txt", "!")17 v.AddFile(f)18 f = vcs.NewFile("file8.txt", "!")19 v.AddFile(f)20 f = vcs.NewFile("file9.txt", "!")21 v.AddFile(f)22 f = vcs.NewFile("file10.txt", "!")23 v.AddFile(f)24 f = vcs.NewFile("file11.txt", "!")25 v.AddFile(f)26 f = vcs.NewFile("file12.txt", "!")27 v.AddFile(f)28 f = vcs.NewFile("file13.txt", "!")29 v.AddFile(f)30 f = vcs.NewFile("file14.txt", "!")
Patch
Using AI Code Generation
1import (2func main() {3 r, err := vcs.RepoRootForImportPath("golang.org/x/tools", true)4 if err != nil {5 fmt.Println(err)6 }7 vcs := vcs.ByCmd(r.VCS.Cmd)8 if vcs == nil {9 fmt.Println("vcs not found")10 }11 diff, err := vcs.Patch(r.Repo, "go/vcs/vcs.go", "a9b6e2d6f0e6")12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println(diff)16}
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!!