File: differential.go

package info (click to toggle)
android-platform-tools 35.0.2-1~exp6
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 211,716 kB
  • sloc: cpp: 995,749; java: 290,495; ansic: 145,647; xml: 58,531; python: 39,608; sh: 14,500; javascript: 5,198; asm: 4,866; makefile: 3,115; yacc: 769; awk: 368; ruby: 183; sql: 140; perl: 88; lex: 67
file content (292 lines) | stat: -rw-r--r-- 8,184 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package controllers

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"github.com/pkg/errors"

	ent "repodiff/entities"
	"repodiff/interactors"
	"repodiff/mappers"
	"repodiff/persistence/filesystem"
	"repodiff/repositories"
)

var expectedOutputFilenames = []string{
	"project.csv",
	"commit.csv",
}

// Executes all of the differentials specified in the application config.
// While each target is executed synchronously, the differential script is already multi-threaded
// across all of the local machine's cores, so there is no benefit to parallelizing multiple differential
// targets
func ExecuteDifferentials(config ent.ApplicationConfig) error {
	err := createWorkingPath(config.OutputDirectory)
	if err != nil {
		return errors.Wrap(err, "Could not create working path")
	}

	commonManifest, err := defineCommonManifest(config)
	if err != nil {
		return err
	}

	for _, target := range config.DiffTargets {
		fmt.Printf("Processing differential from %s to %s\n", target.Upstream.Branch, target.Downstream.Branch)
		err = clearOutputDirectory(config)
		commitCSV, projectCSV, err := runPyScript(config, target)
		if err != nil {
			return errors.Wrap(err, "Error running python differential script")
		}
		err = TransferScriptOutputToDownstream(config, target, projectCSV, commitCSV, commonManifest)
		if err != nil {
			return errors.Wrap(err, "Error transferring script output to downstream")
		}
	}
	return nil
}

func defineCommonManifest(config ent.ApplicationConfig) (*ent.ManifestFile, error) {
	workingDirectory := filepath.Join(config.OutputDirectory, "common_upstream")
	if err := createWorkingPath(workingDirectory); err != nil {
		return nil, err
	}
	cmd := exec.Command(
		"bash",
		"-c",
		fmt.Sprintf(
			"repo init -u %s -b %s",
			config.CommonUpstream.URL,
			config.CommonUpstream.Branch,
		),
	)
	cmd.Dir = workingDirectory
	if _, err := cmd.Output(); err != nil {
		return nil, err
	}

	var manifest ent.ManifestFile
	err := filesystem.ReadXMLAsEntity(
		// the output of repo init will generate a manifest file at this location
		filepath.Join(workingDirectory, ".repo/manifest.xml"),
		&manifest,
	)
	return &manifest, err
}

func createWorkingPath(folderPath string) error {
	return os.MkdirAll(folderPath, os.ModePerm)
}

func printFunctionDuration(fnLabel string, start time.Time) {
	fmt.Printf("Finished '%s' in %s\n", fnLabel, time.Now().Sub(start))
}

func clearOutputDirectory(config ent.ApplicationConfig) error {
	return exec.Command(
		"/bin/sh",
		"-c",
		fmt.Sprintf("rm -rf %s/*", config.OutputDirectory),
	).Run()
}

func setupCommand(pyScript string, config ent.ApplicationConfig, target ent.DiffTarget) *exec.Cmd {
	cmd := exec.Command(
		"python",
		pyScript,
		"--manifest-url",
		target.Downstream.URL,
		"--manifest-branch",
		target.Downstream.Branch,
		"--upstream-manifest-url",
		target.Upstream.URL,
		"--upstream-manifest-branch",
		target.Upstream.Branch,
	)
	cmd.Dir = config.OutputDirectory
	return cmd
}

func runPyScript(config ent.ApplicationConfig, target ent.DiffTarget) (projectCSV string, commitCSV string, err error) {
	pyScript := filepath.Join(
		config.AndroidProjectDir,
		config.DiffScript,
	)
	outFilesBefore := filesystem.FindFnamesInDir(config.OutputDirectory, expectedOutputFilenames...)
	err = diffTarget(pyScript, config, target)
	if err != nil {
		return "", "", err
	}
	outFilesAfter := filesystem.FindFnamesInDir(config.OutputDirectory, expectedOutputFilenames...)
	newFiles := interactors.DistinctValues(outFilesBefore, outFilesAfter)
	if len(newFiles) != 2 {
		return "", "", errors.New("Expected 1 new output filent. A race condition exists")
	}
	return newFiles[0], newFiles[1], nil
}

func diffTarget(pyScript string, config ent.ApplicationConfig, target ent.DiffTarget) error {
	defer printFunctionDuration("Run Differential", time.Now())
	cmd := setupCommand(pyScript, config, target)

	displayStr := strings.Join(cmd.Args, " ")
	fmt.Printf("Executing command:\n\n%s\n\n", displayStr)

	return errors.Wrap(
		cmd.Run(),
		fmt.Sprintf(
			"Failed to execute (%s). Ensure glogin has been run or update application config to provide correct parameters",
			displayStr,
		),
	)
}

