File: Url.cpp

package info (click to toggle)
storm-lang 0.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 52,028 kB
  • sloc: ansic: 261,471; cpp: 140,432; sh: 14,891; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (645 lines) | stat: -rw-r--r-- 14,137 bytes parent folder | download
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
#include "stdafx.h"
#include "Url.h"
#include "Str.h"
#include "StrBuf.h"
#include "CloneEnv.h"
#include "Protocol.h"
#include "Serialization.h"
#include "SerializationUtils.h"
#include "Core/Convert.h"
#include "Core/Exception.h"

#if defined(WINDOWS)
#include <Shlobj.h>
#pragma comment (lib, "Shell32.lib")
#endif

namespace storm {

	static inline bool isDot(const wchar *str) {
		return str[0] == '.' && str[1] == '\0';
	}

	static inline bool isParent(const wchar *str) {
		return str[0] == '.' && str[1] == '.' && str[2] == '\0';
	}

	static inline bool separator(wchar c) {
		return (c == '/') || (c == '\\');
	}

	// Make sure 'str' do not contain any forbidden characters, and is not empty.
	static void validate(Str *str) {
		if (str->empty())
			throw new (str) InvalidName();

		for (const wchar *s = str->c_str(); *s; s++) {
			// Now, we only disallow separators in parts.
			if (separator(*s))
				throw new (str) InvalidName(str);
		}
	}

	static void validate(Array<Str *> *data) {
		for (Nat i = 0; i < data->count(); i++)
			validate(data->at(i));
	}

	static Array<Str *> *simplify(Array<Str *> *parts) {
		Array<Str *> *result = new (parts) Array<Str *>();
		result->reserve(parts->count());

		for (Nat i = 0; i < parts->count(); i++) {
			Str *p = parts->at(i);
			if (isDot(p->c_str())) {
				// Ignore it.
			} else if (isParent(p->c_str()) && result->any() && !isParent(result->last()->c_str())) {
				result->remove(result->count() - 1);
			} else {
				result->push(p);
			}
		}

		return result;
	}

	static void simplifyInplace(Array<Str *> *&parts) {
		for (Nat i = 0; i < parts->count(); i++) {
			Str *p = parts->at(i);
			if (isDot(p->c_str()) || isParent(p->c_str())) {
				parts = simplify(parts);
				return;
			}
		}
	}

	Url::Url() : flags(nothing) {
		parts = new (this) Array<Str *>();
		proto = new (this) RelativeProtocol();
	}

	Url::Url(Protocol *p, Array<Str *> *parts) : proto(p), parts(parts), flags(nothing) {
		dbg_assert(p, L"Need a protocol!");
		validate(this->parts);
		simplifyInplace(this->parts);
	}

	Url::Url(Array<Str *> *parts) : proto(new (engine()) RelativeProtocol()), parts(parts), flags(nothing) {
		validate(this->parts);
		simplifyInplace(this->parts);
	}

	Url::Url(Protocol *p, Array<Str *> *parts, UrlFlags flags) : proto(p), parts(parts), flags(flags) {
		dbg_assert(p, L"Need a protocol!");
		validate(this->parts);
		simplifyInplace(this->parts);
	}

	Url::Url(Array<Str *> *parts, UrlFlags flags) : proto(new (engine()) RelativeProtocol()), parts(parts), flags(flags) {
		validate(this->parts);
		simplifyInplace(this->parts);
	}

	void Url::toS(StrBuf *to) const {
		*to << proto;

		if (parts->count() > 0)
			*to << parts->at(0);

		for (Nat i = 1; i < parts->count(); i++)
			*to << L"/" << parts->at(i);

		if (flags & isDir)
			*to << L"/";
	}

	Url::Url(ObjIStream *from) {
		// Read data here so that we can initialize Url later.
		proto = (Protocol *)Protocol::read(from);
		parts = Serialize<Array<Str *> *>::read(from);
		flags = UrlFlags(Serialize<Nat>::read(from));
		from->end();
	}

	SerializedType *Url::serializedType(EnginePtr e) {
		SerializedStdType *t = serializedStdType<Url>(e.v);
		t->add(S("protocol"), StormInfo<Protocol>::type(e.v));
		t->add(S("parts"), StormInfo<Array<Str *>>::type(e.v));
		t->add(S("flags"), StormInfo<Nat>::type(e.v));
		return t;
	}