// SBL need to add test coverage here
func TransferScriptOutputToDownstream(
	config ent.ApplicationConfig,
	target ent.DiffTarget,
	projectCSVFile, commitCSVFile string,
	common *ent.ManifestFile) error {

	diffRows, commitRows, err := readCSVFiles(projectCSVFile, commitCSVFile)
	if err != nil {
		return err
	}

	manifestFileGroup, err := loadTargetManifests(config, common)
	if err != nil {
		return err
	}
	analyzedDiffRows, analyzedCommitRows := interactors.ApplyApplicationMutations(
		interactors.AppProcessingParameters{
			DiffRows:   diffRows,
			CommitRows: commitRows,
			Manifests:  manifestFileGroup,
		},
	)
	return persistEntities(target, analyzedDiffRows, analyzedCommitRows)
}

func loadTargetManifests(config ent.ApplicationConfig, common *ent.ManifestFile) (*ent.ManifestFileGroup, error) {
	var upstream, downstream ent.ManifestFile
	dirToLoadAddress := map[string]*ent.ManifestFile{
		"upstream":   &upstream,
		"downstream": &downstream,
	}

	for dir, addr := range dirToLoadAddress {
		if err := filesystem.ReadXMLAsEntity(
			filepath.Join(config.OutputDirectory, dir, ".repo/manifest.xml"),
			addr,
		); err != nil {
			return nil, err
		}
	}

	return &ent.ManifestFileGroup{
		Common:     *common,
		Upstream:   upstream,
		Downstream: downstream,
	}, nil
}

func readCSVFiles(projectCSVFile, commitCSVFile string) ([]ent.DiffRow, []ent.CommitRow, error) {
	diffRows, err := csvFileToDiffRows(projectCSVFile)
	if err != nil {
		return nil, nil, errors.Wrap(err, "Error converting CSV file to entities")
	}
	commitRows, err := CSVFileToCommitRows(commitCSVFile)
	if err != nil {
		return nil, nil, errors.Wrap(err, "Error converting CSV file to entities")
	}
	return diffRows, commitRows, nil
}

func persistEntities(target ent.DiffTarget, diffRows []ent.AnalyzedDiffRow, commitRows []ent.AnalyzedCommitRow) error {
	sourceRepo, err := repositories.NewSourceRepository()
	if err != nil {
		return errors.Wrap(err, "Error initializing Source Repository")
	}
	mappedTarget, err := sourceRepo.DiffTargetToMapped(target)
	if err != nil {
		return errors.Wrap(err, "Error mapping diff targets; a race condition is possible")
	}
	err = persistDiffRowsDownstream(mappedTarget, diffRows)
	if err != nil {
		return errors.Wrap(err, "Error persisting diff rows")
	}

	return MaybeNullObjectCommitRepository(
		mappedTarget,
	).InsertCommitRows(
		commitRows,
	)
}

func csvFileToDiffRows(csvFile string) ([]ent.DiffRow, error) {
	entities, err := filesystem.CSVFileToEntities(
		csvFile,
		func(cols []string) (interface{}, error) {
			return mappers.CSVLineToDiffRow(cols)
		},
	)
	if err != nil {
		return nil, err
	}
	return toDiffRows(entities)
}

func toDiffRows(entities []interface{}) ([]ent.DiffRow, error) {
	diffRows := make([]ent.DiffRow, len(entities))
	for i, entity := range entities {
		diffRow, ok := entity.(*ent.DiffRow)
		if !ok {
			return nil, errors.New("Error casting to DiffRow")
		}
		diffRows[i] = *diffRow
	}
	return diffRows, nil
}

func CSVFileToCommitRows(csvFile string) ([]ent.CommitRow, error) {
	entities, err := filesystem.CSVFileToEntities(
		csvFile,
		func(cols []string) (interface{}, error) {
			return mappers.CSVLineToCommitRow(cols)
		},
	)
	if err != nil {
		return nil, err
	}
	return toCommitRows(entities)
}

func toCommitRows(entities []interface{}) ([]ent.CommitRow, error) {
	commitRows := make([]ent.CommitRow, len(entities))
	for i, entity := range entities {
		commitRow, ok := entity.(*ent.CommitRow)
		if !ok {
			return nil, errors.New("Error casting to CommitRow")
		}
		commitRows[i] = *commitRow
	}
	return commitRows, nil
}

func persistDiffRowsDownstream(mappedTarget ent.MappedDiffTarget, diffRows []ent.AnalyzedDiffRow) error {
	p, err := repositories.NewProjectRepository(mappedTarget)
	if err != nil {
		return errors.Wrap(err, "Error instantiating a new project repository")
	}
	err = p.InsertDiffRows(diffRows)
	if err != nil {
		return errors.Wrap(err, "Error inserting rows from controller")
	}
	return nil
}