	Url *Url::read(ObjIStream *from) {
		return from->readClass<Url>();
	}

	void Url::write(ObjOStream *to) const {
		if (to->startClass(this)) {
			proto->write(to);
			Serialize<Array<Str *> *>::write(parts, to);
			Serialize<Nat>::write(Nat(flags), to);
			to->end();
		}
	}

	void Url::deepCopy(CloneEnv *e) {
		cloned(parts, e);
	}

	Bool Url::operator ==(const Url &o) const {
		if (!sameType(this, &o))
			return false;

		if (*proto != *o.proto)
			return false;

		if (parts->count() != o.parts->count())
			return false;

		for (Nat i = 0; i < parts->count(); i++) {
			if (!proto->partEq(parts->at(i), o.parts->at(i)))
				return false;
		}

		return true;
	}

	Nat Url::hash() const {
		Nat r = 5381;
		for (Nat i = 0; i < parts->count(); i++) {
			r = ((r << 5) + r) + proto->partHash(parts->at(i));
		}
		return r;
	}

	Url *Url::withProtocol(Protocol *p) const {
		Url *out = copyShallow();
		out->proto = p;
		return out;
	}

	Array<Str *> *Url::getParts() const {
		return new (this) Array<Str *>(*parts);
	}

	Url *Url::copyDeep() const {
		Url *copy = copyShallow();
		copy->deepCopy(new (this) CloneEnv());
		return copy;
	}

	Url *Url::copyShallow() const {
		return new (this) Url(*this);
	}

	Url *Url::push(Str *p) const {
		validate(p);

		Url *c = copyDeep();
		if (p->empty())
			return c;

		c->parts->push(p);
		simplifyInplace(c->parts);
		c->flags &= ~isDir;
		return c;
	}

	Url *Url::operator /(Str *p) const {
		return push(p);
	}

	Url *Url::pushDir(Str *p) const {
		validate(p);

		Url *c = copyDeep();
		if (p->empty())
			return c;

		c->parts->push(p);
		simplifyInplace(c->parts);
		c->flags |= isDir;
		return c;
	}

	Url *Url::makeDir() const {
		Url *copy = copyShallow();
		copy->flags |= isDir;
		return copy;
	}

	Url *Url::makeAbsolute(Url *base) {
		if (absolute())
			return this;
		return base->push(this);
	}

	Url *Url::push(Url *url) const {
		if (url->absolute())
			throw new (this) InvalidName(url->toS());

		Url *c = copyDeep();
		for (Nat i = 0; i < url->parts->count(); i++)
			c->parts->push(url->parts->at(i));

		simplifyInplace(c->parts);
		c->flags = (flags & ~isDir) | (url->flags & isDir);
		return c;
	}

	Url *Url::operator /(Url *p) const {
		return push(p);
	}

	Url *Url::parent() const {
		Url *copy = copyShallow();

		copy->parts = new (this) Array<Str *>();
		if (parts->any())
			for (Nat i = 0; i < parts->count() - 1; i++)
				copy->parts->push(parts->at(i));

		copy->flags |= isDir;

		return copy;
	}

	Bool Url::dir() const {
		return (flags & isDir) != nothing;
	}

	Bool Url::absolute() const {
		return proto->absolute();
	}

	Str *Url::name() const {
		if (parts->any())
			return parts->last();
		else
			return new (this) Str(L"");
	}

	static Str::Iter divideName(Str *str) {
		if (str->empty())
			return str->begin();

		Str::Iter last = str->end();
		for (Str::Iter at = str->begin(); at != str->end(); at++) {
			if (at.v() == Char(L'.'))
				last = at;
		}

		if (last == str->begin())
			last = str->end();
		return last;
	}

	Str *Url::ext() const {
		Str *n = name();
		Str::Iter d = divideName(n);
		d++;
		return n->substr(d);
	}

	Url *Url::withExt(Str *ext) const {
		Url *c = copyDeep();
		if (parts->empty())
			return c;

		// Sorry about the derefs, the + operator is intended for use in Storm...
		c->parts->last() = *(*this->title() + S(".")) + ext;
		return c;
	}

	Str *Url::title() const {
		Str *n = name();
		Str::Iter d = divideName(n);
		return n->substr(n->begin(), d);
	}

	Url *Url::relative(Url *to) {
		if (absolute() != to->absolute())
			throw new (this) UrlError(new (this) Str(S("Both paths to 'relative' must be either absolute or relative.")));

		// Different protocols, not possible...
		if (*proto != *to->proto)
			return this;

		Array<Str *> *rel = new (this) Array<Str *>();
		Str *up = new (this) Str(L"..");

		Nat equalTo = 0; // Equal up to a position
		for (Nat i = 0; i < to->parts->count(); i++) {
			if (equalTo == i) {
				if (i >= parts->count()) {
				} else if (proto->partEq(to->parts->at(i), parts->at(i))) {
					equalTo = i + 1;
				}
			}

			if (equalTo <= i)
				rel->push(up);
		}

		for (Nat i = equalTo; i < parts->count(); i++)
			rel->push(parts->at(i));

		Url *copy = copyShallow();
		copy->proto = new (this) RelativeProtocol();
		copy->parts = rel;
		return copy;
	}

	Url *Url::relativeIfBelow(Url *to) {
		if (!isBelow(to))
			return this;

		Array<Str *> *rel = new (this) Array<Str *>();
		for (Nat i = to->parts->count(); i < parts->count(); i++)
			rel->push(parts->at(i));

		Url *copy = copyShallow();
		copy->proto = new (this) RelativeProtocol();
		copy->parts = rel;
		return copy;
	}

	Bool Url::isBelow(Url *to) const {
		if (absolute() != to->absolute())
			throw new (this) UrlError(new (this) Str(S("Both paths to 'relativeIfBelow' must be either absolute or relative.")));

		// Different protocols?
		if (*proto != *to->proto)
			return false;

		// Check so that "to" is equal to "this" for all elements in "to".
		if (to->parts->count() > parts->count())
			return false;

		for (Nat i = 0; i < to->parts->count(); i++) {
			if (!proto->partEq(to->parts->at(i), parts->at(i)))
				return false;
		}

		return true;
	}

	Url *Url::updated() {
		UrlFlags f = flags;
		switch (proto->stat(this)) {
		case sNotFound:
			return this;
		case sDirectory:
			f |= isDir;
			break;
		case sFile:
			f &= ~isDir;
			break;
		}

		if (f == flags)
			return this;

		Url *copy = copyShallow();
		copy->flags = f;
		return copy;
	}

	/**
	 * Forward to the protocol.
	 */

	// Find all children URL:s.
	Array<Url *> *Url::children() {
		return proto->children(this);
	}

	// Open this Url for reading.
	IStream *Url::read() {
		return proto->read(this);
	}

	// Open this Url for writing.
	OStream *Url::write() {
		return proto->write(this);
	}

	// Does this Url exist?
	Bool Url::exists() {
		return proto->stat(this) != sNotFound;
	}

	// Create a directory.
	Bool Url::createDir() {
		return proto->createDir(this);
	}

	// Create a directory, recursive.
	Bool Url::createDirTree() {
		if (!exists()) {
			if (!parent()->createDirTree())
				return false;

			return createDir();
		} else {
			return true;
		}
	}

	// Delete.
	Bool Url::unlink() {
		return proto->unlink(this);
	}

	// Recursive delete.
	Bool Url::deleteTree() {
		Bool ok = true;
		Array<Url *> *children = this->children();
		for (Nat i = 0; i < children->count(); i++) {
			ok &= children->at(i)->deleteTree();
		}

		if (ok) {
			ok &= unlink();
		}

		return ok;
	}

	// Format.
	Str *Url::format() {
		return proto->format(this);
	}


	/**
	 * Parsing
	 */


	Url *parsePath(Str *s) {
		return parsePath(s->engine(), s->c_str());
	}

	Url *parsePathAsDir(Str *s) {
		return parsePathAsDir(s->engine(), s->c_str());
	}

	static Url *parsePathI(Engine &e, const wchar *src, UrlFlags flags) {
		if (*src == 0)
			return new (e) Url();

		Array<Str *> *parts = new (e) Array<Str *>();
		Protocol *protocol = new (e) FileProtocol();

		const wchar *start = src;
		// UNIX absolute path?
		if (separator(*start))
			start++;
		// Windows absulute path?
		else if (src[0] != 0 && src[1] == ':')
			start = src;
		// Windows network share?
		else if (separator(src[0]) && separator(src[1]))
			start = src + 2;
		// Relative path?
		else
			protocol = new (e) RelativeProtocol();

		if (*start == 0)
			return new (e) Url(protocol, parts, flags);

		const wchar *end = start;
		for (; end[1]; end++)
			;

		if (separator(*end)) {
			flags |= isDir;
			end--;
		}

		const wchar *last = start;
		for (const wchar *i = start; i < end; i++) {
			if (separator(*i)) {
				if (i > last) {
					parts->push(new (e) Str(last, i));
				}
				last = i + 1;
			}
		}
		if (end + 1 > last)
			parts->push(new (e) Str(last, end + 1));

		return new (e) Url(protocol, parts, flags);
	}

	Url *parsePath(Engine &e, const wchar *src) {
		return parsePathI(e, src, nothing);
	}

	Url *parsePathAsDir(Engine &e, const wchar *src) {
		return parsePathI(e, src, isDir);
	}

#if defined(WINDOWS)
	Url *cwdUrl(EnginePtr e) {
		DWORD written = GetCurrentDirectory(0, NULL);
		std::vector<wchar_t> buffer;
		// Loop is only necessary if another thread modifies CWD while we are getting it.
		do {
			// +1 is not really needed, just to have some margin since GetCurrentDirectory sometimes
			// returns length not including null terminator...
			buffer.resize(written + 1);
			buffer[0] = 0;
			written = GetCurrentDirectory(DWORD(buffer.size()), &buffer[0]);
		} while (written > buffer.size());

		return parsePathAsDir(e.v, &buffer[0]);
	}

	Url *userConfigUrl(Str *appName) {
		Engine &e = appName->engine();

		wchar_t tmp[MAX_PATH + 1];
		if (SHGetFolderPath(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, tmp) != S_OK)
			throw new (e) InternalError(S("Failed to retrieve the AppData folder for the current user."));

		Url *url = parsePath(e, tmp);
		url = url->pushDir(appName);
		if (!url->exists())
			url->createDir();
		return url;
	}

	Url *executableFileUrl(EnginePtr e) {
		std::vector<wchar_t> buffer(MAX_PATH + 1, 0);
		do {
			GetModuleFileName(NULL, &buffer[0], DWORD(buffer.size()));
			if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
				buffer.resize(buffer.size() * 2);
				continue;
			}
		} while (false);

		return parsePath(e.v, &buffer[0]);
	}

#elif defined(POSIX)
	Url *cwdUrl(EnginePtr e) {
		char path[PATH_MAX + 1] = { 0 };
		if (!getcwd(path, PATH_MAX))
			throw new (e.v) InternalError(S("Failed to get the current working directory."));
		return parsePathAsDir(e.v, toWChar(e.v, path)->v);
	}

	Url *userConfigUrl(Str *appName) {
		Engine &e = appName->engine();
		Url *url = null;

		const char *base = getenv("XDG_CONFIG_HOME");
		if (base && *base != '\0') {
			url = parsePath(e, toWChar(e, base)->v);
		} else {
			const char *home = getenv("HOME");
			if (home == null)
				throw new (e) InternalError(S("Failed to find the current user's HOME directory."));
			url = parsePath(e, toWChar(e, home)->v);
			url = url->pushDir(new (e) Str(S(".config")));
		}

		if (!url->exists())
			url->createDir();

		url = url->pushDir(appName);

		if (!url->exists())
			url->createDir();

		return url;
	}

	Url *executableFileUrl(EnginePtr e) {
		char path[PATH_MAX + 1] = { 0 };
		ssize_t r = readlink("/proc/self/exe", path, PATH_MAX);
		if (r >= PATH_MAX || r < 0)
			throw new (e) InternalError(S("Failed to get the path of the executable."));
		return parsePath(e.v, toWChar(e.v, path)->v);
	}
#else
#error "Please implement executableFileUrl and cwdUrl for your OS!"
#endif

	Url *executableUrl(EnginePtr e) {
		Url *v = executableFileUrl(e);
		return v->parent();
	}

	Url *dbgRootUrl(Engine &e) {
#ifndef DEBUG
		WARNING(L"Using dbgRoot in release!");
#endif
		Url *v = executableUrl(e);
		return v->parent();
	}

}